コード例 #1
0
    def copyFile(sourceFile, targetFile):
        Common.assertExit(os.path.isfile(sourceFile), "源文件不存在" + sourceFile)

        # 创建目标文件夹
        targetDir = FileUtils.getFileDirectory(targetFile)
        FileUtils.createDirectory(targetDir)
        shutil.copy(sourceFile, targetFile)
コード例 #2
0
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.init_Ui()
        self.com = Common()
        self.title = [
            u"COUNT", u"CPU(%)", u"MEM(M)", u"FPS", u"Wifi下行(KB/S)",
            u"Wifi上行(KB/S)", u"下载流量(MB)", u"上传流量(MB)", u"Wifi总流量(MB)",
            u"移动网络下行(KB/S)", u"移动网络上行(KB/S)", u"下载流量(MB)", u"上传流量(MB)",
            u"移动网络总流量(MB)", u"温度", "Drawcall", u"电量"
        ]
        self.excel_path = "D:\PerfReport"
        # self.create_excel()
        self.getData = 0

        BufferSize = 1  #同时并发的线程数
        FpsS = QSemaphore(BufferSize)  # cpu并发锁
        CpuS = QSemaphore(0)
        DrawcallS = QSemaphore(0)
        NetS = QSemaphore(0)
        MemS = QSemaphore(0)
        TempS = QSemaphore(0)
        BatteryS = QSemaphore(0)
        TimeS = QSemaphore(0)
        self.lock = {}  #并发锁词典
        self.lock['cpu'] = CpuS
        self.lock['fps'] = FpsS
        self.lock['drawcall'] = DrawcallS
        self.lock['net'] = NetS
        self.lock['mem'] = MemS
        self.lock['temp'] = TempS
        self.lock['battery'] = BatteryS
        self.lock['time'] = TimeS
        self.dw = Draw()
        self.isCollect = 0
コード例 #3
0
 def save_word2vec_format(self, dest, source):
     with tf.variable_scope('model', reuse=None):
         if source is VocabType.Token:
             vocab_size = self.word_vocab_size
             embedding_size = self.config.EMBEDDINGS_SIZE
             index = self.index_to_word
             var_name = 'WORDS_VOCAB'
         elif source is VocabType.Target:
             vocab_size = self.target_word_vocab_size
             embedding_size = self.config.EMBEDDINGS_SIZE * 3
             index = self.index_to_target_word
             var_name = 'TARGET_WORDS_VOCAB'
         else:
             raise ValueError(
                 'vocab type should be VocabType.Token or VocabType.Target.'
             )
         embeddings = tf.get_variable(var_name,
                                      shape=(vocab_size + 1,
                                             embedding_size),
                                      dtype=tf.float32,
                                      trainable=False)
         self.saver = tf.train.Saver()
         self.load_model(self.sess)
         np_embeddings = self.sess.run(embeddings)
     with open(dest, 'w') as words_file:
         Common.save_word2vec_file(words_file, vocab_size, embedding_size,
                                   index, np_embeddings)
コード例 #4
0
    def handle_menu(user):
        '''
        Allows to choose an action to perform.
        '''
        options = ['View grades', "Submit an assignment", 'View attandence']

        while True:

            Ui.print_message(('\n...:::Logged in as {}:::...\n').format(user))
            Ui.print_menu("What do you want to do?", options, 'Exit')
            inputs = Ui.get_inputs(["Please enter a number: "], "")
            option = inputs[0]

            if option == '1':
                StudentMenu.show_grades(user)

            elif option == '2':
                os.system('clear')
                user.submit_assignment()

            elif option == '3':
                StudentMenu.show_attendance(user)

            elif option == '0':
                Common.write_submission_to_db('database.db',
                                              Submission.submission_list)
                sys.exit()
            else:
                Ui.print_message('There is no such option.')
