Beispiel #1
0
def run():
    try:
        if client.protocol == IoTHubTransportProvider.MQTT:
            synchronizeDeviceTwin()

        while True:
            send = False
            for sensor in s.sensor:
                time.sleep(0.4)
                readValue(sensor)
                if (checkData(sensor)):
                    send = True
            if (send):
                print("sending")
                checkTimeouts()
                sendMessage()
                status = client.get_send_status()

    except IoTHubError as iothub_error:
        logging.DEBUG("DEBUG: {0} Unexpected error {1} from IoTHub".format(
            dt.datetime.now(), iothub_error))

        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except IoTHubClientError as iotclient_error:
        logging.DEBUG(
            "DEBUG: {0} Unexpected error {1} from IoTHubclient".format(
                dt.datetime.now(), iothub_error))
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
        print_last_message_time(client)
Beispiel #2
0
def tesa(a):
    logging.info("into the function tesa ")
    #logging.critical("the function got the value "+str(a))
    logging.critical("the function got the value " + str(a))
    logging.error("the function got the value " + str(a))
    logging.warning("the function got the value " + str(a))
    pdb.set_trace()
    logging.info("the function got the value " + str(a))
    logging.debug("the function got the value " + str(a))

    try:
        b = a / 2
    except Exception as ex:
        logging.DEBUG("an exception has occured DEBUG")

        logging.INFO("an exception has occuredINFO")

        logging.WARNING("an exception has occuredWARNING")

        logging.ERROR("an exception has occuredERROR")

        logging.CRITICAL("an exception has occuredCRITICAL")
        logging.CRITICAL(str(ex))
        logging.ERROR(str(ex))
        logging.WARNING(str(ex))
        logging.INFO(str(ex))
        logging.DEBUG(str(ex))
Beispiel #3
0
def readStaticText(window):
    try:
        statictextofcurrentwindow = window.staticTextsR()
        logging.DEBUG("Statictext in the current window")
    except Exception as er:
        logging.DEBUG("Not able to read the static text")
    return False
    return statictextofcurrentwindow
Beispiel #4
0
 def browserlaunch(self,browsername):
     self.drowsername = browsername
     logging.info("To Launch URL setting the browser to open :"+ self.drowsername)
     #path = application_path()
     try:
         if self.drowsername == "Chrome":
             try:
                 self.curr_caps = webdriver.DesiredCapabilities.CHROME.copy()
                 self.driver = webdriver.Chrome(executable_path=drivepath.Chromedriverpath)
                 #,desired_capabilities=self.curr_caps
                 logging.info("Broswer launch success")
                 driver = self.driver
                 driver.maximize_window()
             except:
                 logging.info("Unable to launch browser due to some error plZ Chcek driver path need to update")
                 logging.DEBUG("Debug Message")
                 Utilities.close(self)
                 #exit(new)
         elif self.drowsername == "Firefox":
             try:
                 self.driver = webdriver.Firefox(executable_path= drivepath.Firefoxdriverpath)
                 logging.info("Broswer launch success")
                 driver = self.driver
                 driver.maximize_window()
             except:
                 logging.info("Unable to launch browser due to some error plZ Chcek driver path need to update")
                 logging.DEBUG("Debug Message")
         elif self.drowsername == "Ie":
             try:
                 self.driver = webdriver.Ie(executable_path=drivepath.Iedriverpath)
                 logging.info("Broswer launch success")
                 driver = self.driver
                 driver.maximize_window()
             except:
                 logging.info("Unable to launch browser due to some error plZ Chcek driver path need to update")
                 logging.DEBUG("Debug Message")
         elif self.drowsername == "Edgebrowser":
             try:
                 self.driver = webdriver.Edge(executable_path=drivepath.Edgebrowserdriverpath)
                 logging.info("Broswer launch success")
                 driver = self.driver
                 driver.maximize_window()
             except:
                 logging.info("Unable to launch browser due to some error plZ Chcek driver path need to update")
                 logging.DEBUG("Debug Message")
         elif self.drowsername == "Opera":
             try:
                 self.driver = webdriver.Opera(executable_path=drivepath.Operadriverpath)
                 logging.info("Broswer launch success")
                 driver = self.driver
                 driver.maximize_window()
             except:
                 logging.info("Unable to launch browser due to some error plZ Chcek driver path need to update")
                 logging.DEBUG("Debug Message")
         else:
             logging.info("No browser found please check the browser name in correct format")
     except:
         logging.info("Unable to Load driver for the browser")
