def getResponse(self, sentence):        # major modification needs to be done...
        response = None
        sentence = sentence.lower()
        words = self.getWords(sentence)

        if self.hasNumbers(sentence) and (sentence.__contains__('+') or sentence.__contains__('-') or sentence.__contains__('into') or sentence.__contains__('x') or sentence.__contains__('/') or sentence.__contains__('divided') or sentence.__contains__('by') or sentence.__contains__('over')):
            response = self.calculate(words)
        elif sentence.__contains__('time') and (sentence.__contains__('date') or words.__contains__('day')):
            response = random.choice(self.dayResponses) + self.getCurrentSystemDate() + ' and ' + random.choice(self.timeResponses) + self.getCurrentSystemTime()
        elif sentence.__contains__('time'):
            response = random.choice(self.timeResponses) + self.getCurrentSystemTime()
        elif sentence.__contains__('date') or words.__contains__('day'):
            response = random.choice(self.dayResponses) + self.getCurrentSystemDate()
        elif sentence.__contains__('weather'):
            response = self.weather.getWeatherStatus("Dhaka, BD")
        elif sentence.__contains__('temperature'):
            response = self.weather.getTemperature("Dhaka, BD")
        elif sentence.__contains__('humidity'):
            response = self.weather.getHumidity("Dhaka, BD")
        elif sentence.__contains__('wind'):       # needs to be fixed...
            response = self.weather.getWindInformation("Dhaka, BD")
        elif sentence.__contains__('sun'):
            _lists = [[ 'rise', 'shine' ], [ 'set' ]]

            if sentence.__contains__(_lists[0][0]) or sentence.__contains__(_lists[0][1]):
                response = 'Sun will ' + random.choice(_lists[0]) + ' at ' + self.weather.getSunriseTime("Dhaka, BD")
            elif sentence.__contains__(_lists[1][0]):
                response = 'Sun will ' + random.choice(_lists[1]) + ' at ' + self.weather.getSunsetTime("Dhaka, BD")
        else:
            response = Utility.getData(sentence, Utility.getDataFrame("response.xlsx"))     # needs to be fixed...
        
        return str(response)
Esempio n. 2
0
    def __completeImageByMarginal(self, instance, part):
        self.__setInput(instance, part)
        self.__evaluateSPN()
        self.__differentiateSPN()

        
        for l in xrange(0, Parameters.imageWidth):
            r = l + 1
            for u in xrange(0, Parameters.imageHeight):
                d = u + 1
                num_id = Region.getRegionId(u, d, l, r)
                region = Region.getRegion(num_id)
                if part == 'LEFT':
                    if l < Parameters.imageWidth / 2:
                        tmp = self.__computeMarginal(region)
                        Utility.parseBuffer.append( \
                            Utility.getIntValue(instance, tmp))
                    else:
                        Utility.parseBuffer.append( \
                            Utility.getIntValue(instance, instance.getValue(u, l)))
                if part == 'BOTTOM':
                    if u < Parameters.imageHeight / 2:
                        Utility.parseBuffer.append( \
                            Utility.getIntValue(instance, instance.getValue(u, l)))
                    else:
                        tmp = self.__computeMarginal(region)
                        Utility.parseBuffer.append( \
                            Utility.getIntValue(instance, tmp))
Esempio n. 3
0
 def __init__(self):
     self._utility = Utility()
     self._mongo_client = MongoClient(Configurations.MONGO_DB_HOST, int(Configurations.MONGO_DB_PORT))
     print("Successfully connected to Mongo DB host: {0} and port: {1}".format(Configurations.MONGO_DB_HOST,
                                                                               str(Configurations.MONGO_DB_PORT)))
     self._create_db_and_collections_if_not_exist()
     self._create_indexes()
     self._get_all_manufacturers()
     self._get_all_models()
     self._time_format = "%Y-%m-%d"
 def visit(self, featureset):
     try:
         preprocessor = p.Binarizer()
         if self._column is not None:
             featureset.set_featureset_column(self._column,
                                              preprocessor.fit_transform(featureset.get_column_values(self._column)))
         else:
             featureset.set_featureset_values(preprocessor.fit_transform(featureset.get_featureset_values()))
     except Exception as error:
         Util.print_error("Unable to binarize values: " + str(error))
         Util.print_detailed_error()
Esempio n. 5
0
 def visit(self, featureset):
     try:
         tmp_list = []
         if self._dimension == "num_rows":
             tmp_list.append(str(featureset.get_featureset().get_featureset().shape[0]))
         elif self._dimension == "num_columns":
             tmp_list.append(str(featureset.get_featureset().get_featureset().shape[1]))
         return tmp_list
     except Exception as error:
         util.print_error("Unable to print data size" + str(error))
         util.print_detailed_error()
 def visit(self, featureset):
     try:
         data = featureset.get_featureset()
         if self._method == "median":
             data = data.fillna(data.median())
         else:
             data = data.interpolate(method=self._method)
         featureset.set_featureset(data)
     except Exception as error:
         Util.print_error("Unable to mask featureset: " + str(error))
         Util.print_detailed_error()
 def visit(self, featureset):
     try:
         preprocessor = p.Imputer(strategy=self._strategy)
         if self._column is not None:
             featureset.set_featureset_column(self._column,
                                              preprocessor.fit_transform(featureset.get_column_values(self._column)))
         else:
             featureset.set_featureset_values(preprocessor.fit_transform(featureset.get_featureset_values()))
     except Exception as error:
         Util.print_error("Unable to impute missing values: " + str(error))
         Util.print_detailed_error()
Esempio n. 8
0
    def recognize(self, image):
        tempImage = cv2.medianBlur(image.copy(), 15)
        returnValue, tempImage = cv2.threshold(tempImage, 127, 255,
                                               cv2.THRESH_BINARY)

        im2, contours, hierarchy = cv2.findContours(tempImage, cv2.RETR_TREE,
                                                    cv2.CHAIN_APPROX_SIMPLE)

        if len(contours) > 0:
            contour = max(contours, key=cv2.contourArea)

            try:
                [x, y, w, h] = cv2.boundingRect(contour)

                # image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
                image = image[y:(y + h), x:(x + w)]

                ImageProcessor.storeImage(
                    Utility.getAbsolutePath(
                        "data\\optical-character-recognition\\temporary-files\\temp.jpg"
                    ), image)

                if os.name == "nt":
                    text = pytesseract.image_to_string(
                        Image.open(
                            Utility.getAbsolutePath(
                                "data\\optical-character-recognition\\temporary-files\\temp.jpg"
                            )),
                        lang="eng",
                        config=
                        "--tessdata-dir \"C:/Program Files (x86)/Tesseract-OCR/tessdata\""
                    ).strip()
                else:
                    text = pytesseract.image_to_string(
                        Image.open(
                            Utility.getAbsolutePath(
                                "data\\optical-character-recognition\\temporary-files\\temp.jpg"
                            ))).strip()

                if len(text) != 0:
                    try:
                        print text

                        # textToSpeech.speak(text);

                    except Exception:
                        pass

                ImageProcessor.showPreview("OCR", image)

                if cv2.waitKey(1) == 27:
                    pass
            except Exception:
                pass
Esempio n. 9
0
 def visit(self, featureset):
     try:
         tmp_list = []
         for idx, col in enumerate(featureset.get_featureset().get_featureset().columns):
             name = col
             dtype_val = self.get_type(featureset, col)
             tmp = (str(idx) + "\t" + str(name) + "\t" + str(dtype_val))
             tmp_list.append(tmp)
         return tmp_list
     except Exception as error:
         util.print_error("Unable to print data head:" + str(error))
         util.print_detailed_error()
Esempio n. 10
0
    def graphifize(self, name, t, sol, limits=None):
        figure = plt.figure(name)

        plt.plot(t, sol[:, 1])
        plt.ylabel('temperature, $^\circ$C')
        plt.xlabel('time, s')
        plt.grid()
        if limits:
            plt.xlim(limits['x'])
            plt.ylim(limits['y'])

        Utility.saveFile(figure, name)