コード例 #5
0
    def __init__(self):
        self.api_key = 'AIzaSyC7SQ-1m0M6dN9L4E2aUhTM1ihAfTXIA0k '
        self.date_val = []
        self.date = []
        self.regex_val = ''

        self.result = {}

        self.keys = []
        self.values = []
        self.description = []

        self.name = Queue()
        self.actual_date = []
        self.date_val1 = []
        self.zip_code = []
        self.licence_id = ''
        self.regex_value = []
        self.code = ''
        self.first_name_original,self.last_name_original,self.middle_name_original,self.first_name_processed,self.last_name_processed,self.middle_name_processed={},{},{},{},{},{}
        self.regex_value,self.street,self.address,self.full_address=[],[],[],[]
        self.street_address_original,self.state_original,self.city_original,self.zip_code_original,self.street_address_processed,self.state_processed,self.city_processed,self.zip_code_processed={},{},{},{},{},{},{},{}
        self.failure_regex = ''
        self.c = Common()

        with open('../config/city.json', 'r') as data_file:
            self.cities = json.load(data_file)
        with open('../config/filtering.json', 'r') as data:
            self.state_value = json.load(data)
コード例 #6
0
 def wait_system_activation_page(cls, sn):
     try:
         co.reboot_device(sn)
         time.sleep(random.randint(30, 40))
         logger.log_info("wait adb alive", \
                         sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name,
                         sys._getframe().f_lineno)
         adb_object.check_adb_device_isalive()
         os.system('adb root')
         time.sleep(random.randint(3, 6))
         while True:
             Result = subprocess.check_output(
                 'adb -s %s shell "%s|%s wc -l"' %
                 (sn, system_activation_pid, busybox),
                 shell=True)
             print("antony@@debug")
             Result = co.removal(Result)
             print("antony@@@debug %s" % (Result))
             if int(Result) == 1:
                 logger.log_info("system activation has showed", \
                                 sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name,
                                 sys._getframe().f_lineno)
                 return 0
             time.sleep(random.randint(5, 10))
     except Exception as e:
         logger.log_error("%s" %(e), \
                          sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name,
                          sys._getframe().f_lineno)
コード例 #7
0
def login():
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                #if helpers.credentials_valid(username, password):
                session['logged_in'] = True
                session['username'] = username
                return json.dumps({'status': 'Login successful'})
            #return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    user = helpers.get_user()
    sskey = ""
    if 'keyword' in session:
        sskey = session["keyword"]
    simages = ""
    if 'imagePath' in session:
        if session['imagePath'] != "":
            imagePath = session['imagePath']
            print(imagePath)
            if (sskey == ""):
                return render_template("home.html", user=user)
            commonF = Common()
            simages = commonF.sprkSQLReadDFtoList(imagePath, sskey)

            sskey = "You are searching " + sskey
    return render_template('home.html',
                           user=user,
                           searchkey=sskey,
                           hists=simages)
コード例 #8
0
ファイル: Model.py プロジェクト: XLab-Tongji/DeepLearning-SDP
    def predict(self, predict_data_lines):
        if self.predict_queue is None:
            self.predict_queue = PathContextReader.PathContextReader(word_to_index=self.word_to_index,
                                                                     path_to_index=self.path_to_index,
                                                                     target_word_to_index=self.target_word_to_index,
                                                                     config=self.config, is_evaluating=True)
            self.predict_placeholder = self.predict_queue.get_input_placeholder()
            self.predict_top_words_op, self.predict_top_values_op, self.predict_original_names_op, \
            self.attention_weights_op, self.predict_source_string, self.predict_path_string, self.predict_path_target_string = \
                self.build_test_graph(self.predict_queue.get_filtered_batches(), normalize_scores=True)

            self.initialize_session_variables(self.sess)
            self.saver = tf.train.Saver()
            self.load_model(self.sess)

        results = []
        for batch in Common.split_to_batches(predict_data_lines, 1):
            top_words, top_scores, original_names, attention_weights, source_strings, path_strings, target_strings = self.sess.run(
                [self.predict_top_words_op, self.predict_top_values_op, self.predict_original_names_op,
                 self.attention_weights_op, self.predict_source_string, self.predict_path_string,
                 self.predict_path_target_string],
                feed_dict={self.predict_placeholder: batch})
            top_words, original_names = Common.binary_to_string_matrix(top_words), Common.binary_to_string_matrix(
                original_names)
            # Flatten original names from [[]] to []
            attention_per_path = self.get_attention_per_path(source_strings, path_strings, target_strings,
                                                             attention_weights)
            original_names = [w for l in original_names for w in l]
            results.append((original_names[0], top_words[0], top_scores[0], attention_per_path))
        return results
