def scraping_exe(): try: today = datetime.date.today() # マスタ機種情報を取得 slotInformation = SlotInformation() slot_infos = slotInformation.getAll() for slot_info in slot_infos: search_url = slot_info["search_url"] time.sleep(2) topPageHtmlElements = Function.getAllElements(search_url) machineUrlList = Function.getMachineUrlList(topPageHtmlElements) for machineUrl in machineUrlList: dataPageHtmlElements = Function.getAllElements(machineUrl) # 登録データ定義 bonusDataDict = { "id": None, "BB": 0, "RB": 0, "BB_ave": 0, "RB_ave": 0, "total_game": 0, "total_ave": 0, "class": 0, "data_time": today, "user_id": 1, "store_id": 1, "slot_id": slot_info["id"], "guess_class1": 0, "guess_class2": 0, "guess_class3": 0, "guess_class4": 0, "guess_class5": 0, "guess_class6": 0, } # 当日データ取得 bonusDataDict = Function.getBonusData( dataPageHtmlElements, bonusDataDict) # 台番号取得できなかったらスキップ if not bonusDataDict['id']: continue # 設定判別 bonusDataDict = Function.setting_judgement( slot_info, bonusDataDict) # データベース登録 slotGameData = SlotGameData() slotGameData.insertSlotGameData(slot_info["id"], bonusDataDict) except Exception as e: print('[heroku][slot_scraping][scraping_exe]失敗しました。' + str(e))
def __init__(self, table): """ Args: table: A n-dimension tensor that maps a set of assignment to a value. """ Function.__init__(self) self.table = table
def __init__(self, sig): """ Args: sig: The variance value. """ Function.__init__(self) self.sig = sig
class App: def __init__(self, args=None): self.func = None self.image = None self.parser = argparse.ArgumentParser() self.parser.add_argument( 'function', help= 'Function you wish to work with. Must be holomorphic on D(0,1) as a function of z.' ) self.parser.add_argument( 'degree', help='Degree to which we shall expand the function.') self.parser.add_argument( 'a', help= 'Base point for expansion. Do not exceed the open unit circle, results may be non-sense.' ) self.parser.add_argument( 'z0', help='Point at which to perform spectral evaluation.') def main(self): args = self.parser.parse_args(sys.argv[1:]) self.func = Function(args.function) self.renderer = Renderer() self.func.expand_eval(complex(args.z0), complex(args.a)) points = [] for i in range(0, int(args.degree)): points.append(self.func.next_term()) self.renderer.addPoints(points) filename = 'spectralEval' + args.function + '.png' self.renderer.image.save('output.png', 'PNG') print('Saved .png to this directory.') self.renderer.dump() print('Dumped points as .json file in this directory.')
def main(): root = Tk() root.geometry("800x600+0+0")#w x h + posx + posy function = Function() app = GUI(root, function) function.addGUI(app) root.mainloop()
def test_get_by_name_and_file_id_returns_first_if_multiple_same_name( with_database): file = SourceFile.get_by_file_path("one.r") first = Function.get_by_name("doMath") duplicate = Function.create("doMath", file.fileID) assert duplicate.functionID == first.functionID
def test_give_proper_value_third_degree(self): sut = Function() sut.coefficients.clear() sut.coefficients.append(3) sut.coefficients.append(4) sut.coefficients.append(5) self.assertEqual(sut.get_value(2), 25)
def createSerializationFunction(self, cls, serialize_type): function = Function() function.name = 'serialize' if serialize_type == SERIALIZATION else 'deserialize' for func in cls.functions: if func.name == function.name: return function.args = [[self.getSerialiationFunctionArgs(), None]] if cls.behaviors: if self.serialize_format == 'xml': function.operations.append('parent::{}($xml);'.format(function.name)) else: function.operations.append('parent::{}($json);'.format(function.name)) for obj in cls.members: if obj.is_runtime: continue if obj.is_static: continue if obj.is_const and not obj.is_link: continue line = self._buildSerializeOperation(obj.name, obj.type, obj.initial_value, serialize_type, obj.template_args, obj.is_pointer, is_link=obj.is_link) function.operations.append(line) cls.functions.append(function)
def __init__(self, mu, sig): """ Args: mu: The mean vector (must be 1 dimensional). sig: The covariance matrix (must be 2 dimensional). """ Function.__init__(self) self.set_parameters(mu, sig)
def test_create_mapping_between_test_and_function(with_database): file = SourceFile.get_by_file_path("one.r") testCase = TestCase.create("apoijwdapoijwd", file.fileID) function = Function.create("paoiwdjaowidj", file.fileID) testCase.create_mapping(function) function = Function.get_by_name_and_file_id(function.name, file.fileID) assert testCase.name in function.testCaseNames
def create_shared_method(self): function = Function() function.name = 'shared' function.args.append(['', '']) function.return_type = '{}&:const'.format(self.name) function.is_static = True function.operations.append('static {} instance;'.format(self.name)) function.operations.append('return instance;') self.functions.append(function)
def _generate_setters_function(self, parser): function = Function() function.name = constants.CLASS_FUNCTION_SET_PROPERTY function.return_type = 'void' function.args.append(['name', 'string']) function.args.append(['value', 'string']) add_function = False for member in self.members: if member.is_pointer: continue if member.is_runtime: continue if member.is_static: continue if member.is_const: continue supported_types = { 'string': 'std::string', 'int': 0, 'float': 0, 'bool': 0 } if member.type in supported_types: type_ = member.type type_ = type_ if supported_types[ type_] == 0 else supported_types[type_] op = 'if(name == "{0}") \n{2}\nthis->{0} = strTo<{1}>(value);\n{3}' if len(function.operations): op = 'else ' + op function.operations.append( op.format(member.name, type_, '{', '}')) add_function = True override = False if self.behaviors: for class_ in self.behaviors: if class_.is_abstract: continue for func in class_.functions: equal = func.name == function.name and func.get_return_type( ).type == function.get_return_type().type for i, arg in enumerate(func.args): equal = equal and func.args[i][1] == function.args[i][1] if equal: override = True if len(function.operations): op = 'else \n{1}\n{0}::{3}(name, value);\n{2}' else: op = '{0}::{3}(name, value);' function.operations.append( op.format(class_.name, '{', '}', constants.CLASS_FUNCTION_SET_PROPERTY)) break if add_function or not override: self.functions.append(function)
def run(self): # vertex input print("Please enter list of NODES separated by comma(No less than 3 nodes)") isTrue = True while isTrue: Text = input("Node: ") self.temp = Text.split(",") counter = 0 for x in self.temp: self.vertexObjectList.append(Node(x)) counter += 1 if counter < 3: print("Nodes num must be greater than three") elif counter >= 3: isTrue = False for x in self.temp: self.vertexNameList.append(x) isTrue = True while isTrue: userInput = input("Please input the start Node, finish Node and distance between them separated by comma: ") self.edgeInnerNameList = userInput.split(",") counter = 0 for x in self.edgeInnerNameList: if self.edgeInnerNameList[0] and self.edgeInnerNameList[1] in self.vertexNameList: counter += 1 else: print("Node not found in the list") if counter < 2: print("Please enter correct information") userInput2 = input("Do you want to keep enter Node? (y/n)") if userInput2 == 'n': isTrue = False self.edgeObjectList.append(Edge(self.vertexObjectList[0], self.vertexObjectList[1], int(self.edgeInnerNameList[-1]))) elif userInput2 == 'y': isTrue = True else: print("Please enter correct selection") algorithm = Function() i = 0 while i < len(self.vertexObjectList): if i > 0: for elements in self.vertexObjectList: elements.minDistance = sys.maxsize algorithm.calculateShortestPath(self.vertexObjectList[i], self.vertexObjectList, self.edgeObjectList) i += 1 j = 0 while j < len(self.vertexObjectList): self.printMatrix.append(self.vertexObjectList[j].minDistance) j += 1 printRoutingTable(self.vertexNameList, self.printMatrix)
def create_shared_method(self): function = Function() function.name = 'shared' function.args.append(['', '']) function.return_type = self.name function.is_static = True function.operations.append('if not {}.__instance:'.format(self.name)) function.operations.append(' {0}.__instance = {0}()'.format(self.name)) function.operations.append('return {}.__instance'.format(self.name)) self.functions.append(function)
def __init__(self): self.root = Tk() self.root.title("Ear - Explicit Algorithm Representation") self.mainframe = ttk.Frame(self.root, padding="3 3 12 12") self.mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) # Buttons self.state = None fbutton = ttk.Button(self.mainframe, text="Function", command=lambda: self.change_state(STATE_FUNC)) cbutton = ttk.Button(self.mainframe, text="Case", command=lambda: self.change_state(STATE_CASE)) abutton = ttk.Button(self.mainframe, text="Arrow", command=lambda: self.change_state(STATE_ARROW)) rbutton = ttk.Button(self.mainframe, text="Remove", command=lambda: self.change_state(STATE_RM)) ibutton = ttk.Button(self.mainframe, text="Import", command=self.import_event) ebutton = ttk.Button(self.mainframe, text="Export", command=self.export) fbutton.grid(column=1, row=1) cbutton.grid(column=2, row=1) abutton.grid(column=3, row=1) rbutton.grid(column=4, row=1) ibutton.grid(column=5, row=1) ebutton.grid(column=6, row=1) self.buttons = { STATE_FUNC: fbutton, STATE_CASE: cbutton, STATE_ARROW: abutton, STATE_RM: rbutton, "import": ibutton, "export": ebutton, } # Canvas self.canvas = Canvas(self.mainframe, width=600, height=600, bg="grey") # TODO the mainframe should be grey self.canvas.grid(column=1, row=2, columnspan=len(self.buttons)) self.canvas.bind("<Button-1>", self.register_position) self.canvas.bind("<B1-Motion>", self.hold_click) self.canvas.bind("<ButtonRelease-1>", self.simple_click) self.functions = [] self.cases = [] self.arrows = [] self.start = None self.n_elems = 0 # Display for child in self.mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) # Create start and end blocks d = 30 start_f = Function(self, Properties.WINDOW_WIDTH / 2, d, name="start") end_f = Function(self, Properties.WINDOW_WIDTH / 2, Properties.WINDOW_HEIGHT - d, name="end") self.functions += [start_f, end_f] self.root.mainloop()
def create_deserialize(self): function = Function() function.name = 'deserialize' function.args.append(self.get_deserialize_args()) for member in self.members: if member.type != 'map': continue pattern = self.get_deserialize_pattern() function.operations.append(pattern.format(member.name, member.template_args[1].name)) self.functions.append(function)
def create_getters(self, classes): for class_ in classes: if class_.is_storage and (class_.side == self.parser.side or class_.side == 'both'): map_name = get_data_list_name(get_data_name(class_.name)) function = Function() function.name = 'get' + class_.name function.args.append(['name', '']) function.operations.append('if not self._loaded and name not in self.{}:'.format(map_name)) function.operations.append(' from {0} import {0}'.format(class_.name)) function.operations.append(' self.{}[name] = {}()'.format(map_name, class_.name)) function.operations.append('return self.{}[name]'.format(map_name)) self.functions.append(function)
def execute(self, text): lexer = FunctionCallLexer(text) stream = CommonTokenStream(lexer) parser = FunctionCallParser(stream) statement = parser.statement().function() if (statement): function = Function(statement) tree = function.process_statement_tree() return self.function_processor.evaluate_statement_tree(tree) else: return Status.OK
def testSelection(repo): # get function names from git diff into changedCode.txt # check to see if repository is in database, if not, then exit (depends on when repository will be added) # parse changedFunctions.txt # go to database and find tests that match function names # output test names into JSON object result = Repository.get_by_path(repo) if not result: print( "No repository has been added to the database. Please specify a database, or call redrawmappings, before moving forward." ) exit(1) subprocess.call(['./getCodeChanges.sh testselection' + ' ' + result.path], shell=True) functionList = dict() testList = dict() with open('changedCode.txt', 'r') as fp: funcs = set() for line in fp.readlines(): line = line.strip() funcs.add(line) functionList['changedFunctions'] = funcs with open('changedCode.txt', 'r') as fp: functions = Function.get_all() if not functions or len(functions) == 0: print("No mappings in the database, calling redrawmappings...") redrawMappings() exit(1) tests = list() for functionName in fp.readlines(): functionName = functionName.strip() function = Function.get_by_name(functionName) if not function: print( "Function %s is not mapped in the database, calling redrawmappings..." % (functionName)) redrawMappings() exit(1) tests.extend(function.testCaseNames) testList['testToRun'] = set(tests) print(functionList) print(testList)
def add_serialization(self, class_, serialization_type): function = Function() if serialization_type == SERIALIZATION: function.is_const = True function.name = 'serialize' function.args.append( self.get_serialization_object_arg(serialization_type)) if serialization_type == DESERIALIZATION: function.name = 'deserialize' function.args.append( self.get_serialization_object_arg(serialization_type)) function.return_type = 'void' function.link() for behabior in class_.behaviors: if not behabior.is_serialized: continue operation = self.get_behavior_call_format().format( behabior.name, function.name) function.operations.append(operation) for obj in class_.members: if obj.is_runtime or obj.is_static or (obj.is_const and not obj.is_link): continue operation = self._build_serialize_object_operation( obj, serialization_type) function.operations.append(operation) class_.functions.append(function)
def main(self): args = self.parser.parse_args(sys.argv[1:]) self.func = Function(args.function) self.renderer = Renderer() self.func.expand_eval(complex(args.z0), complex(args.a)) points = [] for i in range(0, int(args.degree)): points.append(self.func.next_term()) self.renderer.addPoints(points) filename = 'spectralEval' + args.function + '.png' self.renderer.image.save('output.png', 'PNG') print('Saved .png to this directory.') self.renderer.dump() print('Dumped points as .json file in this directory.')
def eand_lsp(Xh, Yh, BestValue, BestCosts, nef, f, nPop2, ndv, LB, UB): # Initialization nPop2, ndv = int(nPop2), int(ndv) Mh = np.zeros((nPop2, ndv), dtype=int) # Mutated values from local search MYh = np.zeros((nPop2, 1), dtype=float) # Evaluation of Mh Delta = np.zeros(((nPop2 - 1), ndv), dtype=float) # Delta matrix (Eq. 8) ''' Local mutation ''' n = np.random.permutation(range(2)) Mh[0] = Xh[0] + Xh[0] * (np.random.uniform(0, 1)) * ( (-1)**n[0]) # First element mutation (Eq. 10) Mh[0] = np.round(Mh[0]) # Handling integer variables Mh[0] = eand_limit(Mh[0], LB, UB) # Constraint handling procedure (Eq. 7) MYh[0] = Function(Mh[0]) # Evaluate MYh = f(Mh) nef += 1 # Update the number of evaluation functions if MYh[0] < BestValue: # Update the best overall evaluation value BestValue = MYh[0] f = nef # Number of evaluation functions to reach the fitness known value BestCosts[0, (nef - 1)] = BestValue # Save the best value over the evaluations for i in range(nPop2 - 1): Delta[i] = Xh[0] - Xh[i + 1] # Delta matrix (Eq. 8) for j in range(ndv): # Restriction condition (Eq. 9) if Delta[i, j] == 0: Delta[i, j] = 1 n = np.random.permutation(range(2)) Mh[i + 1] = Xh[i + 1] + Delta[i] * (np.random.uniform(0, 1)) * ( (-1)**n[0]) # Other elements mutation (Eq. 11) Mh[i + 1] = np.round(Mh[i + 1]) # Handling integer variables Mh[i + 1] = eand_limit(Mh[i + 1], LB, UB) # Constraint handling procedure (Eq. 7) MYh[i + 1] = Function(Mh[i + 1]) # Evaluate MYh = f(Mh) nef += 1 # Update the number of evaluation functions if MYh[i + 1] < BestValue: # Update the best overall evaluation value BestValue = MYh[i + 1] f = nef # Number of evaluation functions to reach the fitness known value BestCosts[0, (nef - 1)] = BestValue # Save the best value over the evaluations ''' Local selection technique ''' Xh, Yh = eand_local_selection(Xh, Yh, Mh, MYh, nPop2, ndv) return Xh, Yh, BestValue, BestCosts, nef, f
def buildIf(self): self.delmov() sline = self.current_token.start.line if(self.current_token.start.line != sline): throw(ExpectedValue(self.current_token)) return if self.current_token.tok == T_ID: self.checkDefn() self.update() multitok = False definitionTokens = [self.current_token] self.delmov() while(self.current_token.start.line == sline): if self.current_token.tok == T_ID: self.checkDefn() self.update() self.current_token.start.line = sline continue definitionTokens.append(self.current_token) self.delmov() tmpfn = Function("empty", [], VOID, config.GlobalCompiler, []) value = determineConstexpr(False, definitionTokens, tmpfn) if value.accessor == 0: self.skipIfbody() else: pass
def print_approximation_table(function_table: dict, f: Function, function_type: str, decimals=3): x = np.around(list(function_table.keys()), decimals) y = np.around(list(function_table.values()), decimals) approximated_y = np.around( list( round(f.function(x), decimals) for x in function_table.keys()), decimals) logging.info(function_type) approximation_table = PrettyTable() approximation_table.field_names = [ "", *(i for i in range(1, len(y) + 1)) ] approximation_table.add_row(["x", *x]) approximation_table.add_row(["y", *y]) approximation_table.add_row([f.text, *approximated_y]) approximation_table.add_row([ "E", *(round(approximated_y[i] - y[i], decimals) for i in range(len(y))) ]) logging.info(approximation_table)
def MAKE_CLOSURE(self, argc): name = self.pop() closure, code = self.popn(2) defaults = self.popn(argc) globs = self.frame.f_globals func = Function(name, code, globs, defaults, closure, self) self.push(func)
def MAKE_FUNCTION(self, flags): name = self.pop() code = self.pop() defaults = self.popn(flags) globs = self.frame.f_globals func = Function(name, code, globs, defaults, None, self) self.push(func)
def byte_MAKE_FUNCTION(self, argc): name = self.pop() code = self.pop() defaults = self.popn(argc) globs = self.frame.f_globals fn = Function(name, code, globs, defaults, None, self) self.push(fn)
def main(): x_ = [] d_ = [] dt = 0.01 func = Function() x = 0 while x < 10: x_.append(x) function = func.savings(x, 3) d_.append(function) x += dt; plt.plot(x_, d_) plt.show()
def find_an_approximation(self, function_table: dict) -> Function: try: SLNX = sum(log(x) for x in function_table.keys()) SLNXX = sum(log(x) * log(x) for x in function_table.keys()) SLNY = sum(log(y) for y in function_table.values()) SLNXY = sum(log(x) * log(y) for x, y in function_table.items()) n = len(function_table) except ValueError: return None try: b, a = self.solve_matrix22([[n, SLNX], [SLNX, SLNXX]], [SLNY, SLNXY]) if a is None: return None a = exp(a) fun = lambda x: a * (x**b) s = sum( (fun(x) - function_table[x])**2 for x in function_table.keys()) root_mean_square_deviation = sqrt(s / n) f = Function(fun, f'ф = {round(a, 3)}*x^({round(b, 3)})', s, root_mean_square_deviation) self.print_approximation_table(function_table, f, self.function_type) return f except TypeError: return None
def simple_click(self, event): """If clicked on an empty space: add a function/case/arrow, Else if in state "remove", remove the function/case/arrow, Else edit the function/case. """ print("simple_click: selected is {}, moving is {}".format(self.selected, self.moving)) if self.selected is None: if self.state == STATE_FUNC: f = Function(self, event.x, event.y) if not f.cancelled: self.functions.append(f) elif self.state == STATE_CASE: c = Case(self, event.x, event.y) if not c.cancelled: self.cases.append(c) else: if self.state == STATE_RM and not self.moving: self.selected.destroy() self.start = None elif self.state == STATE_ARROW: if self.start is None: self.start = self.selected else: a = Arrow(self, self.start, self.selected) self.arrows.append(a) self.start = None elif not self.moving: self.selected.edit() self.start = None else: self.start = None self.moving = False
def buildCastOverload(self): starttok = self.current_token self.advance() t = self.compiler.checkType() self.update() if self.current_token.tok != T_OPENP: throw(ExpectedToken(self.current_token, T_OPENP)) self.advance() if self.current_token.tok != T_CLSP: throw(ExpectedToken(self.current_token, T_CLSP)) self.advance() if self.current_token.tok != T_OPENSCOPE: throw(ExpectedToken(self.current_token, T_CLSP)) self.advance() start = self.compiler.ctidx self.compiler.skipBody() end = self.compiler.ctidx body = self.compiler.currentTokens[start:end + 1] fun = Function( f"operator@{t}", [], t, self.compiler, body, memberfn=True, parentstruct=self.prototypeType, declare_token=starttok, ) self.compiler.functions.append(fun) self.prototypeType.operators[t.name] = fun self.current_token = self.compiler.currentTokens[end + 1]
def create_function(self, ctx, function_name, parameters, initial_virtual_direction, literal, return_direction): """ Name: create_function Description: Creates the information for the function with its corresponding quadruples. Parameters: ctx: Holds the context of the definition_function rule. function_name: The name of the function to create. parameters: The information of the parameters of the function. initial_virtual_direction: The virtual direction to access after Start Proc. literal: Information about the return literal. return_direction: The global direction used for the return. Returns: NA Important methods where its called: definition_function: To create the quadruples of the function. """ # Ensure the new function is not already defined check_defined_function(function_name) code_virtual_direction = memory.get_last_code() + 1 # Add the function to the functions table gl.functions[function_name] = Function(function_name, literal.type, {}, parameters, False, initial_virtual_direction, code_virtual_direction, return_direction, literal.array_info) memory.add_quadruple(Operator.PARAMEND, None, None, None) self.function(ctx.function()) gl.current_scope = global_function memory.add_quadruple(Operator.ENDPROC, None, None, None) memory.local_segment.clear()
def create_full_tree(depth): if depth == 0: terminal = Terminal.random_terminal() node = Node("terminal", terminal) return Tree(node) else: function = Function.random_function() root_node = Node("function", function) result = Tree(root_node) for i in range(2): #function.arity() result.add_child(Initializer.create_full_tree(depth - 1)) return result
return matchlist def _match_stmt(self, (tag, left, right, sublist), buffer): matcher = MatchStatement() matcher.matchlist = self._match_list(sublist[0], buffer) matcher.statements = self._suite(sublist[1], buffer) return matcher def _when_stmt(self, (tag, left, right, sublist), buffer): matcher = WhenStatement() matcher.matchlist = self._match_list(sublist[0], buffer) matcher.statements = self._suite(sublist[1], buffer) return matcher def _function(self, (tag, left, right, sublist), buffer): function = Function() function.name = getString(sublist[0], buffer) if len(sublist) == 1: return function for arg in sublist[1][3]: expression = self._expression(arg, buffer) function.args.append(expression) return function def _inherit(self, (tag, left, right, sublist), buffer): return getString(sublist[0], buffer) def _suite(self, (tag, left, right, sublist), buffer): statements = [] for token in sublist: tag = token[0]