Esempio n. 11
0
def getAllEvent():
    for event in getEventsInformations():
        eventName=Utils.encode(event['name']['text'])
        eventDescription=Utils.encode(event['description']['text'])
        startEventTime=Utils.encode(event['start']['local'])
        endEventTime=Utils.encode(event['end']['local'])
        eventCategoryId=event['category_id']
        if eventCategoryId is not None:
            event=Event(eventName,eventDescription,startEventTime,endEventTime,getCategory(eventCategoryId),"Turkey")
        else:
            event=Event(eventName,eventDescription,startEventTime,endEventTime,"Genel","Turkey")
        eventList.append(event)
Esempio n. 12
0
 def send_message(self, message):
     try:
         self.connect()
         message = message.encode()
         self._client_socket.send(message)
         data = self._client_socket.recv(1024).decode()
         print("Received: " + data)
         self._client_socket.close()
         return data
     except Exception as error:
         util.print_error("Unable to send message to Server")
         util.print_error(error)
Esempio n. 13
0
    def try_purchase_via_cart(self) -> bool:
        try:
            add_to_cart_button = self.browser.find_element_by_id(
                "add-to-cart-button")
            add_to_cart_button.click()
            time.sleep(self.timeout_in_seconds)

            self.try_reject_additional_warranty()

            self.browser.get(self.cart_url)

            checkout_button = self.browser.find_element_by_name(
                "proceedToRetailCheckout")
            checkout_button.click()

            # Cart price check
            price_info = self.browser.find_element_by_css_selector(
                "td.grand-total-price").text
            add_to_cart_cost = Utility.parse_price_string(price_info)
            if add_to_cart_cost > self.max_cost_per_item:
                Utility.log_information(
                    f"{AmazonBuyer.BUYER_NAME}::Add to cart price is too high: {add_to_cart_cost} instead of {self.max_cost_per_item}"
                )

                return False

            # Confirm order
            order_confirmation_button = self.browser.find_element_by_name(
                "placeYourOrder1")

            # Check if the item is bought via another BuyerInterface instance.
            with self.item_counter as locked_counter:
                if locked_counter.get_within_existing_lock(
                )[0] >= max_buy_count:
                    return False

                if self.is_test_run:
                    Utility.log_warning(
                        f"{AmazonBuyer.BUYER_NAME}::Performing test run on Purchase via Cart"
                    )
                else:
                    order_confirmation_button.click()

                locked_counter.increment_within_existing_lock(
                    1, add_to_cart_cost)
            Utility.log_warning(
                f"{AmazonBuyer.BUYER_NAME}::Purchased {self.item_counter.get()[0]} of {self.max_buy_count} via Add to Cart at: {add_to_cart_cost}"
            )

            return True

        except Exception as ex:
            # TODO: Add success detection.
            Utility.log_verbose(
                f"{AmazonBuyer.BUYER_NAME}::Failed to buy item via cart. Current stock: {self.item_counter.get()[0]} of {self.max_buy_count} at: {self.item_counter.get()[1]}. Error was: {str(ex)}"
            )

            return False
 def visit(self, featureset):
     preprocessor = p.OneHotEncoder()
     try:
         if self._column is not None:
             featureset.set_featureset_column(
                 self._column,
                 preprocessor.fit_transform(featureset.get_column_values(self._column)))
         else:
             featureset.set_featureset_values(preprocessor.fit_transform(featureset.get_featureset_values()))
     except Exception as error:
         Util.print_error("Unable to apply One Hot Encoding: " + str(error))
         Util.print_detailed_error()
    def buildDatabase(self):
        print "initializing..."

        ID = 0
        facesDetected = 0
        subdirectoryNames = os.listdir(
            Utility.getAbsolutePath("data\\face-recognition\\faces"))
        listIDs = []
        listFaces = []

        faceRecognizer = self.createFaceRecognizer()

        print "organizing database..."

        for subdirectoryName in subdirectoryNames:
            files = os.listdir(
                Utility.getAbsolutePath("data\\face-recognition\\faces\\" +
                                        subdirectoryName))

            for _file in files:
                image = ImageProcessor.loadImage(
                    Utility.getAbsolutePath("data\\face-recognition\\faces\\" +
                                            subdirectoryName + "\\" + _file))
                grayImage = ImageProcessor.convertImageToGrayscale(image)
                faces = self.detectFaces(grayImage)
                facesDetected = self.countFaces(faces)

                print "faces detected = ", facesDetected

                if facesDetected == 1:  # the image must contain only one face...
                    print ID, "data\\faces\\" + subdirectoryName + "\\" + _file
                    listIDs.append(ID)
                    croppedImage = self.cropFaces(faces, grayImage)[0]
                    listFaces.append(numpy.array(croppedImage, 'uint8'))

                facesDetected = 0
            # loop ends here...

            ID += 1
        # loop ends here...

        faceRecognizer.train(listFaces, numpy.array(listIDs))

        if cv2.__version__ >= "3.3.0":
            faceRecognizer.write(
                Utility.getAbsolutePath(
                    "data\\face-recognition\\face-recognition-database.xml"))
        else:
            faceRecognizer.save(
                Utility.getAbsolutePath(
                    "data\\face-recognition\\face-recognition-database.xml"))

        print "operation completed successfully..."
    def load_in_requests(self):

        ref_time = '2014-10-01 00:00:00'

        f = open(self.data_folder + '/ems_requests.txt', 'r')
        for line in f:
            items = line.split(',')
            _time = int(
                Utility.get_elapsed_seconds(Utility.string2time(ref_time),
                                            Utility.string2time(items[0])))
            self.requests.append([_time, int(items[1])])
        f.close()
Esempio n. 17
0
    def on_start(self, event):
        # if not Utility.test_status_check(self.test_case_tree):
        #     return
        Utility.test_initialization()
        case_list = TestCaseTree.get_tree_select(tree=self.test_case_tree)
        device_list = ['']
        for device in device_list:
            test_thread = TestExecution(device, case_list, self.message)
            test_thread.setDaemon(True)
            test_thread.start()

            self.thread_list.append(test_thread)
Esempio n. 18
0
def main():
    isTestRun = False  # Don't update ProjectStatus if isTestRun is set.
    csvRows = []
    if len(sys.argv) < 2:
        print("Usage: python3 Main.py <project.json> <output.csv> [isTestRun]")
        sys.exit(-1)
    if len(sys.argv) == 3:
        isTestRun = True
    with open(sys.argv[1], encoding="utf8") as dataFile:
        try:
            projectData = json.load(dataFile, object_pairs_hook=OrderedDict)
            # loop through all the projects in apache-project.json
            for projectName, info in projectData.items():
                urlInfo = {"repository": [], "jira": ""}
                # get information about the bug database
                bugDatabase = info[
                    "bug-database"] if "bug-database" in info else ""
                urlInfo["jira"] = bugDatabase if bugDatabase.find(
                    "jira") >= 0 else None
                # get information about the repositories
                repos = info["repository"] if "repository" in info else []
                localRepos = []
                for eachRepo in repos:
                    goodGitRepo = __getValidGitRepo(eachRepo)
                    if goodGitRepo:
                        print("Validated git repo in Main = ", goodGitRepo)
                        urlInfo["repository"].append(goodGitRepo)
                        localRepos.append(
                            config.LOCAL_REPO.format(projectName))
                updateStatus = None
                # either of jira or git repo is not available.
                if urlInfo["jira"] is None:
                    print("Missing JIRA database.")
                    if isTestRun:
                        updateProjectStatus(projectName, "NoJIRA")
                    continue
                elif len(urlInfo["repository"]) == 0:
                    print("Missing Git repositories.")
                    if isTestRun:
                        updateProjectStatus(projectName, "NoGit")
                    continue
                if isTestRun:
                    updateProjectStatus(projectName, True)
                proj = ProjectApache(urlInfo["jira"], urlInfo["repository"],
                                     localRepos)
                csvRows.append(proj.csvRows)
                Utility.prettyPrintJSON(Utility.getCurrentRateLimit())
        except Exception as e:
            print(e)
        finally:
            finalTable = CSV(sys.argv[2], Perils.initCSVHeaders(), csvRows)
            finalTable.outputCSVFile()
            dataFile.close()