コード例 #9
0
    def getPsuadeInstalledModules():

        libs = ['MARS','TPROS','SVM','METIS']
        foundLibs = dict()
        for lib in libs:
            foundLibs[lib] = False
            
        #psuadePath = LocalExecutionModule.getPsuadePath(False)
        psuadePath = LocalExecutionModule.getPsuadePath()
        if psuadePath is None:
#            return foundLibs
            raise Exception('PSUADE path not set!')
        
        p = subprocess.Popen(psuadePath + ' --info',
                             stdin=None,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             shell=True)
        # process error        
        out, error = p.communicate()
        if error:
            Common.showError(error, out)
            return foundLibs

        # parse results
        lines = out.splitlines()
        installedString = 'installed... true'; 
        if len(lines) >= 2:
            for line in lines:   # skip first line with version info
                for lib in libs:
                    if (lib in line) and (installedString in line):
                        foundLibs[lib] = True
                        break

        return foundLibs
コード例 #10
0
    def getFactionAverageGameInterestStats(self, sFactionName):
        gameEndDatas = self.getGameEndDatasWithFaction(sFactionName)
        iNumEntries = len(gameEndDatas)
        if not gameEndDatas:
            return 0, 0, 0, 0

        fInterest = 0
        fTimesPlayed = 0
        fAverageScore = 0
        fFactionPlusMinus = 0
        for gameEndData in gameEndDatas:
            fInterest += gameEndData.m_fGameInterest
            fTimesPlayed += gameEndData.m_fTimesPlayed
            fAverageScore += gameEndData.m_fAverageScore

            for factionGameEndData in gameEndData.m_lFactionGameEndDatas:
                if factionGameEndData.m_Faction.m_sFactionName == sFactionName:
                    fFactionPlusMinus += factionGameEndData.m_fScore * 6 - gameEndData.m_fAverageScore
                    break

        return Common.floatround(fInterest / iNumEntries,
                                 4), Common.floatround(
                                     fFactionPlusMinus / (iNumEntries * 6),
                                     1), iNumEntries, round(
                                         fTimesPlayed / iNumEntries, 2)
コード例 #11
0
class BatteryThread(QThread, Common):

    trigger = pyqtSignal(int, bool)

    def __init__(self, excel, sheet, workbook, interval, durtime, package,
                 lock):
        super(QThread, self).__init__()
        self.excel = excel
        self.interval = interval
        self.durtime = durtime
        self.package = package
        self.sheet = sheet
        self.workbook = workbook
        self.btn_enable = False
        self.lock = lock
        self.com = Common()

    def run(self):
        try:
            row = 0
            durtime = self.durtime.replace("min", "")
            interval = self.interval.replace("s", "")
            durtime = int(durtime) * 60
            interval = int(interval)
            n = int(durtime / interval)

            for i in range(n):
                sleep_interval = 0.001
                start_time = time.time()
                if self.check_adb(self.package) == 1:
                    cmd = self.com.adb + " shell dumpsys battery"
                    res = self.execshell(cmd)
                    while res.poll() is None:
                        line = res.stdout.readline().decode('utf-8', 'ignore')
                        if line != "":
                            if 'level' in line:
                                line = re.findall('level\:\s(\d+)', line).pop()
                                line = int(line)

                                self.lock['battery'].acquire()
                                self.trigger.emit(line, self.btn_enable)
                                row += 1
                                self.sheet.write(row, 16, line)
                                self.lock['mem'].release()
                                # print("mem release %d" % (self.lock['mem'].available()))

                    while (time.time() -
                           start_time) * 1000000 <= interval * 1000000:
                        sleep_interval += 0.0000001
                        sleep(sleep_interval)
                    end_time = time.time()
                    # avg = (end_time-start_time)*1000
                    # print("Battery为%f" % avg)

            self.btn_enable = True
            self.trigger.emit(0, self.btn_enable)
            # self.workbook.save(self.excel)
        except Exception:
            self.com.writeLog().info(traceback.format_exc())
