def load_default(self): self.Clear() try: cad.OpenXmlFile(wx.GetApp().cam_dir + "/default.tooltable", self) except: # no default file found, add 2 tools cad.AddUndoably( Tool(diameter=3.0, type=TOOL_TYPE_SLOTCUTTER, tool_number=1), self, None) cad.AddUndoably( Tool(diameter=6.0, type=TOOL_TYPE_SLOTCUTTER, tool_number=2), self, None) return
def get_zhuanlan_comment(headers, number, fp=None): tool = Tool() writer = csv.writer(fp) url_web = 'https://zhuanlan.zhihu.com/api/posts/{}/comments?limit=10&offset=' #专栏评论 base_url = url_web.format(number) + '{}' url_number = 'https://zhuanlan.zhihu.com/p/' + number #专栏文章url request = requests.get(url_number, headers=headers) soup = BeautifulSoup(request.text, 'lxml') title = soup.select('head > title') commentCount = soup.select( '#react-root > div > div > div.Layout-main.av-card.av-paddingBottom.av-bodyFont.Layout-titleImage--normal > div.PostComment > div.BlockTitle.av-marginLeft.av-borderColor.PostComment-blockTitle > span.BlockTitle-title' ) commentCount = commentCount[0].get_text().split()[0] if commentCount == '还没有评论': return all_comment_num = int(commentCount) if all_comment_num % 10 != 0: count = 1 + all_comment_num // 10 else: count = all_comment_num // 10 for i in range(count): url_contents = base_url.format(i * 10) wb_data = requests.get(url_contents, headers=headers) js = json.loads(wb_data.content) for each in js: con = tool.replace(each['content']) writer.writerow([title[0].get_text(), con]) print(title[0].get_text(), con) time.sleep(random.uniform(2, 4)) # get_zhuanlan_comment(headers,'28047189')
def accept(self): ui = self.createToolUi ui.hide() setStatus("hidden") mode = getGUIMode() if mode == "AddingToolFromIcon": self.tool = Tool(self.selectedObject) p = self.setToolProperties() self.tool.getObject().Label = ui.nameEdit.text() self.tool.setProperties(p, self.tool.getObject()) setGUIMode("None") return True elif mode == "EditingToolFromIcon": self.tool = self.selectedObject.Proxy self.tool.Label = ui.nameEdit.text() p = self.setToolProperties() self.tool.setProperties(p, self.selectedObject) setGUIMode("None") return True elif mode == "AddingToolFromGUI": p = self.setToolProperties() setGUIProperties(ui.nameEdit.text(), p) return True elif mode == "EditingToolFromGUI": p = self.setToolProperties() setGUIProperties(ui.nameEdit.text(), p) return True else: print "unexpected mode (" + mode + ")" return False
def __init__(self, baseUrl, seeLz, floorTag): self.baseUrl = baseUrl self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' self.headers = {'User-Agent' : self.user_agent, 'Content-Type':'text/html; charset=UTF-8', 'Vary':'Accept-Encoding'} self.seeLz = '?see_lz=' + str(seeLz) self.tool = Tool() self.floor = 1 self.defaultTitle = u"百度贴吧" self.floorTag = floorTag
def get_contents(headers, number, fp): tool = Tool() writer = csv.writer(fp) url_web = 'https://www.zhihu.com/api/v4/questions/{}/answers?include=data%5B*%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cupvoted_followees%3Bdata%5B*%5D.mark_infos%5B*%5D.url%3Bdata%5B*%5D.author.follower_count%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics&limit=20&sort_by=default&offset=' base_url = url_web.format(number) + '{}' url_number = 'https://www.zhihu.com/question/' + str(number) wb = requests.get(url_number, headers=headers) sp = BeautifulSoup(wb.text, 'lxml') num_sel = sp.select( '#QuestionAnswers-answers > div > div > div.List-header > h4 > span') follower = sp.select( '#root > div > main > div > div > div.QuestionHeader > div.QuestionHeader-content > div.QuestionHeader-side > div > div > div > button > div.NumberBoard-value' ) title = sp.select( '#root > div > main > div > div > div.QuestionHeader > div.QuestionHeader-content > div.QuestionHeader-main > h1' ) browsed = sp.select( '#root > div > main > div > div > div.QuestionHeader > div.QuestionHeader-content > div.QuestionHeader-side > div > div > div > div.NumberBoard-item > div.NumberBoard-value' ) if num_sel == []: return all_answer_num = int(num_sel[0].get_text().split()[0]) if all_answer_num % 20 != 0: count = 1 + all_answer_num // 20 else: count = all_answer_num // 20 for i in range(count): url_contents = base_url.format(i * 20) wb_data = requests.get(url_contents, headers=headers) js = json.loads(wb_data.content) for each in js['data']: con = tool.replace(each['content']) timestamp = each['created_time'] # 转换成localtime time_local = time.localtime(timestamp) # 转换成新的时间格式 dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) times = time_local.tm_mon + time_local.tm_mday / 100 if (times < 6.18 or times > 8.28): pass else: writer.writerow([ title[0].get_text(), follower[0].get_text(), browsed[0].get_text(), dt, con ]) print(title[0].get_text(), follower[0].get_text(), browsed[0].get_text(), dt, con) time.sleep(random.uniform(2, 4))
def load_default(self): self.ClearChildren() try: f = open(HeeksCNC.heekscnc_path + "/default_tools.txt") except: # no default file found, add 2 tools self.Add( Tool(diameter=3.0, type=TOOL_TYPE_SLOTCUTTER, tool_number=1)) self.Add( Tool(diameter=6.0, type=TOOL_TYPE_SLOTCUTTER, tool_number=2)) return import cPickle from Object import next_object_index while True: try: tool = cPickle.load(f) except: break # end of file tool.index = next_object_index next_object_index = next_object_index + 1 self.Add(tool) f.close()
def apply(self): ui = self.createTTUi if self.dirty == True: if self.selectedObject == None: obj = FreeCAD.ActiveDocument.addObject( 'App::DocumentObjectGroupPython', "ToolTable") ViewToolTable(obj.ViewObject) obj.addProperty("App::PropertyString", "ObjectType") obj.ObjectType = "ToolTable" obj.setEditorMode("ObjectType", ("ReadOnly", )) self.selectedObject = obj FreeCADGui.Selection.clearSelection() FreeCADGui.Selection.addSelection(obj) for tool in self.selectedObject.Group: FreeCAD.ActiveDocument.removeObject(tool.Name) for line in self.toolList: tool = Tool(self.selectedObject) tool.getObject().Label = line['label'] tool.setProperties(line['properties'], tool.getObject()) self.selectedObject.Label = ui.nameLE.text() self.dirty = False FreeCAD.ActiveDocument.recompute()
def get_tools_list(self, TOOL_FILE_PATH): tool_list = [] cur_tool_obj = None with open(TOOL_FILE_PATH, "r", errors='ignore', encoding='utf-8') as reader: for line in reader: line = line.strip() if (line == ""): continue tool_pattern = re.compile(TOOL) tool_id_pattern = re.compile(TOOL_ID) tool_name_pattern = re.compile(TOOL_NAME) tool_description_pattern = re.compile(TOOL_DESCR) tool_url_pattern = re.compile(TOOL_URL) tool_supp_smells_pattern = re.compile(TOOL_SUPP_SMELL) tool_supp_langs_pattern = re.compile(TOOL_SUPP_LANGS) tool_end_pattern = re.compile(TOOL_END) if (re.search(tool_pattern, line) != None): cur_tool_obj = Tool() elif (re.search(tool_end_pattern, line) != None): tool_list.append(cur_tool_obj) elif (re.search(tool_id_pattern, line) != None): cur_tool_obj.id = re.split(TOOL_ID, line)[1].strip() elif (re.search(tool_name_pattern, line) != None): cur_tool_obj.name = re.split(TOOL_NAME, line)[1].strip() elif (re.search(tool_description_pattern, line) != None): cur_tool_obj.description = re.split(TOOL_DESCR, line)[1].strip() elif (re.search(tool_url_pattern, line) != None): cur_tool_obj.url = re.split(TOOL_URL, line)[1].strip() elif (re.search(tool_supp_smells_pattern, line) != None): cur_tool_obj.supported_smells.append( re.split(TOOL_SUPP_SMELL, line)[1].strip()) elif (re.search(tool_supp_langs_pattern, line) != None): cur_tool_obj.supported_langs = re.split( TOOL_SUPP_LANGS, line)[1].strip() return tool_list
def __init__(self, labyrinth): """ initializing Game Manager """ self.labyrinth = labyrinth # player & guard positioning position_p = self.labyrinth.get_player_position() position_g = self.labyrinth.get_guard_position() self.MacGyver = Player(position_p[0], position_p[1]) self.guard = Guard(position_g[0], position_g[1]) # tools random positioning from an empty spaces list empty_spaces = self.labyrinth.get_empty_spaces() self.tools = [] self.symbols = ['E', 'N', 'T'] self.names = ['éther', 'aiguille', 'tube'] for idx, symbol in enumerate(self.symbols): tmp_pos = random.choice(empty_spaces) temp_tool = Tool(tmp_pos[0], tmp_pos[1], symbol, self.names[idx]) self.tools.append(temp_tool) empty_spaces.remove(tmp_pos) for tool in self.tools: self.labyrinth.write_symbol((tool.x, tool.y), tool.symbol)
def tool_dispatcher(tool): tid, ip = setup_log_vars() lggr = setup_local_logger(tid, ip) TOL = Tool() data = getattr(TOL, tool.lower())(request) if hasattr(current_user, 'id'): data['handle'] = current_user.id data['current_user'] = current_user o = urlparse.urlparse(request.url) data['host_url'] = urlparse.urlunparse( (URL_SCHEME, o.netloc, '', '', '', '')) t = time.time() data['today'] = time.strftime("%A %b %d, %Y ", time.gmtime(t)) if 'redirect' in data: return data else: return render_template(data['template'], data=data)
def __init__(self, labyrinth): self.labyrinth = labyrinth # Player positioning position_p = self.labyrinth.get_player_position() self.MacGyver = Player(position_p[0], position_p[1]) # GUI elements initializing pygame.init() self.screen = pygame.display.set_mode((800, 600)) self.background_image = pygame.image.load(r"img/background.png") self.ether_image = pygame.image.load(r"img/ether.png") self.guard_image = pygame.image.load(r"img/guard.png") self.macgyver_image = pygame.image.load(r"img/macgyver.png") self.needle_image = pygame.image.load(r"img/needle.png") self.tube_image = pygame.image.load(r"img/tube.png") self.wall_image = pygame.image.load(r"img/wall.png") self.win_image = pygame.image.load(r"img/win.png") self.lost_image = pygame.image.load(r"img/lost.png") self.title_image = pygame.image.load(r"img/title.png") self.etherC_image = pygame.image.load(r"img/etherC.png") self.needleC_image = pygame.image.load(r"img/needleC.png") self.tubeC_image = pygame.image.load(r"img/tubeC.png") self.clock = pygame.time.Clock() self.character_sprites_list = pygame.sprite.Group() self.tools_sprites_list = pygame.sprite.Group() self.wall_sprites_list = pygame.sprite.Group() self.macgyver_sprite = ImageSprite(self.macgyver_image) self.guard_sprite = ImageSprite(self.guard_image) self.tools_list = (ImageSprite(self.ether_image), ImageSprite(self.needle_image), ImageSprite(self.tube_image)) self.character_sprites_list.add([self.macgyver_sprite, self.guard_sprite]) self.tools_sprites_list.add(self.tools_list) # To be used when printing tool's names & icons in lateral self.start_tools_y = 200 self.start_icons_y = 200 pygame.display.set_caption("Le labyrinthe de MacGyver") # Tools random positioning from an empty spaces list empty_spaces = self.labyrinth.get_empty_spaces() self.tools = [] self.symbols = ['E', 'N', 'T'] self.names = ['Ether', 'Aiguille', 'Tube'] self.images = [self.etherC_image, self.needleC_image, self.tubeC_image] for idx, symbol in enumerate(self.symbols): tmp_pos = random.choice(empty_spaces) temp_tool = Tool(tmp_pos[0], tmp_pos[1], symbol, self.names[idx], self.images[idx]) self.tools.append(temp_tool) empty_spaces.remove(tmp_pos) for tool in self.tools: self.labyrinth.write_symbol((tool.x, tool.y), tool.symbol)
def __init__(self, CurrentLayer): self.tool = Tool(self, CurrentLayer)
def __init__(self, laby): self.laby = laby player_position = laby.get_symbol_position(Player.GAMER) self.macgyver = Player(player_position[0], player_position[1]) self.guardian = Guardian() self.tool = Tool(laby) self.mac_bag = 0 self.finish_game = 0 self.carry_on = 1 """ The constructor for Gui class. Parameters: laby (class): Access of the class Labyrinth. player_position(tuple): return the vertical and horizontal position of the player. macgyver(class): Access of the class Player. guardian(class): Access of the class Guardian. Tool(class): Access of the class tool. self.mac_bag(int): The number of tool catch by the player. self.finish_game(int): Help to open the text in of end of the game self.carry_on(int): Allow to continue or stop the game """ pygame.init() pygame.font.init() size = (900, 600) self.clock = pygame.time.Clock().tick(30) # Font self.font_text_winner = pygame.font.SysFont('Arial', 25) self.font_menu = pygame.font.SysFont('Arial', 15) self.window = pygame.display.set_mode(size) pygame.display.set_caption("Mac vs guardian") """ Init pygame. Parameters: size (class): Access of the class Labyrinth. self.font_text_winner(pygame.font.Font): return the font of the message at the end of the game. self.font_menu(pygame.font.Font): return the font of the menu. self.window(pygame.Surface): Set the window of the game. """ self.fond = pygame.image.load("gui/background.png").convert() self.wall = pygame.image.load("gui/wall.png").convert_alpha() self.ether = pygame.image.load("gui/ether.png").convert_alpha() self.needle = pygame.image.load("gui/needle.png").convert_alpha() self.pipe = pygame.image.load("gui/pipe.png").convert_alpha() self.guard = pygame.image.load("gui/guard.png").convert_alpha() # character setup self.character = pygame.image.load("gui/macgyver.png").convert() self.position_character = self.character.get_rect() """ Load image. Parameters: self.fond: Load an image from background.png file. self.wall: Load an image from wall.png file. self.ether: Load an image from ether.png file. self.needle: Load an image from needle.png file. self.pipe: Load an image from pipe.png file. self.guard: Load an image from guard.png file. self.character: Load an image from macgyver.png file. self.position_character: Returns a new rectangle covering the entire surface. """ self.store_wall_position = [] for box in self.laby.all_box(): x_wall = box[0] * 40 y_wall = box[1] * 40 self.store_wall_position.append((y_wall, x_wall)) """Find the position for all walls in graphic mode.""" self.list_gadget = [(self.tool.needle_random_position, self.needle), (self.tool.ether_random_position, self.ether), (self.tool.pipe_random_position, self.pipe)] """Find random position for the tools in graphic mode.""" self.tool.write_tool_in_laby() """Write the tools in labyrinth with this position."""
def main(plan_p, schedule_p, timing_p, batch_p, tools_p): data = Data(plan_p, schedule_p, timing_p, batch_p, tools_p) details = data.get_current_details() tools = {} for i, row in data.tools.iterrows(): tools[row['INV_NOM']] = Tool(row['INV_NOM'], plan_p, schedule_p, timing_p, batch_p, tools_p) plan = data.get_plan() dates = data.schedule.replace(0, None) dates = pd.to_datetime(dates.dropna()['DATA']) dates = dates.astype(str).values martix = Out() for day in dates: martix.add_day(tools, day) print('Start - ' + str(day) + '...') list_today = plan[plan['DATA'] == day] list_today = list_today.groupby('DET').agg('sum') list_today = data.add_total(list_today) list_today = list_today.sort_values(by=['TOOLS', 'TOTAL'], ascending=[True, True]) list_today['VALUE'] = list_today['QUANT_DAY'] * list_today['NEEDLE'] for i, detail in list_today.iterrows(): details[str(i)]['need'] += detail['QUANT_DAY'] if detail['QUANT_DAY'] <= details[str(i)]['balance']: details[str(i)]['balance'] -= detail['QUANT_DAY'] continue det = details[str(i)] max = 0 tid = 0 for tool in det['tools']: if tools[tool].time_left == 0: continue if tools[tool].time_left > max: max = tools[tool].time_left tid = tool else: continue result, num = tools[tid].add_detail(day, i) if result == 'added': # 'Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p' details[str(i)]['balance'] += details[str( i)]['plan'] - detail['QUANT_DAY'] timestamp = datetime.strptime( day + ' 08:00:00', '%Y-%m-%d %H:%M:%S') + timedelta(days=num / 24) martix.add_value(timestamp.strftime('%H:%M'), tool, day, i) continue elif result == 'n_added': break else: if num < detail['QUANT_DAY']: details[str(i)]['balance'] = detail['QUANT_DAY'] else: details[str(i)]['balance'] = num - detail['QUANT_DAY'] break for index in tools: id, debt = tools[index].recount_day() if id is not None: details[str(id)]['balance'] = debt martix.render()
output += f" {i + 2}. Exit" return output def __repr__(self): return f'Store("{self.name}", {self.departments})' # lets make some products # clothes tshirt = Clothing("Long Sleve T-Shirt", 20, "XXL", "Blue") red_shoes = Clothing("Red Running Shoe", 34, "12", "Red") # tools hammer = Tool("Ball Pane Hammer", 5, "Hammer") screw_driver = Tool("Philips Head Screw Driver", 3, "Screw Driver") # electronics televisions = Electronic("50 inch Wide Screen LCD", 400, "50w") tablet = Electronic("Android Tablet", 50, "8w") # lets create some Departments clothes_dept = Department("Clothes", [tshirt, red_shoes]) tools_dept = Department("Tools", [hammer, screw_driver]) electronics_dept = Department("Electronics", [televisions, tablet]) # instance of the Store class my_store = Store("Bobs Emporium", [clothes_dept, tools_dept, electronics_dept]) # print(repr(my_store))
resultSum = [] resultSD = [] result = [] time = [] bestR = [] bestD = 10**(20) dict = [] constk = 10 for idx in range(5): result = [] k = (idx + 1) * constk # percent = 0.1 + 0.1*idx ep = [] #get the time tools = Tool(data) start = datetime.datetime.now().timestamp() a, b, c = tools.Generic_Algorithm(k, t, percent) end = datetime.datetime.now().timestamp() time.append(end - start) for i in range(10): np.random.shuffle(data) tools = Tool(data) a, b, c, e = tools.Generic_Algorithm_Epoch(k, t, percent, epoch) ep.append(e) if b < bestD: bestR = np.copy(a) bestD = b dict = copy.deepcopy(c)
def convertTools(self): for id, tool in self.tools.items(): self.tools[id] = Tool(id, tool[0], tool[1], tool[2])