Beispiel #5
0
def readTextFields(window):
    try:
        textlist = []
        textlist = window.textFields()
        logging.DEBUG("textfields in current window")
    except Exception as er:
        logging.DEBUG("Not able to get textfields in current window")
    return False
    return textlist
Beispiel #6
0
def get_user_input(name):
    """ Get the user input for psi and angle. Return as a list of two
    numbers. """
    # Later on in the 'exceptions' chapter, we will learn how to modify
    # this code to not crash the game if the user types in something that
    # isn't a valid number.
    logging.DEBUG("I'm now in get_user_input(name)")
    try:
        psi = float(input(name + " charge the gun with how many psi? "))
        angle = float(input(name + " move the gun at what angle? "))
    except (ValueError, UnboundLocalError, TypeError):
        logging.DEBUG("The user might input something wrong.")
    return psi, angle
Beispiel #7
0
def ApiContact(testURL, tryTimes=1):
	logging.info("ApiContact called with %s.", testURL)
	tokenList = getLibraryAuthInfo()
	uname = tokenList[0]
	passwd = tokenList[1]
	r = requests.get(testURL, auth=(uname, passwd))
	status = r.status_code
	ctype = r.headers.get('content-type')
	if (status == 200):
		logging.DEBUG("Success! %s content available")
	else:
		logging.warning("Get request %s returned %s", testURL, status)
	logging.DEBUG("ApiContact: status check %s.", status)
Beispiel #8
0
def delete_client(sock):
    """
    CR (misha):
        Classic example to ehy i hate global direct access to variables, what if some one iterates
        over OPEN_CLIENT_SOCKETS in this moment in other thread
    """
    OPEN_CLIENT_SOCKETS.remove(sock)
    sock.close()
    """
    CR (misha): Again CLIENTS here!
    """
    if sock not in CLIENTS.values():
        """
        CR (misha): Consider using logging instead of prints
        """
        logging.DEBUG("Unknown socket disconnected")
        return

    deleted_client_name = ""
    """
    CR (misha): 
        Could not understand what CLIENTS.keys are just from reading this code ( socket, names, objects... )
        dont use 'n' as a variable name 
    """
    for name in CLIENTS.keys():
        if CLIENTS[name] is sock:
            deleted_client_name = name
            del CLIENTS[name]

    """
    CR (misha): This is not the first time i read this snippet of code, it should be wrapped behind some logic
    """
    if deleted_client_name in ADMINS:
        name = ADMIN_SYMBOL + deleted_client_name
    MESSAGES_TO_SEND.append(["server", "Left the chat {} has!\n".format(deleted_client_name), False])

    """
    CR (misha): actually i like that you have this as an optional, good job ^^ 
    """
    if HARD_THROW:  # if HARD_THROW is on delete client from Admin and Mute lists
        """
        CR (misha): What is MASTER[0] name? socket? this code is unreadable 
        """
        if deleted_client_name in ADMINS and deleted_client_name != MASTER_ADMIN[0]:
            ADMINS.remove(deleted_client_name)

        if deleted_client_name in MUTED_CLIENTS:
            MUTED_CLIENTS.remove(deleted_client_name)

    logging.DEBUG("{} disconnected".format(deleted_client_name))
Beispiel #9
0
    def valid_chain(self, chain):
        prev_block = chain[0]
        current_index = 1
        while current_index < len(chain):
            block = chain[current_index]
            logging.DEBUG(f"{last_block}")
            logging.DEBUG(f"{block}")
            logging.DEBUG("\n--------\n")

            if block["previous_hash"] != self.hash(prev_block):
                return False

            prev_block = block
            current_index += 1
        return True