コード例 #12
0
ファイル: Model.py プロジェクト: XLab-Tongji/DeepLearning-SDP
 def get_attention_per_path(self, source_strings, path_strings, target_strings, attention_weights):
     attention_weights = np.squeeze(attention_weights)  # (max_contexts, )
     attention_per_context = {}
     for source, path, target, weight in zip(source_strings, path_strings, target_strings, attention_weights):
         string_triplet = (
             Common.binary_to_string(source), Common.binary_to_string(path), Common.binary_to_string(target))
         attention_per_context[string_triplet] = weight
     return attention_per_context
コード例 #13
0
    def setForKey(plistPath, key, value):
        Common.assertExit(os.path.isfile(plistPath), plistPath + "文件不存在")

        if Plist.isKeyExist(plistPath, key):
            cmd = '/usr/libexec/PlistBuddy -c "Set :%s %s" %s' % (key, value,
                                                                  plistPath)
            return Common.runCmd(cmd)
        Plist.addStringForKey(plistPath, key, value)
コード例 #14
0
 def setUp(self):
     print("--setUp")
     # Get the current file name which will be output to the log
     gloVar.caseName = os.path.basename(__file__)[:-3]
     # Initial automation script
     self.common = Common()
     gloVar.common = self.common
     self.common.timeOut(30)
コード例 #15
0
ファイル: Encoder.py プロジェクト: yws/shedskin
 def __init__(self, inputStream, outputStream, options):
     Common.__init__(self, inputStream, outputStream, options)
     self.rcBuffer = 0
     self.rcRange = 0x7fffffff
     self.xFFRunLength = 0
     self.lastOutputByte = 0
     self.delay = False
     self.carry = False
コード例 #16
0
ファイル: Encoder.py プロジェクト: GINK03/shedskin
 def __init__(self, inputStream, outputStream, options):
     Common.__init__(self, inputStream, outputStream, options)
     self.rcBuffer = 0
     self.rcRange = 0x7fffffff
     self.xFFRunLength = 0
     self.lastOutputByte = 0
     self.delay = False
     self.carry = False
コード例 #17
0
ファイル: patent.py プロジェクト: DongDong-123/zgg_active
 def __init__(self):
     self.common = Common()
     self.timetemp = time.strftime("%Y-%m-%d-%H-%M-%S",
                                   time.localtime())  # 存储Excel表格文件名编号
     self.db = "case"
     self.dboperate = DbOperate()
     self.windows = None
     self.report_path = ReadConfig().save_report()
     self.catlog = 1
コード例 #18
0
 def Run(cls):
     templateApi = groupdocs_parser_cloud.TemplateApi.from_config(Common.GetConfig())
     options = groupdocs_parser_cloud.CreateTemplateOptions()
     options.template = Common.GetTemplate()
     options.template_path = "templates/template-for-companies.json"
     request = groupdocs_parser_cloud.CreateTemplateRequest(options)
     response = templateApi.create_template(request)
     
     print("Path to saved template in storage: " + response.template_path + ". Link to download template: " + response.url);