Esempio n. 19
0
 def checkGroup(self, featureset, column):
     try:
         target_column = featureset[column]
         if target_column.dtype == "object":
             if isinstance(target_column.iloc[0],
                           (list, tuple, np.ndarray)):
                 return True
         return False
     except Exception as error:
         Util.print_error("Unable to check group in featureset: " +
                          str(error))
         Util.print_detailed_error()
Esempio n. 20
0
    def create(self, plugin_name: str):
        """
            tries to create a new plugin inside plugins_folder.
            May fail due to one of the following reasons:
            * naming-convention not matched (only lowercase, alphanumeric + underscore)
            * name already exists in plugins-folder
            * one of the necessary ressources can't be linked (godot-cpp, godot_headers)
        """

        # match plugin_name against pattern
        Utility.matchNamingConvention(plugin_name)

        plugins_folder = self.config.plugins_folder

        # check if folder does not already exist
        Utility.checkNotOccupied(plugin_name, plugins_folder)

        # check if both (godot-cpp and godot_headers)-folders can be found
        godot_cpp_folder = self.config.godot_cpp_folder
        godot_headers_folder = self.config.godot_headers_folder
        if not os.path.isdir(godot_cpp_folder) or not os.path.isdir(
                godot_headers_folder):
            print(
                'godot-cpp-folder or godot_header-folder couldn\'t be found.')
            sys.exit()

        # open sconstruct-template and paste values
        sconstruct_template = open(self.config.sconstruct_template_file)
        sconstruct_str = str(sconstruct_template.read())
        sconstruct_lines = sconstruct_str.splitlines(keepends=True)
        sconstruct_lines[8] = 'output_name = \'' + plugin_name + '\''

        print('checks passed')

        # make directories, links and files
        new_plugin_folder = plugins_folder + plugin_name + '/'
        os.mkdir(new_plugin_folder)
        os.mkdir(new_plugin_folder + 'bin')
        os.mkdir(new_plugin_folder + 'src')
        os.symlink(godot_cpp_folder, new_plugin_folder + 'godot-cpp')
        os.symlink(godot_headers_folder, new_plugin_folder + 'godot_headers')
        os.mknod(new_plugin_folder + 'SConstruct')
        os.mknod(new_plugin_folder + 'src/.gdignore')

        new_sconstruct_file = open(new_plugin_folder + 'SConstruct', mode='w')
        for line in sconstruct_lines:
            new_sconstruct_file.write(line)

        shutil.copyfile(self.config.api_json_file,
                        new_plugin_folder + 'api.json')
        shutil.copyfile(self.config.gdlibrary_cpp_file,
                        new_plugin_folder + 'src/gdlibrary.cpp')
Esempio n. 21
0
 def _calCost(self):
     multiList = Utility.multFeatureWeights(self.weightList, self.xList);
     self.prob0=Sigmoid.getSigmoidVal(multiList);
     #print len(self.prob0);
     #print len(self.yList);
     self.prob1 = Utility.matrixXminusOper(1, self.prob0);
     firstPart = self._calFistPart(self.prob1);
     secPart = self._calSecPart(self.prob0);
     regpart = self._calRegpart();
     #print firstPart;
     #print secPart;
     cost = firstPart+secPart-regpart;
     return cost;
 def visit(self, featureset):
     try:
         data = featureset.get_featureset()
         if self._mode == "shuffle":
             data = data.sample(frac=1)
         elif self._mode == "column":
             data = data.sort_values(by=self._column)
         elif self._mode == "index":
             data = data.sort_index()
         featureset.set_featureset(data)
     except Exception as error:
         Util.print_error("Unable to sort featureset: " + str(error))
         Util.print_detailed_error()
Esempio n. 23
0
def create_device_mapper():
    """
    :return: dictionary of device mapping
    """
    utility = Utility(log_file="data_gen_process_log_file.txt", debug=1)
    sql = "SELECT DeviceName, DeviceType, DeviceLocation FROM DeviceMapper"
    mapped_device_list, device_count = utility.query_database(sql)
    if device_count == 0:
        print("no device registered in the database")
        return None
    for mapped_device in mapped_device_list:
        print mapped_device
    return None
 def visit(self, featureset):
     try:
         featureset.set_featureset(
             pd.concat([
                 featureset.get_featureset(),
                 self._featureset.get_featureset()
             ],
                       axis=1,
                       join='inner'))
     except Exception as error:
         util.print_error("Failed to Join Featureset with Featureset" +
                          str(error))
         util.print_detailed_error()
    def visit(self, featureset_element):
        try:
            featureset = featureset_element.get_featureset()
            print(featureset.shape)
            index = featureset[eval(self._condition)].index
            featureset.drop(index, inplace=True)
            featureset.reset_index(inplace=True, drop=True)
            print(featureset.shape)
            featureset_element.set_featureset(featureset)

        except Exception as error:
            util.print_error("Failed to drop rows by condition: " + str(error))
            util.print_detailed_error()
    def visit(self, featureset):
        try:
            featureset_df = featureset.get_featureset()
            if self._group_by is not None:
                group_column = featureset_df[self._group_by]

                if self._column is not None:
                    # check if column is single-column or column group
                    feature_vector = False
                    target_column = featureset_df[self._column]
                    if self.checkGroup(featureset.get_featureset(), self._column):
                        feature_vector = True
                        target_column = self.expand(featureset_df, self._column, True)

                    # add group_column to dataframe and transform standardization on groups
                    target_column = pd.concat([target_column, group_column], axis=1)
                    target_column = target_column.groupby(self._group_by).transform(lambda x: (x - x.mean()) / x.std())
                    if feature_vector:
                        featureset.set_featureset_column(self._column, list(target_column.values))
                    else:
                        featureset.set_featureset_column(self._column, target_column)

                else:
                    # group dataframe by group_column and perform standardization on whole df
                    data = featureset_df.groupby(self._group_by).transform(lambda x: (x - x.mean()) / x.std())
                    featureset.set_featureset_column(self._column, data)

            else:
                if self._column is not None:
                    # check if column is single-column or column group
                    target_column = featureset_df[self._column]
                    feature_vector = False
                    if self.checkGroup(featureset.get_featureset(), self._column):
                        feature_vector = True
                        target_column = self.expand(featureset_df, self._column, True)

                    # add group_column to dataframe and transform standardization on groups
                    target_column = target_column.transform(lambda x: (x - x.mean()) / x.std())
                    if feature_vector:
                        featureset.set_featureset_column(self._column, list(target_column.values))
                    else:
                        featureset.set_featureset_column(self._column, target_column)

                else:
                    # group dataframe by group_column and perform standardization on whole df
                    data = featureset_df.transform(lambda x: (x - x.mean()) / x.std())
                    featureset.set_featureset_column(self._column, data)

        except Exception as error:
            Util.print_error("Unable to standardize values: " + str(error))
            Util.print_detailed_error()
Esempio n. 27
0
    def getResponse(self, sentence):  # major modification needs to be done...
        response = None
        sentence = sentence.lower()
        words = self.getWords(sentence)

        if self.hasNumbers(sentence) and (
                sentence.__contains__('+') or sentence.__contains__('-')
                or sentence.__contains__('into') or sentence.__contains__('x')
                or sentence.__contains__('/') or
                sentence.__contains__('divided') or sentence.__contains__('by')
                or sentence.__contains__('over')):
            response = self.calculate(words)
        elif sentence.__contains__('time') and (sentence.__contains__('date')
                                                or words.__contains__('day')):
            response = random.choice(
                self.dayResponses) + self.getCurrentSystemDate(
                ) + ' and ' + random.choice(
                    self.timeResponses) + self.getCurrentSystemTime()
        elif sentence.__contains__('time'):
            response = random.choice(
                self.timeResponses) + self.getCurrentSystemTime()
        elif sentence.__contains__('date') or words.__contains__('day'):
            response = random.choice(
                self.dayResponses) + self.getCurrentSystemDate()
        elif sentence.__contains__('weather'):
            response = self.weather.getWeatherStatus("Dhaka, BD")
        elif sentence.__contains__('temperature'):
            response = self.weather.getTemperature("Dhaka, BD")
        elif sentence.__contains__('humidity'):
            response = self.weather.getHumidity("Dhaka, BD")
        elif sentence.__contains__('wind'):  # needs to be fixed...
            response = self.weather.getWindInformation("Dhaka, BD")
        elif sentence.__contains__('sun'):
            _lists = [['rise', 'shine'], ['set']]

            if sentence.__contains__(_lists[0][0]) or sentence.__contains__(
                    _lists[0][1]):
                response = 'Sun will ' + random.choice(
                    _lists[0]) + ' at ' + self.weather.getSunriseTime(
                        "Dhaka, BD")
            elif sentence.__contains__(_lists[1][0]):
                response = 'Sun will ' + random.choice(
                    _lists[1]) + ' at ' + self.weather.getSunsetTime(
                        "Dhaka, BD")
        else:
            response = Utility.getData(
                sentence,
                Utility.getDataFrame("response.xlsx"))  # needs to be fixed...

        return str(response)