Beispiel #10
0
def sftpfile(host, getfiles, putfiles):
    try:
        logging.info("connnect to " + host['ip'] + ",user " +
                     host['username'] + ",sftp")
        t = paramiko.Transport((host['ip'], int(host['port'])))
        t.connect(username=host['username'], password=host['passwd'])
        sftp = paramiko.SFTPClient.from_transport(t)
        if getfiles != None:
            for file in getfiles:
                logging.info("get " + file)
                file = file.replace("\n", "")
                sftp.get(file, file)
        if putfiles != None:
            for file in putfiles:
                file = file.replace("\n", "")
                logging.info("put " + file)
                sftp.put(file, file)
        t.close()
    except:
        import traceback
        traceback.print_exc()
        try:
            t.close()
        except Exception as e:
            logging.DEBUG(e)
Beispiel #11
0
def getdata():
    if request.method == 'POST':
        try:
            data = request.get_data()
            session.permanent = True
            data1 = json.loads(data.decode('utf-8'))
            print("request.cookies.get", request.cookies)
            uuid_1 = data1.get('uuid')
            if uuid_1:
                if session.get("uuid") == uuid_1:
                    data = generate_data()
                    success = True
                    message = "successfully"
                else:
                    session["uuid"] = uuid_1
                    data = generate_data()
                    success = True
                    message = "successfully"
            else:
                print('else', uuid_1)
                # logging.DEBUG('at getdata function, uuid failed')
                success = False
                data = {}
                message = 'uuid 为空'
        except Exception as e:
            logging.DEBUG(
                'at getdata function, save file failed, exception {0}'.format(
                    e))
            success = False
            data = None
            message = e
        return jsonify({'success': success, 'data': data, 'message': message})
Beispiel #12
0
def shrinkpart(part, size):
    dsk = part.disk
    dev = dsk.device
    print('Resizing partition...')
    # Create a new geometry
    newgeo = parted.Geometry(start=part.geometry.start,
                             length=parted.sizeToSectors(
                                 shrink_to, 'B', dev.sectorSize),
                             device=dev)
    logging.DEBUG(newgeo.__str__())
    # Create a new partition with our new geometry
    newpart = parted.Partition(disk=dsk,
                               type=parted.PARTITION_NORMAL,
                               geometry=newgeo)
    # Create a constraint that aligns our new geometry with the optimal alignment of the disk
    constraint = parted.Constraint(maxGeom=newgeo).intersect(
        dev.optimalAlignedConstraint)
    dsk.deletePartition(part)
    dsk.addPartition(partition=newpart, constraint=constraint)
    try:
        dsk.commit()
    except:
        pass

    return (newgeo.end + 1) * dev.sectorSize
Beispiel #13
0
def getPathdata():
    if request.method == 'POST':
        try:
            data = request.get_data()
            data1 = json.loads(data.decode('utf-8'))
            uuid = data1.get('uuid')
            filename = os.path.join(app.config['UPLOAD_PATH'], uuid)
            data = generate_path_gesture_data(filename)
            x = list(data[:, 0])
            y = list(data[:, 1])
            z = list(data[:, 2])
            path_data = {'x': x, 'y': y, 'z': z}
            success = True
            message = "successfully"
            print("getpathdata", path_data)
        except Exception as e:
            logging.DEBUG(
                'at getPathdata function, get data failed, exception {0}'.
                format(e))
            success = False
            path_data = None
            message = e
        return jsonify({
            'success': success,
            'data': path_data,
            'message': message
        })
Beispiel #14
0
 def create(self, validated_data):
     if self.context['request'].user.id is None:
         validated_data['created_by_id'] = 1
     else:
         validated_data['created_by_id'] = self.context['request'].user.id
         logging.DEBUG(validated_data)
     return Post.objects.create(**validated_data)
Beispiel #15
0
def calculate_distance(psi, angle_in_degrees):
    """ Calculate the distance the mudball flies. """
    angle_in_radians = math.radians(angle_in_degrees)
    distance = .5 * psi**2 * math.sin(angle_in_radians) * math.cos(
        angle_in_radians)
    logging.DEBUG("I'm now in calculate_distance(psi, angle_in_degrees)")
    return distance