コード例 #19
0
def up_photo():
    img = request.files.get('photo')
    #username = request.form.get("name")
    if (not img):
        return redirect('/')
    if not (img and allowed_file(img.filename)):
        return jsonify({
            "error": 1001,
            "msg": "Only support .png .PNG .jpg .JPG .bmp .gif"
        })
    path = basedir + "/static/photo/"
    imgfilename = img.filename.encode("utf-8").decode("latin1")
    file_path = path + imgfilename
    img.save(file_path)
    '''
    encoded_string=""
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    #print (encoded_string)
    '''
    imgType = imghdr.what(file_path)
    imagebase64 = base64.b64encode(open(file_path, 'rb').read())
    commonF = Common()
    #if (not commonF.sparkSQLIsRepeat('04122019203919021146.txt',str(imagebase64, 'utf-8'))):
    #    return redirect('/')
    x = commonF.readImageText(file_path, "all")
    x = re.sub('\s', '', x)
    x = x.replace('\n', '').replace(' ', '').replace('|', '')
    x = ("NoTag") if x == "" else (x.lower())
    sstring = img.filename + "|" + x + "|data:image/" + imgType + ";base64," + str(
        imagebase64, 'utf-8')
    nowstring = sstring.encode("utf-8").decode("latin1")

    print("here here here here")
    conf = SparkConf(
    )  #.setAppName("Upload One Image to HDFS").setMaster("yarn")
    #sc = SparkContext(conf=conf)
    sc = SparkContext.getOrCreate(conf=conf)
    sqlContext = SQLContext(sc)

    uploadedDF = sc.parallelize([
        (img.filename, x,
         "data:image/" + imgType + ";base64," + str(imagebase64, 'utf-8'))
    ]).toDF(["path", "features", "binary"])
    uploadedDF.write.mode('append').parquet(
        dataFrameUrl)  #("hdfs://gpu3:9000/dataFrames/final9")
    print(nowstring)
    #file = '04122019203919021146.txt'
    #with open(file, 'a+') as f:
    #    f.write(nowstring)
    #    f.write('\n')
    #    f.close()
    #   with hdfs.open('hdfs://gpu3:9000/wuxi/04122019203919021146.txt', 'a') as f:
    #       f.write(nowstring)
    #return render_template('home.html')
    return redirect('/')
コード例 #20
0
def talker():
    calc = 'calculated'
    pub = rospy.Publisher('calc_done', String, queue_size=10)
    rospy.init_node('mapcalc', anonymous=True)
    common = Common()
    common.Init()
    common.Frame()
    if not rospy.is_shutdown():
        rospy.loginfo(calc)
        pub.publish(calc)
コード例 #21
0
    def replaceContent(sourceContent, targetContent, filePath):
        Common.assertExit(os.path.isfile(filePath), "文件不存在")

        with open(filePath, "r") as f:
            lines = f.readlines()
        with open(filePath, "w") as f_w:
            for line in lines:
                strinfo = re.compile(sourceContent)
                b = strinfo.sub(targetContent, line)
                f_w.write(b)
コード例 #22
0
 def getDirectorysFromDirectory(dirPath):
     Common.assertExit(os.path.isdir(dirPath), "文件夹不存在:" + dirPath)
     dirPaths = []
     dirNames = []
     for fileName in os.listdir(dirPath):
         path = os.path.join(dirPath, fileName)
         if os.path.isdir(path):
             Array.insert(dirPaths, path)
             Array.insert(dirNames, fileName)
     return dirPaths, dirNames
コード例 #23
0
 def __init__(self):
     try:
         self.__usrInpt = -1
         self.common = Common("KEY.txt", "ENC.txt")
         self.keyGeneration = KeyGeneration(self.common)
         self.encryption = Encryption(self.common)
         self.decryption = Decryption(self.common)
         self.breakEncryption = BreakEncryption(self.common)
     except Exception as ex:
         print("An error occurred while initializing class Main. Error: ",
               ex)
コード例 #24
0
    def __init__(self, image_level=None):
        """ Builds the object

        Parameters
        ----------
        image_level : bool
            Whether using image-level dataset, set to False if using bounding boxes, by default is True
        """

        self.image_level = True if image_level is None else image_level
        self.common = Common(self.image_level)