Esempio n. 28
0
 def _processDir(self):
     exampleList = []
     for key in self.trainDict:
         fileList = Utility.readDir(self.trainDict[key])
         folderName = self.trainDict[key]
         for file in fileList:
             if (file == '.DS_Store'): continue
             self.yDict[folderName + "/" + file] = self.classDict[key]
             self.yList.append(self.classDict[key])
             sentList = Utility.readFile(folderName + "/" + file)
             wordsDictCount = Utility.getWordsCountDict(sentList)
             exampleList.append(wordsDictCount)
             self._populateVocab(wordsDictCount)
     self._makeXList(exampleList)
Esempio n. 29
0
    def __init__(self, chrome_driver_path: str, item_indice: int,
                 item_name: str, max_buy_count: int, max_cost_per_item: float,
                 item_counter: ThreadSafeCounter, max_retry_limit: int,
                 timeout_in_seconds: int, is_test_run: bool):
        super(NeweggBuyer,
              self).__init__(chrome_driver_path, item_indice, item_name,
                             max_buy_count, max_cost_per_item, item_counter,
                             max_retry_limit, timeout_in_seconds, is_test_run)

        self.affiliate_url = Utility.get_config_value_str(
            "NEWEGG_AFFILIATE_URL")
        self.secure_subdomain_url = Utility.get_config_value_str(
            "NEWEGG_SECURE_SUBDOMAIN_URL")
        self.item_endpoint = Utility.get_config_value_str(
            f"NEWEGG_ITEM_ENDPOINT_{self.item_indice+1}")
        self.whitelisted_sellers = Utility.get_config_value_str(
            "NEWEGG_WHITELISTED_SELLERS").split(",")
        self.login_url = f"{self.secure_subdomain_url}{NeweggBuyer.LOGIN_ENDPOINT}"
        self.item_url = f"{self.affiliate_url}{self.item_endpoint}"
        self.cart_url = f"{self.secure_subdomain_url}{NeweggBuyer.CART_ENDPOINT}"
        self.login_confirmation_wait_in_seconds = Utility.get_config_value_int(
            "NEWEGG_LOGIN_CONFIRMATION_WAIT_IN_SECONDS")
        self.stock_check_min_wait_in_seconds = Utility.get_config_value_int(
            "NEWEGG_STOCK_CHECK_MIN_WAIT_IN_SECONDS")
        random.seed(time.time())

        self.is_authenticated = False
        try:
            self.browser = webdriver.Chrome(self.chrome_driver_path)
            self.browser.get(self.affiliate_url)
            self.wait = WebDriverWait(self.browser, self.timeout_in_seconds)
        except Exception as ex:
            Utility.log_error(
                f"{NeweggBuyer.BUYER_NAME}::Failed to open browser: {str(ex)}")
            raise
 def visit(self, featureset):
     pca = PCA(self._n)
     log = None
     try:
         preprocessor = pca.fit_transform(featureset.GetSelectedFeatures())
         log.append("Components " + preprocessor.components_)
         log.append("ExplainedVariance " + preprocessor.explained_variance_)
         log.append("ExplainedVarianceRatio " + preprocessor.explained_variance_ratio_)
         log.append("SingularValue " + preprocessor.singular_values_)
         log.append("Mean " + preprocessor.mean_)
         return log
     except Exception as error:
         Util.print_error("Unable to apply PCA: " + str(error))
         Util.print_detailed_error()
def pax_flow_analyzer(img_date, img_time, image_key, matched_image_list):
    utility = Utility(log_file="big_data_process_log_file.txt", debug=1)
    utility.loginfo("Initializing ......... PaxFlowAnalyzer")
    pax_location, pax_location_type, pax_key, pax_date, pax_sha_enter_time, pax_sha_exit_time = "SHA", "SHA", \
                                                                                                image_key, img_date, img_time, img_time

    # passenger must be at sha
    pax_sha = PaxFlow(pax_key, pax_date, str(pax_sha_enter_time),
                      str(pax_sha_exit_time), pax_location, pax_location_type)
    # PaxFlow("F1XXCdf0000", "2018-01-23", "13:00:00", "21:00:00", "sha1", "sha")
    pax_sha.add_pax_flow(utility)
    del pax_sha

    if len(matched_image_list) == 0:
        return None

    for pax in matched_image_list:
        pax_similarity, pax_location, pax_location_type, pax_location_time = pax[
            2], pax[3], pax[5], pax[7].time()
        utility.loginfo("passenger({}) found at {}, type: {}".format(
            pax_key, pax_location, pax_location_type, str(pax_location_time)))

        # if pax_location_time == "footfall":
        try:
            print(
                "passenger({}) found at {}, type: {}, capture time: {}".format(
                    pax_key, pax_location, pax_location_type,
                    str(pax_location_time)))
            # passenger location changes , break passenger flow.
            if pax_location != pax_flow.get("location"):
                # add passenger flow in the database
                pax_flow.add_pax_flow(utility)
                # update passenger flow for new location
                print(
                    "updating passenger flow for ({}) new location({})........., type: {}"
                    .format(pax_key, pax_location, pax_location_type))
                pax_flow.set("location", pax_location)
                pax_flow.set("location_type", pax_location_type)
                pax_flow.set("enter_time", str(pax_location_time))
                pax_flow.set("exit_time", str(pax_location_time))
                continue

            pax_exit_time = datetime.strptime(pax_flow.get("exit_time"),
                                              '%H:%M:%S').time()

            if pax_location_time > pax_exit_time:
                pax_flow.set("exit_time", str(pax_location_time))

        except NameError:
            utility.loginfo(
                "creating object for passenger({}) found at {}, type:{}".
                format(pax_key, pax_location, pax_location_type))
            pax_flow = PaxFlow(pax_key, str(pax_date), str(pax_location_time),
                               str(pax_location_time), pax_location,
                               pax_location_type)
    # add current passenger flow in the db
    pax_flow.add_pax_flow(utility)
    del pax_flow
    return None
Esempio n. 32
0
    def __solveTree(self, node):
        '''
        Recursively solve the problem tree.
        '''

        self.__iterationCount += 1
        if self.__debugLevel >= 2:
            print '----------------'
            print 'Iteration %d' % self.__iterationCount
            print '----------------'
            print Utility.formatSolution(node.conf)

        # Assign next value, and check constraints
        if node.value != None:
            self.__setValue(node.domain, node.conf, node.x, node.y, node.value)
            if not ConstraintStore.checkConstraints(
                    self.boardSize,
                    self.cages,
                    node.domain,
                    node.conf,
                    debugLevel=self.__debugLevel):
                return False

        # Done if all cells are assigned
        unassignedCells = filter(
            lambda x: node.conf[x[0]][x[1]] == None,
            itertools.product(range(0, self.boardSize),
                              range(0, self.boardSize)))
        if len(unassignedCells) == 0:
            if self.__debugLevel >= 2: print 'Solution found!'
            return True

        # Get next cell
        unassignedCells = sorted(unassignedCells,
                                 key=lambda x: len(node.domain[x[0]][x[1]]))
        cell = unassignedCells[0]
        x = cell[0]
        y = cell[1]

        # Try each domain value
        for value in node.domain[x][y]:
            childNode = SolverNode(node.domain, node.conf, x, y, value)
            if self.__solveTree(childNode):
                node.domain = childNode.domain
                node.conf = childNode.conf
                return True

        # No solution found in this subtree
        return False