Beispiel #16
0
def find_user_matchIDs(username):
    'search the target user latest 3page martch id'
    matchid = []
    serverName = r'网通三'
    playerName = username

    matchId_by_name_url = r'http://lolbox.duowan.com/matchList.php?serverName=%s&playerName=%s' % (
        serverName, urllib.quote(playerName))
    re = spider.http_header(matchId_by_name_url)
    html = urllib2.urlopen(re).read()
    soup_html = spider.BeautifulSoup(html, "html.parser")
    page_nnnumber = int(spider.get_page_limit(soup_html))
    t = spider.find_match_id(soup_html)
    matchid.extend(t)  #page_nnnumber默认从0开始,记录数据,避免后续重复查询
    # print '第%s页有%s条数据,当前一共%s数据'%(1,len(t),len(matchid))

    if page_nnnumber <= 2:
        logging.DEBUG('%s 用户数据过少,不予统计' % (username))
        return []

    else:
        for n_page in range(1, 4):
            matchId_by_name_url = r'http://lolbox.duowan.com/matchList.php?serverName=%s&playerName=%s&page=%s' % (
                serverName, playerName, str(n_page + 1))
            re = spider.http_header(matchId_by_name_url)
            html = urllib2.urlopen(re).read()
            soup_html = spider.BeautifulSoup(html, "html.parser")
            temp = spider.find_match_id(soup_html)

            matchid.extend(temp)
            # print '第%s页有%s条数据,当前一共%s数据'%(n_page+1,len(temp),len(matchid))
            if len(matchid) > 15:
                break
    return matchid
Beispiel #17
0
 def print_settings(self):
     """
     Shows the settings of the main parameters necessary to process the algorithm.
     """
     logging.DEBUG(f'Initial settings:\n')
     for key, value in self.__dict__.items():
         logging.info(f'{key} = {value}')
Beispiel #18
0
    def HandleHave(self, msg_have):
        """Update the local have map"""
        
        if self._logger.isEnabledFor(logging.DEBUG):
            logging.DEBUG("FROM > {0} > HAVE: {1}".format(self._peer_num, msg_have))

        # TODO: THIS NEEDS TO BE ADJUSTED FOR VOD
        if self._swarm.live and self.live_discard_wnd is not None:
            # Check for new max
            if msg_have.end_chunk > self._max_have_value:
                self._max_have_value = msg_have.end_chunk

                lower_bound = self._max_have_value - self.live_discard_wnd

                # Discard according to live window if required
                if any(self.set_have):
                    self.set_have = set(filter(lambda x: x > lower_bound, self.set_have))
                if any(self.set_i_requested):
                    self.set_i_requested = set(filter(lambda x: x > lower_bound, self.set_i_requested))
        
        for i in range(msg_have.start_chunk, msg_have.end_chunk+1):
            self.set_have.add(i)

            # Special handling for live swarms
            if self._swarm.live or self._swarm.vod:
                if i in self._swarm.set_have:
                    # Do nothing if I have the advertised chunk
                    pass
                elif i > self._swarm._last_discarded_id:
                    # There is a chunk somebody have and I don't -> add to missing set
                    self._swarm.set_missing.add(i)
Beispiel #19
0
def question(quiz, school, _type, options):
    sql = "insert into questions(quiz,school,type,options) VALUES('{quiz}','{school}','{_type}','{options}','{answer}')".format(
        quiz=quiz, school=school, _type=_type, options=options)
    try:
        c.execute(sql)
        conn.commit()
    except Exceptions as e:
        logging.DEBUG(e)
Beispiel #20
0
def handle_client(client_socket):
    # 打印出客户端发送的内容
    request = client_socket.recv(1024)

    logging.DEBUG("[*] Received: %s" % request)

    # 返回一个数据包
    client_socket.send("ACK!")
Beispiel #21
0
def main():
    all_is_good = check_status()
    logging.DEBUG("Aircheck result: %s", all_is_good)

    with FileLock(f'{settings.OUTPUT_PATH}.lock') as lock:
        with open(settings.OUTPUT_PATH, 'w') as out_file:
            if not all_is_good:
                out_file.write('1')