コード例 #25
0
    def maskdata(v, vmin, vmax):

        vm = np.ma.array(v)
        vm = np.ma.masked_where(vm < vmin, vm)  # mask data below min value
        vm = np.ma.masked_where(vm > vmax, vm)  # mask data above max value

        if vm.mask.all():   # if all values are masked (i.e., no valid data)
            error = 'Visualizer: Data lies within [%f, %f] (outside of specified range [%f, %f]).' % (min(v), max(v), vmin, vmax)
            Common.showError(error)
            vm = None

        return vm
コード例 #26
0
ファイル: InputParser.py プロジェクト: ckreid/PythonSandbox
def calculateInterest(fCubeScore, inputFaction):
    fInterest = 1.4
    bConverged = False
    while not bConverged:
        fDummyFinalScore = calculateFinalScore(fInterest, inputFaction)
        if Common.floatround(fDummyFinalScore, 2) == fCubeScore:
            bConverged = True

        fInterest = fInterest + 0.3 * (
            (fCubeScore - fDummyFinalScore) / fCubeScore)

    return Common.floatround(fInterest, 4)
    def Run(cls):
        # For example purposes create template if not exists.
        Common.CreateIfNotExist("templates/companies.json")

        templateApi = groupdocs_parser_cloud.TemplateApi.from_config(
            Common.GetConfig())
        options = groupdocs_parser_cloud.TemplateOptions()
        options.template_path = "templates/template-for-companies.json"
        request = groupdocs_parser_cloud.DeleteTemplateRequest(options)
        response = templateApi.delete_template(request)

        print("Done.")
コード例 #28
0
ファイル: Time.py プロジェクト: performance12345/PerfCat-0609
class TimeThread(QThread, Common):

    trigger = pyqtSignal(str)

    def __init__(self, excel, sheet, workbook, interval, durtime, package,
                 lock):
        super(QThread, self).__init__()
        self.excel = excel
        self.interval = interval
        self.durtime = durtime
        self.package = package
        self.sheet = sheet
        self.workbook = workbook
        self.btn_enable = False
        self.lock = lock
        self.com = Common()

    def run(self):
        try:
            durtime = self.durtime.replace("min", "")
            interval = self.interval.replace("s", "")
            durtime = int(durtime) * 60
            interval = int(interval)
            n = int(durtime / interval)
            name = self.get_package(self.package)

            for i in range(n):
                start_time = time.time()
                sleep_interval = 0.001

                durtime -= interval
                min = int(durtime / 60)
                sec = (durtime % 60)
                timeCount = str(min) + ":" + str(sec)

                self.lock['time'].acquire()
                self.trigger.emit(timeCount)
                self.lock['fps'].release()
                # print("fps release %d" % (self.lock['fps'].available()))

                while (time.time() -
                       start_time) * 1000000 <= interval * 1000000:
                    sleep_interval += 0.0000001
                    time.sleep(sleep_interval)
                end_time = time.time()
                # avg = (end_time - start_time) * 1000
                # print("内存为%f" % avg)

            # print("time over")
            self.trigger.emit("0")
            # self.workbook.save(self.excel)
        except Exception:
            self.com.writeLog().info(traceback.format_exc())
コード例 #29
0
ファイル: Time.py プロジェクト: performance12345/PerfCat-0609
 def __init__(self, excel, sheet, workbook, interval, durtime, package,
              lock):
     super(QThread, self).__init__()
     self.excel = excel
     self.interval = interval
     self.durtime = durtime
     self.package = package
     self.sheet = sheet
     self.workbook = workbook
     self.btn_enable = False
     self.lock = lock
     self.com = Common()
コード例 #30
0
    def analyze(self):
        data = self.ensemble.getValidSamples()
        Common.initFolder(RawDataAnalyzer.dname)
        fname = Common.getLocalFileName(RawDataAnalyzer.dname, data.getModelName().split()[0], '.dat')
        data.writeToPsuade(fname)

        #perform UA
        mfile = RawDataAnalyzer.performCA(fname, self.outputs[0])
        
        #archive file
        if mfile is not None:
            self.archiveFile(mfile)
        return mfile