Esempio n. 33
0
 def __init__ (self, configuration):
     Utility.__init__(self)
     Debug.__init__(self)
     # Used for private and pointer variables
     self.current_threads = []
     # Variable type lists
     self.shared     = []
     self.private    = []
     self.pointers   = []
     self.ports      = []
     self.variables  = [self.shared, self.private, self.pointers, self.ports]
     self.configuration = configuration
     # Location Zero is a special case always equal to zero.
     # It must exist before any other shared variable.
     self.shared.append(Shared_Variable(label = None, address = 0, value = 0, memory = "A"))
     self.shared.append(Shared_Variable(label = None, address = 0, value = 0, memory = "B"))
Esempio n. 34
0
    def de(self,mod):
        frontier_size = 50
        max_tries = 40
        f = 0.75
        cf = 0.3
        epsilon = 0.1
        ib = -1
        frontier = self.generate_frontier(frontier_size,mod)
        eb = self.init_score(mod,frontier)
        for k in range(max_tries):
            total,n,eb,ib,frontier = self.update(mod,f,cf,frontier,eb)
            Utility.say("\n")
            #en = total/n

            #if total/n > (1 - epsilon):
             #   break
        f1,f2 = mod.objs(frontier[ib])
        Utility.printOutput("Success",f1,f2,frontier[ib],eb)
        return frontier
Esempio n. 35
0
 def __solveTree(self, node):
     '''
     Recursively solve the problem tree.
     '''
     
     self.__iterationCount += 1
     if self.__debugLevel >= 2:
         print '----------------'
         print 'Iteration %d' % self.__iterationCount
         print '----------------'
         print Utility.formatSolution(node.conf)
     
     # Assign next value, and check constraints
     if node.value != None:
         self.__setValue(node.domain, node.conf, node.x, node.y, node.value)
         if not ConstraintStore.checkConstraints(self.boardSize, self.cages, node.domain, node.conf, debugLevel=self.__debugLevel):
             return False
     
     # Done if all cells are assigned
     unassignedCells = filter(lambda x: node.conf[x[0]][x[1]] == None, itertools.product(range(0, self.boardSize), range(0, self.boardSize)))
     if len(unassignedCells) == 0:
         if self.__debugLevel >= 2: print 'Solution found!'
         return True
     
     # Get next cell
     unassignedCells = sorted(unassignedCells, key=lambda x: len(node.domain[x[0]][x[1]]))
     cell = unassignedCells[0]
     x = cell[0]
     y = cell[1]
     
     # Try each domain value
     for value in node.domain[x][y]:
         childNode = SolverNode(node.domain, node.conf, x, y, value)
         if self.__solveTree(childNode):
             node.domain = childNode.domain
             node.conf = childNode.conf
             return True
     
     # No solution found in this subtree
     return False
    def __init__(self):
        self.port = Utility.getValueFromConfigurationFile('port')

        serverSocket = socket.socket()      # creating socket object...
        serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        serverSocket.bind(('', int(self.port)))    # binding socket to address (host-name, port)...
        serverSocket.listen(5)

        print('server running...\n\nip-address = ' + socket.gethostbyname(socket.gethostname()) + '\nport = ' + self.port)

        threading.Thread(target = self.backgroundWorker).start()       # starting background thread...

        while True:         # this infinite loop accepts new clients and running on main thread...
            print('waiting for client...')
            
            self._socket, address = serverSocket.accept()
            
            print('client connected...')
Esempio n. 37
0
def fitness(wf, rm, estimator, position):
    if isinstance(position, Schedule):
        sched = position
    else:
        sched = build_schedule(wf, estimator, rm, position)

    # isvalid = Utility.is_static_schedule_valid(wf,sched)
    # if not isvalid:
    #     print("NOT VALID SCHEDULE!")

    makespan = Utility.makespan(sched)
    ## TODO: make a real estimation later
    cost = 0.0
    Fitness.weights = [-1.0, -1.0]
    fit = Fitness(values=(makespan, cost))
    ## TODO: make a normal multi-objective fitness estimation
    fit.mofit = makespan
    return fit
Esempio n. 38
0
 def update(self,mod,f,cf,frontier,eb, total=0.0, n=0):
     ib = -1
     for i,x in enumerate(frontier):
         sc = mod.score(x)
         new = self.extrapolate(frontier,x,f,cf,i,mod)
         new_sc = mod.score(new)
         if new_sc < eb:
             Utility.say('?')
             eb = sc = new_sc
             frontier[i] = x[:]
             ib = i
         elif new_sc < sc:
             Utility.say('+')
             sc = new_sc
             frontier[i] = x[:]
         else:
             Utility.say('.')
         total += sc
         n += 1
     return total,n,eb,ib,frontier
Esempio n. 39
0
	def randomizedApriori(self):

		apriori = Apriori(self.transactionFile,self.minimumSupport);
		utility = Utility(self.transactionFile,self.minimumSupport);

		candidates,T = apriori.C1List();
		
		frequentItemSet = {};
		k=1;

		list = apriori.itemsetWithMinimumSupport(candidates);
		
		if list:
			frequentItemSet[k] = list;

		onezero = {};
		indexes = {};

		d=0;
		
		while list:

			if k==1:
				
				onezero,d = utility.convert(list,apriori);
				
			else:

				onezero = utility.combineConvert(onezero,indexes);
				
			k = k+1;			
			m = utility.mValue(onezero);			
						
			pqonezero = utility.pqTrasform(onezero,m,d);			
			qponezero = utility.qpTransform(onezero,m,d);

			# print "old support : ",self.minimumSupport;
			alpha = float(m)/T ;	
			omega = ( (1-self.tolerance)*self.minimumSupport )/(2*alpha-(1-self.tolerance)*self.minimumSupport);
			# print "omega value : ",omega;
			epsolon = ( (alpha)*self.tolerance ) /( alpha +(alpha -self.minimumSupport)*(1-self.tolerance) );
			# print "epsolon value :",epsolon;
			deltaInverse = int(1/self.error);
			# print "delta inverse is : ",deltaInverse;

			# numberOfHashFunctions = int( (2/(omega*epsolon*epsolon))*log(deltaInverse) );
			support = ( ( 1-epsolon )*self.minimumSupport)/(2*alpha - self.minimumSupport);			
			
			# print "new support is :",support;			
			# print "number of hashfunctions : ",numberOfHashFunctions;

			prime = 9887;
			a,b = self.random(0,prime,self.numberOfHashFunctions);			
			# if m < self.numberOfHashFunctions:
			# 	self.numberOfHashFunctions =m;

			pSignature = utility.minHashSignature(list,pqonezero,a,b,prime,m,d,self.numberOfHashFunctions);
			qSignature = utility.minHashSignature(list,qponezero,a,b,prime,m,d,self.numberOfHashFunctions);
						

			candidates,indexes = utility.generate(pSignature,qSignature,k,support);
				
			del pSignature,qSignature;
			
			list,indexes = utility.itemsetWithMinimumSupport(candidates,indexes,apriori);
			
			frequentItemSet[k] = list;			
			

		
		return frequentItemSet;
Esempio n. 40
0
# -*- coding: unicode -*-
import sys,urllib,urllib2,gzip,StringIO,io,cookielib,re,socket,time,os,traceback,copy
from cookielib import CookieJar
from threading import Thread
import socket
from urllib2 import Request, urlopen, URLError, HTTPError
from Utility import Utility
from SiteData import *
from ErrorCode import *
from pprint import pprint
from multiprocessing import Pool,Manager
from ResultData import *

SINGLE_PROCESS_TIMEOUTS = 50
socket.setdefaulttimeout(SINGLE_PROCESS_TIMEOUTS)
utility = Utility()

# Processor for one single action, for example, one post, one get, with one result check.
class SingleActionProcessor:

  cj = None

  # Initialize the cookie / opener.
  # It might NOT be thread safe, NOR can it support multiple action processor.
  def __init__(self):
    # Note: Don't install_opener as a global opener for now, considering
    # timeouts. For each batch-send/fetch, we require one explicit login.
    # Also, we don't use Basic Auth Handler.
    self.cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
    urllib2.install_opener(opener)