Beispiel #22
0
def sign_in(user):
    msg = 1
    browser = webdriver.Chrome()
    browser.get('http://bcfl.sdufe.edu.cn/index/')
    logging.info("Successfully get chrome driver.")
    number = browser.find_element_by_id('number')
    print("Found <%s> element with that number!" % (number.tag_name))
    password = browser.find_element_by_id('card')
    print("Found <%s> element with that card!" % (password.tag_name))
    captcha = browser.find_element_by_id('verify')
    print("Found <%s> element with that verify!" % (captcha.tag_name))
    sign_bt = browser.find_element_by_id('sub_btn')
    print("Found <%s> element with that sub_btn!" % (sign_bt.tag_name))
    auth_img = browser.find_element_by_id('auth_code_img')
    print("Found <%s> element with that auth_code_img!" % (auth_img.tag_name))

    number.send_keys(user.uid)
    password.send_keys(user.pwd)
    action = ActionChains(browser)
    action.context_click(auth_img).perform()  #右键点击该元素

    #选中右键菜单中第3个选项
    pyautogui.press('down')
    pyautogui.press('down')
    pyautogui.press('down')
    pyautogui.press('enter')
    time.sleep(5)
    os.system('xclip -selection clipboard -t image/png -o > ./img.png')
    rsp = captcha_pred()
    captcha.send_keys(rsp.pred_rsp.value)
    sign_bt.click()

    try:
        wait = WebDriverWait(browser, 10)
        wait.until(EC.alert_is_present())
        alert = browser.switch_to.alert
        if alert.text == "请输入有效验证码":
            logging.info(
                "Captcha for user <{0}> is wrong, now try again.".format(
                    user.uid))
            alert.accept()
            browser.quit()
            if rsp.ret_code == 0:
                api = FateadmApi(app_id, app_key, pd_id, pd_key)
                api.Justice(rsp.request_id)
        elif alert.text == "工号或密码错误,请重新输入!":
            logging.DEBUG(
                "Password for user <{0}> is wrong, now try again.".format(
                    user.uid))
        return 0
    except TimeoutException:
        success_sub = 0
        while success_sub == 0:
            success_sub = sub_info(browser, user)

    browser.quit()
    return 1
Beispiel #23
0
def delete_artifact(url):
    config = g.get_central_config()
    username = config['nexus']['maven']['username']
    password = config['nexus']['maven']['password']

    try:
        res = requests.delete(url, auth=(username, password))
    except Exception as e:
        logging.DEBUG(e)
Beispiel #24
0
    def issue_cmd(self, cmds):
        """
        :param cmds: list of commands to pass to Xfoil
        """
        if isinstance(cmds, str):
            cmds = [cmds]

        for cmd in cmds:
            self.ps.stdin.write(cmd + '\n')
            logging.DEBUG(' - Issue_cmd: "%s"' % cmd)
Beispiel #25
0
 def get_client(client_id):
     try:
         client = ClientService.get_client_by_id(int(client_id))
         return jsonify(client.json()), 200
     except ValueError as e:
         logging.DEBUG("Client does not exist")
         return "Client does not exist", 400
     except ResourceNotFound as r:
         logging.debug("Resource Not Found")
         return r.message, 404
Beispiel #26
0
 def get_data(self):
     response = requests.post(url=self.url,
                              data=self.data,
                              headers=self.headers)
     print(response.text)
     if response.status_code == 200:
         print(response.text)
     if response.status_code != 200:
         print(response.status_code)
         logging.DEBUG()
Beispiel #27
0
def getMcafeedmgfilename(dmgpath, dmgfilename):
    try:
        for root, dirs, files in os.walk(dmgpath):
            for dmg in files:
                if dmg.endswith(dmgfilename):
                    dmginstallername = dmgfilename
    except Exception as er:
        logging.DEBUG("dmg")
    return False
    return dmginstallername
Beispiel #28
0
def verifynotification(notificationbutton):
    try:
        atomacclick(notificationbutton)
        ldtp.wait(3)
        content = notificationbutton.AXTitle
        ldtp.wait(1)
    except Exception as er:
        logging.DEBUG("Not able to click on notification object")
        return False
    return content
Beispiel #29
0
 def getAllergyEntriesFromResponse(self, response):
     entries = ''
     try:
         json_data = json.loads(response.text)
         entries = json_data['entry']
         #print("ENTRIES: ", entries)
         logging.DEBUG("Entry: ", entries)
     except:
         logging.error("Could not parse entries from JSON response")
     return entries
Beispiel #30
0
	def item_completed(self, results, item, info):
		print results
		# 判断 src 是缩略图还是 内容中的图片,并各自保存。
		image_paths = [x['path'] for ok, x in results if ok]
		
		if image_paths:
			item['thumb'] = image_paths[0]
		
		logging.DEBUG("finished get Thumb")
		return item