コード例 #31
0
def getStickerwithPrice(sticker):
    found = False
    with open("Sticker.csv", 'r', encoding="utf-8") as readFile:
        reader = csv.reader(readFile)
        for row in reader:
            sticker_name = row[0]
            if sticker_name == sticker:
                found = True
                return convertPrice(row[1], 'USD')
        # print("Name: {0}. Price {1}".format(sticker_name,sticker_price))
        if found is False:
            print("Sticker not found: " + sticker_name)
            Common.sendLog("info", sticker_name + "Not found")
コード例 #32
0
class ResultController:
    def __init__(self):
        self.common_tools = Common()
        self.search_type = self.common_tools.enum(SubDirectory=1, FileName=2, FileContent=3)

    @staticmethod
    def convert_item_to_result_object(item, current_root_directory, current_search_type, item_content=None):
        result_dictionary = {}

        result_dictionary["size"] = getsize(join(current_root_directory, item))
        result_dictionary["is_directory"] = os.path.isdir(os.path.join(os.path.expanduser(current_root_directory), item))
        result_dictionary["root_directory"] = str(current_root_directory)
        result_dictionary["name"] = str(item)
        result_dictionary["search_type"] = current_search_type

        if not item_content is None:
            result_dictionary["item_content"] = item_content

        return result_dictionary

    def convert_list_to_result_object_dictionary(self, current_list, last_dict_enumerator, current_root_directory,
                                                 current_search_type):
        dictionary_enumerator = last_dict_enumerator
        new_dictionary = {}

        for item in current_list:
            assert isinstance(item, str)
            dictionary_enumerator += 1

            new_dictionary[dictionary_enumerator] = self.convert_item_to_result_object(item, current_root_directory,
                                                                                       current_search_type)

        return new_dictionary
コード例 #33
0
ファイル: crunchyDec.py プロジェクト: Astoriane/jCrunchyroll
	def generateKey(self, mediaid, size = 32):
		# Below: Do some black magic
		eq1 = int(int(math.floor(math.sqrt(6.9) * math.pow(2, 25))) ^ mediaid)
		eq2 = int(math.floor(math.sqrt(6.9) * math.pow(2, 25)))
		eq3 = (mediaid ^ eq2) ^ (mediaid ^ eq2) >> 3 ^ eq1 * 32
		# Below: Creates a 160-bit SHA1 hash 
		shaHash = sha.new(self.createString([20, 97, 1, 2]) + str(eq3)) 
		finalHash = shaHash.digest()
		hashArray = Common().createByteArray(finalHash)
		# Below: Pads the 160-bit hash to 256-bit using zeroes, incase a 256-bit key is requested
		padding = [0]*4*3
		hashArray.extend(padding)
		keyArray = [0]*size
		# Below: Create a string of the requested key size
		for i, item in enumerate(hashArray[:size]):
			keyArray[i] = item
		return Common().ByteArrayToString(keyArray)
コード例 #34
0
 def __init__(self):
     self.common_tools = Common()
     self.notification_category = self.common_tools.enum(Normal=Style.NORMAL + Fore.CYAN,
                                                         Large_Header=Style.BRIGHT + Back.RED + Fore.WHITE,
                                                         Header=Style.BRIGHT + Back.WHITE + Fore.BLACK,
                                                         Small_Header=Style.NORMAL + Fore.MAGENTA,
                                                         Small_Print=Style.NORMAL + Fore.GREEN,
                                                         Warning=Style.BRIGHT + Fore.YELLOW,
                                                         Error=Style.BRIGHT + Fore.RED,
                                                         Style=Style.NORMAL + Fore.BLUE)
 def test_search_verify_picture(self):
     common_obj = Common(self.driver)
     elem = common_obj.wait_for_element_visibility(5, "name", 'q')
     common_obj.fill_out_field('name', 'q', 'leatherback')
     elem.send_keys(Keys.RETURN)
     common_obj.wait_for_element_visibility(5, 'xpath',
                                            "//div[@class='wsite-search-product-image-container']"
                                            )
     time.sleep(3)