Esempio n. 41
0
def main():
    print("random",random.randint(0,6))
    # ALL THE STUFF!

    # Trade
    def trade(p1, p2):
        """
        :param p1: Player 1
        :param p2: Player 2
        :return: None
        """
        deal = input("Are properties being traded? (y/n) ")
        temp = None
        if deal == "y":
            print("---- PROPERTY NAMES ARE CASE SENSITIVE ----")
            deal = input("Is Player one giving a property? (y/n) ")
            if deal == "y":
                print("Player one's properties:")
                print(p1.getProperties())
                temp = input("What would you like to trade, Player one? ")
                p1.loseProperty(temp)
            deal = input("Is Player two giving a property (y/n) ")
            if deal == "y":
                print("Player two's properties:")
                print(p2.getProperties())
                if temp != None:
                    p2.gainProperty(temp)
                temp = input("What would you like to trade, Player two? ")
                p1.gainProperty(temp)
                p2.loseProperty(temp)
        money = input("Is there money involved in this trade? (y/n) ")
        if money == "y":
            money = input("Is player one giving money? (y/n) ")
            if money == "y":
                p2.gainMoney(int(input("How much money is Player one giving? $")))
            money = input("Is player two giving money? (y/n) ")
            if money == "y":
                p1.gainMoney(int(input("How much money is Player two giving? $")))
        return

    # Die
    Die1 = Die()
    Die2 = Die()

    # Properties:

    # Purple
    Mediterranean = Property("Mediterranean Avenue", "brown", 60, 50, 50, 30, [2, 10, 30, 90, 160, 250])
    Baltic = Property("Baltic Avenue", "brown", 60, 50, 50, 30, [4, 20, 60, 180, 320, 450])

    # Light Blue
    Oriental = Property("Oriental Avenue", "light blue", 100, 50, 50, 50, [6, 30, 90, 270, 400, 550])
    Vermont = Property("Vermont Avenue", "light blue", 100, 50, 50, 50, [6, 30, 90, 270, 400, 550])
    Connecticut = Property("Connecticut Avenue", "light blue", 120, 50, 50, 60, [8, 40, 100, 300, 450, 600])

    # Fuschia
    StCharles = Property("St. Charles Place", "fuschia", 140, 100, 100, 70, [10, 50, 150, 450, 625, 750])
    States = Property("States Avenue", "fuschia", 140, 100, 100, 70, [10, 50, 150, 450, 625, 750])
    Virginia = Property("Virginia Avenue", "fuschia", 160, 100, 100, 80, [12, 60, 180, 500, 700, 900])

    # Orange
    StJames = Property("St. James Place", "orange", 180, 100, 100, 90, [14, 70, 200, 550, 750, 950])
    Tennessee = Property("Tennessee Avenue", "orange", 180, 100, 100, 90, [14, 70, 200, 550, 750, 950])
    NewYork = Property("New York Avenue", "orange", 200, 100, 100, 100, [12, 80, 220, 600, 800, 1000])

    # Red
    Kentucky = Property("Kentucky Avenue", "red", 220, 150, 150, 110, [18, 90, 250, 700, 875, 1050])
    Indiana = Property("Indiana Avenue", "red", 220, 150, 150, 110, [18, 90, 250, 700, 875, 1050])
    Illinois = Property("Illinois Avenue", "red", 240, 150, 150, 120, [20, 100, 300, 750, 925, 1100])

    # Yellow
    Atlantic = Property("Atlantic Avenue", "yellow", 260, 150, 150, 130, [22, 1110, 330, 800, 975, 1150])
    Ventnor = Property("Ventnor Avenue", "yellow", 260, 150, 150, 130, [22, 1110, 330, 800, 975, 1150])
    Marvin = Property("Marvin Gardens", "yellow", 280, 150, 150, 140, [24, 120, 360, 850, 1025, 1200])

    # Green
    Pacific = Property("Pacific Avenue", "green", 300, 200, 200, 150, [26, 130, 390, 900, 110, 1275])
    NorthCarolina = Property("North Carolina Avenue", "green", 300, 200, 200, 150, [26, 130, 390, 900, 110, 1275])
    PennsylvaniaAve = Property("Pennsylvania Avenue", "green", 320, 200, 200, 160, [28, 150, 450, 1000, 1200, 1400])

    # Blue
    Park = Property("Park Place", "blue", 350, 200, 200, 175, [35, 175, 500, 1100, 1300, 1500])
    Boardwalk = Property("Boardwalk", "blue", 400, 200, 200, 30, [50, 200, 600, 1400, 1700])


    #Railroads:
    Pennsylvania = Railroad("Pennsylvania Railroad")

    Reading = Railroad("Reading Railroad")

    Short_Line = Railroad("Short Line")

    BO = Railroad("B. &. O. Railroad")  # lol

    # Utilities:
    Water = Utility("Water Works", Die1, Die2)
    Electric = Utility("Electric Company", Die1, Die2)

    # Extra Spaces:

    # Just Visiting
    # Nothing happens :D

    # Free Parking
    # Put in the turn code

    # Luxury Tax/Income Tax
    # Turn code
    # Variables

    hotels = 12

    houses = 32

    pieces = ["Dog","Top Hat", "Car", "Iron", "Boat", "Thimble", "Boot", "Wheelbarrow"]

    spaces = ["Go", Mediterranean, "Community Chest", Baltic, "Income Tax", Reading, Oriental,
              "Chance", Vermont, Connecticut, "Jail", StCharles, Electric, States, Virginia, Pennsylvania,
              StJames, "Community Chest", Tennessee, NewYork, "Free Parking", Kentucky, "Chance",
              Indiana, Illinois, BO, Atlantic, Ventnor, Water, Marvin, "Go To Jail", Pacific, NorthCarolina,
              "Community Chest", PennsylvaniaAve, Short_Line, "Chance", Park, "Luxury Tax", Boardwalk]
    print("debug", spaces[39])
    # Cards:

    # Community Chest:
    # kill me
    # textEffect, effect

    Chesta = CommunityChest("Life Insurance Matters - Collect $100",100)
    Chestb = CommunityChest("Income Tax Refund - Collect $20", 20)
    Chestc = CommunityChest("Receive for Services - Collect $25", 25)
    Chestd = CommunityChest("Pay Hospital $100", -100)
    Cheste = CommunityChest("Christmas Fund Matures - $100", 100)
    Chestf = CommunityChest("You have won second prize in a beauty contest! - Collect $10", 10)
    Chestg = CommunityChest("Doctors Fee! Pay $50", -50)
    Chesth = CommunityChest("From sale of stock you get $45", 45)
    Chesti = CommunityChest("Pay School Tax of $150", -150)
    Chestj = CommunityChest("Go To Jail", "Jail")
    Chestk = CommunityChest("Advance to Go", "go")
    Chestl = CommunityChest("You inherit $100", 100)
    Chestm = CommunityChest("Bank Error in Your Favor - Collect $200", 200)
    Chestn = CommunityChest("Get Out of Jail Free", "jail card")
    communityChestDeck = [Chesta, Chestb, Chestc, Chestd, Cheste, Chestf, Chestg, Chesth, Chesti, Chestj, Chestk, Chestl, Chestm, Chestn]

    # Chance Cards:
    # TextEffect, effect, type

    ChanceA = Chance("Your building and loan matures - Collect $150", "money", 150)
    ChanceB = Chance("Bank pays you dividend of $50", "money", 50)
    ChanceC = Chance("Advance token to nearest utility - if unowned, you may buy it from bank."
                     "If owned, throw dice and pay owner a total ten times the amount thrown","move",0)
    ChanceD = Chance("Advance to Illinois Ave","move",24)
    chanceDeck = [ChanceA, ChanceB, ChanceC, ChanceD]

    freeParking = 0  #Free Parking
    # TURN CODE
    # i want to die
    print("Welcome to MONOPOLY!!")  # this is more excited than I feel. I hate monopoly
    print("There are 4 people playing")

    # player inputs
    print("Hi players! What piece would you like to have? There are: ")
    for i in range(len(pieces)):
        print(pieces[i],end=" ")
    print("available! Please don't choose the same piece.")  # figure out how to make them not choose the same piece
    player1 = Player(input("Player 1! Input your piece here! "))
    #if player1.getPiece() not in pieces:
    #    print("This was not an acceptable piece to input. Try again")
    player2 = Player(input("Player 2! Input your piece here! "))
    player3 = Player(input("PLayer 3! Input your piece here! "))
    player4 = Player(input("Player 4! Input your piece here! "))

    print("Rolling die to see who goes first!")

    input("Player 1, roll the die!")
    p1d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p1d)
    print()

    input("Player 2, roll the die!")
    p2d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p2d)
    print()

    input("Player 3, roll the die!")
    p3d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p3d)
    print()

    input("Player 4, roll the die!")
    p4d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p4d)

    print()

    playerOrder = []
    if max(p1d, p2d, p3d, p4d) == p1d:
        print("Player 1 goes first!")
        playerOrder = [player1, player2, player3, player4]
    elif max(p1d, p2d, p3d, p4d) == p2d:
        print("Player 2 goes first!")
        playerOrder = [player2, player3, player4, player1]
    elif max(p1d, p2d, p3d, p4d) == p3d:
        print("Player 3 goes first!")
        playerOrder = [player3, player4, player1, player2]
    else:
        print("Player 4 goes first!")
        playerOrder = [player4, player1, player2, player3]

    # Beginning the game
    while playerOrder[0].getMoney() > 0 or playerOrder[1].getMoney() > 0 or playerOrder[2].getMoney() > 0 or playerOrder[3].getMoney() > 0:
        cp = 0

        # Cycling around the order of players
        while cp < 4:

            # Making sure player not in jail
            if not playerOrder[cp].getInJail():
                print()
                print(playerOrder[cp].getPiece(), " Press enter to roll the die!")
                input()
                Die1.rollDie()
                Die2.rollDie()

                # Think about doing the doubles x3 to jail-- maybe not?
                print("You've rolled:", Die1.getCurrentFace(), "and", Die2.getCurrentFace())

                # Passing Go
                if playerOrder[cp].getSpace() + (Die1.getCurrentFace()+Die2.getCurrentFace()) > 39:
                    sp = (Die1.getCurrentFace()+Die2.getCurrentFace()) - (39 - playerOrder[cp].getSpace())
                    playerOrder[cp].setSpace(sp)
                    playerOrder[cp].gainMoney(200)
                    print("You passed GO! You've collected $200!")
                else:
                    playerOrder[cp].moveSpace(Die1.getCurrentFace(), Die2.getCurrentFace())

                # Community Chest
                if playerOrder[cp].getSpace() == 2 or playerOrder[cp].getSpace() == 17 or playerOrder[cp].getSpace() == 33:  #community chest
                    print("You've landed on community chest!")
                    randomnum = random.randint(1, 13)
                    print(communityChestDeck[randomnum].getTextEffect())
                    communityChestDeck[randomnum].drawCard(playerOrder[cp])
                    if isinstance(communityChestDeck[randomnum].getEffect(), int):
                        print("Money!")
                        communityChestDeck[randomnum].applyEffect()
                    else:
                        if communityChestDeck[randomnum].getEffect() == "go":
                            print("You have been sent to GO and have collected $200")
                            communityChestDeck[randomnum].applyEffect()
                        elif communityChestDeck[randomnum].getEffect() == "Jail":
                            print("Oh no! You've been sent to jail!")
                            communityChestDeck[randomnum].applyEffect()
                        else:
                            print("You have a Get Out Of Jail Free card now!")
                            communityChestDeck[randomnum].applyEffect()

                # Chance
                elif playerOrder[cp].getSpace() == 7 or playerOrder[cp].getSpace() == 22 or playerOrder[cp].getSpace() == 36: #chance
                    print("Chance! D:")
                    print(playerOrder[cp].getSpace())

                # Income Taxes
                elif playerOrder[cp].getSpace() == 4 or playerOrder[cp].getSpace() == 38:
                    if playerOrder[cp].getSpace() == 4:
                        print("You've landed on income tax! You lost $200.")
                        playerOrder[cp].loseMoney(200)
                        print("Your current balance is:", playerOrder[cp].getMoney())
                        freeParking += 200
                    else:
                        print("You've landed on luxury tax! You lost $100.")
                        playerOrder[cp].loseMoney(100)
                        print("Your current balance is:", playerOrder[cp].getMoney())
                        freeParking += 200
                    print("debug", playerOrder[cp].getSpace())

                # Go To Jail
                elif playerOrder[cp].getSpace() == 31:  # Go To Jail
                    print("Oh no! Go to jail!")
                    playerOrder[cp].getArrested()
                    print(playerOrder[cp].getSpace())

                # Railroads
                elif playerOrder[cp].getSpace() == 5 or playerOrder[cp].getSpace() == 15 or playerOrder[cp].getSpace() == 25 or playerOrder[cp].getSpace() == 35: #railroads

                    print("You landed on", spaces[playerOrder[cp].getSpace()])
                    print("Your balance is", playerOrder[cp].getMoney())
                    if spaces[playerOrder[cp].getSpace()].getOwner() == "Bank":
                        buy = input("Would you like to buy the railroad for $200? (y/n)")
                        if buy == "y":
                            playerOrder[cp].gainProperty(spaces[playerOrder[cp].getSpace()])
                            playerOrder[cp].loseMoney(spaces[playerOrder[cp].getSpace()].getPrice())
                            print("You bought the railroad! Your properties now are:",playerOrder[cp].getProperties())
                            print("Your balance now is:", playerOrder[cp].getMoney())
                            spaces[playerOrder[cp].getSpace()].buyRailroad(playerOrder[cp])

                        else:
                            print()
                    else:
                        print("Oh no! You landed on someone else's railroad! You have to pay the rent now!")
                        playerOrder[cp].loseMoney((spaces[playerOrder[cp].getSpace()]).getRent())
                        (spaces[playerOrder[cp].getSpace()].getOwner).gainMoney(
                            spaces[playerOrder[cp].getSpace()]).getRent()
                        print("Now your balance is", playerOrder[cp].getMoney())

                # Utilities
                elif playerOrder[cp].getSpace() == 12 or playerOrder[cp].getSpace() == 28:
                    print("debug",playerOrder[cp].getSpace())
                    if Electric.getOwner() == "Bank" or Water.getOwner() == "Bank":
                        print("Would you like to buy the Utility?")
                        buy = input("(Y/N)")
                        if buy == "y".lower():
                            if playerOrder[cp].getSpace() == 12:
                                Electric.buyUtility(playerOrder[cp])
                                playerOrder[cp].gainProperty(Electric)
                                playerOrder[cp].loseMoney(Electric.getPrice())
                            else:
                                Water.buyUtility(playerOrder[cp])
                                playerOrder[cp].gainProperty(Water)
                                playerOrder[cp].loseMoney(Water.getPrice())
                        else:
                            print("Ok.")
                    else:
                        if playerOrder[cp].getSpace() == 12:
                            playerOrder[cp].loseMoney(1)  # you should change this
                    print("Utilities! yay!")

                # Free Parking
                elif playerOrder[cp].getSpace() == 20:
                    if freeParking == 0:
                        print("You landed on Free Parking! Congratulations, you get 100 dollars!")
                        playerOrder[cp].gainMoney(100)
                    else:
                        print("You landed on Free Parking! Congratulations! You get",freeParking,"dollars!")
                        playerOrder[cp].gainMoney(freeParking)

                # Just Visiting
                elif playerOrder[cp].getSpace() == 10:
                    print("You've landed on Just Visiting!")

                # Properties
                else:
                    print(playerOrder[cp].getSpace())
                    print("You are on", spaces[playerOrder[cp].getSpace()])
                    print("You have", playerOrder[cp].getMoney(),"dollars")
                    if spaces[playerOrder[cp].getSpace()].getOwner() is None:
                        buy = input("Would you like to buy the property? (y/n)")
                        if buy == "y":
                            playerOrder[cp].gainProperty(spaces[playerOrder[cp].getSpace()])
                            playerOrder[cp].loseMoney(spaces[playerOrder[cp].getSpace()].getPrice())
                            print(playerOrder[cp].getProperties())
                            spaces[playerOrder[cp].getSpace()].buyProperty(playerOrder[cp].getPiece())
                            print("You bought the property! Your properties now are:", playerOrder[cp].getProperties())
                            print("Your balance now is:", playerOrder[cp].getMoney())
                            print(spaces[playerOrder[cp].getSpace()].buyProperty(playerOrder[cp].getPiece()))
                        else:
                            print("")
                    else:
                        print("Oh no! You landed on someone else's property! You have to pay the rent now!")
                        playerOrder[cp].loseMoney((spaces[playerOrder[cp].getSpace()]).getRent())
                        (spaces[playerOrder[cp].getSpace()].getOwner()).gainMoney(spaces[playerOrder[cp].getSpace()]).getRent()
                        print("Now your balance is",playerOrder[cp].getMoney())
                if Die1.getCurrentFace() == Die2.getCurrentFace():
                    if playerOrder[cp].getTimesDoubled() <= 3:
                        cp += 0
                        print("You rolled a double! Since you did, you get to go again!")
                    else:
                        print("You rolled doubles three times! You've been sent to jail!")
                        playerOrder[cp].getInJail()
                        cp += 1
                else:
                    cp += 1

            # Jail area
            else:
                count = 0
                if playerOrder[cp].getTimesJailed() <= 3:
                    while count < 3:
                        Die1.rollDie()
                        Die2.rollDie()
                        print("You rolled:",Die1.getCurrentFace(),"and",Die2.getCurrentFace())
                        if Die1.getCurrentFace() == Die2.getCurrentFace():
                            print("You rolled a double! Have fun out of jail!")
                            playerOrder[cp].outOfJail()
                        else:
                            print("Roll again!")
                            count += 1
                    print("Aw, you didn't roll a double in 3 rolls! Try again next time!")
                    playerOrder[cp].moreTimesInJail()
                    cp += 1
                else:
                    print("You've spent more than three turns in jail!")
                    print("You now have to pay $50")
                    playerOrder[cp].loseMoney(50)
                    print("Your current balance is", playerOrder[cp].getMoney())
                    playerOrder[cp].outOfJail()

    print("Monopoly is over. Hope you had fun.")
 def getSunsetTime(self, location):
     return datetime.fromtimestamp(self.__getWeather(location).get_sunset_time()).strftime(Utility.getValueFromConfigurationFile("time-format"))