コード例 #36
0
class OutputInteraction:
    def __init__(self):
        self.common_tools = Common()

    def request_result_item(self, search_directory, result_dictionary, input_message):
        message_tool = NotificationController()
        user_input = raw_input(input_message)

        # If escape key is pressed then escape method
        if user_input == '':
            return

        # If the input provided is not a number indicate to user and continue to loop through method until correct input
        # provided.
        if not user_input.isdigit():
            message_tool.print_with_style("No such option exists", message_tool.notification_category.Warning)
            return self.request_result_item(search_directory, result_dictionary, input_message)

        # If the input provided is not a number indicate to user and request another option
        if not user_input.isdigit():
            user_input = raw_input("")

        current_operating_system = self.common_tools.get_operating_system()

        # Make sure that the requested key exists otherwise return a message.
        if int(user_input) in result_dictionary:
            if result_dictionary[int(user_input)]["is_directory"]:
                message_tool.print_with_style(os.path.join(
                    os.path.expanduser(result_dictionary[int(user_input)]["root_directory"]),
                    result_dictionary[int(user_input)]["name"]), message_tool.notification_category.Header)
                print ""
                if current_operating_system == "Windows":
                    subprocess.check_call(["dir", os.path.join(
                        os.path.expanduser(result_dictionary[int(user_input)]["root_directory"]),
                        result_dictionary[int(user_input)]["name"])])
                else:
                    subprocess.check_call(["ls", "-l",
                                           os.path.join(os.path.expanduser(
                                               result_dictionary[int(user_input)]["root_directory"]),
                                               result_dictionary[int(user_input)]["name"])])
            else:
                # os.system('vi %s' % search_results[int(user_input)])
                subprocess.call(["nano",
                                       os.path.join(os.path.expanduser(
                                           result_dictionary[int(user_input)]["root_directory"]),
                                           result_dictionary[int(user_input)]["name"])])
        else:
            message_tool.print_with_style("No such option exists.", message_tool.notification_category.Warning)
            return self.request_result_item(search_directory, result_dictionary, input_message)
コード例 #37
0
    def callme(self):
        print "++++++++++++++++++++++ Regression Week 3: Polynomial Regression ++++++++++++++++++++++"
        cmnHandle = Common()
        df_train = cmnHandle.readcsv("../data/kc_house_train_data.csv")
        df_test = cmnHandle.readcsv("../data/kc_house_test_data.csv")

        tmp = np.array(range(3))
        print cmnHandle.polynomial_sframe(tmp, 3)

        poly1_data = cmnHandle.polynomial_sframe(df_train["sqft_living"], 1)

        print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
コード例 #38
0
class NotificationController:
    def __init__(self):
        self.common_tools = Common()
        self.notification_category = self.common_tools.enum(Normal=Style.NORMAL + Fore.CYAN,
                                                            Large_Header=Style.BRIGHT + Back.RED + Fore.WHITE,
                                                            Header=Style.BRIGHT + Back.WHITE + Fore.BLACK,
                                                            Small_Header=Style.NORMAL + Fore.MAGENTA,
                                                            Small_Print=Style.NORMAL + Fore.GREEN,
                                                            Warning=Style.BRIGHT + Fore.YELLOW,
                                                            Error=Style.BRIGHT + Fore.RED,
                                                            Style=Style.NORMAL + Fore.BLUE)

    def print_with_style(self, output, notification_category):
        # Initialize colorama object
        init()

        if not notification_category:
            notification_category = self.notification_category.Normal

        print notification_category + output + Style.RESET_ALL
コード例 #39
0
ファイル: Decoder.py プロジェクト: GINK03/shedskin
 def __init__(self, inputStream, outputStream, options):
     Common.__init__(self, inputStream, outputStream, options)
     self.started = False
     self.nextHighBit = 0
     self.rcBuffer = 0
     self.rcRange = 0
コード例 #40
0
 def __init__(self):
     self.common_tools = Common()
コード例 #41
0
 def __init__(self):
     self.common_tools = Common()
     self.search_type = self.common_tools.enum(SubDirectory=1, FileName=2, FileContent=3)