Esempio n. 43
0
from RequestInfoLoader import *
from SingleActionProcessor import *
from SiteData import *
from ErrorCode import *
from SiteDataMeihua import *
from MeihuaKeywordLoader import *
from MeihuaDataParser import *
from MeihuaAdType import *
from MeihuaDataWriter import *
from multiprocessing import Pool,Manager
import datetime

startTime = datetime.datetime.now()
requestInfoLoader = RequestInfoLoader(utility)
actionProcessor = SingleActionProcessor()
utility = Utility()
parser = MeihuaDataParser()
writer = MeihuaDataWriter()
useLocalDb = True
printCreateSql = False
dbDryRunMode = False
outputCrawlerDebugInfo = False
catetoryName = {
    "1":['服务公寓','工业用房','海上泊位','墓园','商铺','商务楼','土地','住宅-别墅','住宅-公寓','综合房产','出租与出售','酒店度假村','房地产服务','房地产交易中心'],
    "2":['服务公寓','工业用房','海上泊位','墓园','商铺','商务楼','土地','住宅-别墅','住宅-公寓','综合房产','出租与出售','酒店度假村','房地产服务','房地产交易中心'],
    "6":['服务公寓','工业用房','海上泊位','墓园','商铺','商务楼','土地','住宅-别墅','住宅-公寓','综合房产','出租与出售','酒店度假村','房地产服务','房地产交易中心'],
    "3":['房'],
    "4":['房地产类|房地产类|楼盘宣传','房地产类|房地产类|商业街','房地产类|房地产类|商务出租','房地产类|房地产类|建筑器材服务','房地产类|房地产类|房地产企业形象','房地产类|房地产类|房产中介','房地产类|装潢设计|装潢/设计'],
    "5":['房地产']
}
cityName = {
Esempio n. 44
0
 def __init__ (self, data, code, configuration):
     Utility.__init__(self)
     Debug.__init__(self)
     self.data           = data
     self.code           = code
     self.configuration  = configuration
 def getCurrentSystemDate(self):
     return datetime.now().strftime(Utility.getValueFromConfigurationFile("date-format"))
def main():
    utils = Utility()
    f = open('data.csv', 'w')
    f.write('vertices,penalization,stddev,avg\n')

    # run experimens
    for Kn in range(Properties.Kn_min, Properties.Kn_max):
        all_costs = []
        for i in range(2):  # 0 - without penalization, 1 - with penalization
            for experiment in range(Properties.experiment_limit):
                print "[START] experiment", experiment, "for N", Kn

                # simulated annealing initialization
                total_iterations = 1
                T = Properties.Tmax
                vertices = utils.generate_initial_vertices(Kn)
                edges = utils.generate_edges(Kn)
                g = Graph(vertices, edges)  # g is initial randomly generated graph
                all_costs.append(g.crossingNumber)
                print "> init crossing number", g.crossingNumber

                # utils.draw_graph(g)

                # 3. step: loop until stop condition is met
                # stop condition:
                #   - temperature is cooled
                #   - good-enough solution has been found
                temperatures = []
                intersections = []  # aka fitnesses
                while T > Properties.Tmin:
                    # temperatures.append(T)
                    # intersections.append(g.get_crossing_number())

                    if g.get_crossing_number() == Properties.Min_CrossingNumber[Kn]:
                        break  # end if solution has been found
                    total_iterations += Properties.Kmax

                    # simulated annealing core
                    if i == 0:  # not penalized
                        metropol = utils.metropolis_algorithm(g, Properties.Kmax, T, False)
                    else:  # penalized
                        metropol = utils.metropolis_algorithm(g, Properties.Kmax, T, True)
                    g = metropol[0]  # save new graph
                    metr_run_costs = metropol[1]
                    all_costs.extend(metr_run_costs)

                    T = Properties.alpha * T  # cooldown system - slowly cooling down the system

                    if Properties.debug:
                        print "[INFO] temp", T, "iter", total_iterations, "cross", g.get_crossing_number()

                print "> final crossing number", g.get_crossing_number()
                print "[END] total iterations", total_iterations, "\n----------------------------\n"

            f.write(str(Kn) + ',')
            if i == 0:
                f.write('FALSE,')
            else:
                f.write('TRUE,')
            f.write(str(np.std(all_costs)) + ',' + str(np.average(all_costs)) + '\n')
    f.close()
Esempio n. 47
0
#!/usr/bin/env python

from Utility import Utility

utility = Utility()

imagePayLoad = """------WebKitFormBoundary9Vj7shUQsQewcabN
Content-Disposition: form-data; name="%==>FILE_NAME<==%"; filename="%==>FILE_NAME<==%"
Content-Type: image/jpeg
------WebKitFormBoundary9Vj7shUQsQewcabN--
"""

dataPayLoad = {
  'data_params' : {
    'action' : "post using %==>CONTENT_TYPE<==%",
  },
}

input = {
  'STRINGKEY1' : "AFSL",
  'OBJECTKEY1' : {'test' : 'zzxv'},
  'OBJECTKEY2' : {'test' : 'zzxv'},
  'HOST_NAME' : 'www.test.com',
  'FILE_NAME' : 'test.jpg',
  'CONTENT_TYPE' : 'JPEG',
  'IMAGE_PAY_LOAD' : imagePayLoad,
  'DATA_PAY_LOAD' : dataPayLoad
}

value1 = "asdfa asdf%==>STRINGKEY1<==%weurou"
value2 = "asdfa asdf%==>STRINGKEY2<==%weurou"
 def __init__(self):
     self._owm = pyowm.OWM(Utility.getValueFromConfigurationFile("open-weather-api-key"))
# import pyowm
from Utility import Utility

'''from ResponseGenerator import ResponseGenerator
#class WeatherDataApi:

owm = pyowm.OWM('ecb73e81c510fd8cc1457529463be966')
observation = owm.weather_at_place("Dhaka, BD")
w = observation.get_weather()
wind = w.get_wind()

# print(w)
print(w.get_detailed_status())
# print(w.get_temperature('celsius'))
# print(wind)
print(w.get_humidity())

# print(owm.is_API_online())
'''
# print(Utility.__getValueFromFile(".\\configuration.ini", port))

print(Utility.getData('hello', Utility.getDataFrame("response.xlsx")))