def signal_program(self, node):
        result = self.program(node.add_child(Node('<program>',
                                                  node.depth + 1)))

        if self.is_eof() and not result and len(self.errors) == 0:
            self.errors.append(
                Error(
                    "Unexpected End Of File after '%s'" %
                    self.get_current_lexeme().value,
                    self.get_current_lexeme().line_num,
                    self.get_current_lexeme().col_num))
Example #2
0
    def parse(line, road_items):
        mo = Uni_node.regexp.search(line)
        if not mo:
            return False

        pointer = mo.group(1)
        if pointer in road_items:
            raise Error("uni-node: %s already exists in road_items" % pointer)
        data = '{' + mo.group(2) + '}'
        road_items[pointer] = json.loads(data, object_hook=json_hook)
        return True
Example #3
0
def obtain_feedback(request):
    feedback = {}
    if 'image_id' in request.args:
        feedback['id'] = request.args['image_id']
    else:
        raise Error(2873, 'No `image_id` provided')

    if 'face_index' in request.args:
        feedback['face_index'] = request.args['face_index']

    if 'feedback' in request.args:
        if request.args['feedback'] in emotions:
            feedback['feedback'] = request.args['feedback']
        else:
            raise Error(2873, 'Invalid `feedback` parameter')

    # insert = collection.update({"pic_id": feedback['id'], "faces.index": int(feedback['face_index'])},
    #                            {"$push": {"face.index.$.feedback": feedback['feedback']}})
    # print "INSERT STATUS: ", insert
    return feedback
Example #4
0
    def collapse(self, node_id) -> Error:
        current_node, error = self._node_by_id(node_id)

        if error:
            return error

        for node in PostOrderIter(current_node):
            if node is not current_node:
                node.parent = None

        return Error(None)
Example #5
0
 def __get_from_proxy(self, url):
     ip = ''
     if re.match('^(http:|https:)', url) == None:
         url = 'http://' + url
     try:
         doc = urllib2.urlopen(url, timeout = self.__timeout).read()
     except:
         raise Error("TimeoutError", '', url)
     else:
         pattern = '(?!(((0\.)|(10\.)|(127)|(192\.168)|(172\.(1[6-9])|(2[0-9]\.)|(3[01]\.)))|(2[4,5][0-5])))'
         pattern += '((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){3}'
         pattern += '((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([0-9]))'
         pattern = re.compile(pattern)
         result = pattern.search(doc)
         if result == None:
             raise Error('ReturnValueError', '', url)
         else:
             ip = result.group(0)
     finally:
         return ip
Example #6
0
 def raise_error(self, context):
     error = Error(self, context, 1)
     if error.code in (1, 1400, 2290, 2291, 2292):
         raise IntegrityError(error)
     elif error.code in (22, 378, 602, 603, 604, 609, 1012, 1013, 1033,
                         1034, 1041, 1043, 1089, 1090, 1092, 3113, 3114,
                         3122, 3135, 12153, 12203, 12500, 12571, 27146,
                         28511):
         raise OperationalError(error)
     else:
         raise DatabaseError(error)
Example #7
0
    def batch_ocr(self, src_p, restart):
        if(len(src_p) == 0):
            err = Error("No Image Data For OCR!")
            raise err

        src = sorted(src_p, key=lambda name: int(name[name.find("g_")+2:-4]))

        # initialise images to be sent to Mathpix
        data = {}
        data['urls'] = {}
        data['callback'] = {}
        data['callback']['post'] = "https://requestb.in/1hee59v1"
        # append sliced images to data json
        if (restart):
            self.x = self.x - 23

        for img in src:
            self.x = self.x + 1
            data['urls']['img_'+str(self.x)] = "data:image/jpeg;base64," + base64.b64encode(open(img, "rb").read()).decode("utf-8")

        # post data json to mathpix api
        r = requests.post(
            "https://api.mathpix.com/v3/batch", data=json.dumps(data),
            headers={
                'app_id': 'lsg',
                'app_key': '851562083f16c98fe08e7c3b918066ba',
                'content-type': 'application/json'
            },
            timeout=30
        )

        reply = json.loads(r.text)

        while(True):
            #print("Checking Image Keys...")
            results = requests.get("https://api.mathpix.com/v3/batch/"+reply['batch_id'], headers={
                'app_id': 'lsg',
                'app_key': '851562083f16c98fe08e7c3b918066ba',
            })
            if(self.check_img_keys(json.loads(results.content))):
                break
           

        # Check for the last image key
        while(True):
            #print("Checking Last Image Key...")
            results = requests.get("https://api.mathpix.com/v3/batch/"+reply['batch_id'], headers={
                'app_id': 'lsg',
                'app_key': '851562083f16c98fe08e7c3b918066ba',
            })
            if(self.check_end_img_keys(json.loads(results.content))):
                break       

        return json.loads(results.content)
Example #8
0
 def connect(self, ip):
     self.port = 5005
     client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sslSocket = ssl.wrap_socket(client,
                                      ssl_version=ssl.PROTOCOL_TLSv1,
                                      ciphers=self.ciphers)
     self.sslSocket.settimeout(3)
     try:
         self.sslSocket.connect((ip, self.port))
         return True
     except socket.error as e:
         errorcode = e[0]
         if errorcode == errno.ECONNREFUSED:
             self.error = Error("Could not connect to " + self.contact)
         else:
             messageError = (
                 "Error code " + str(e[0]) +
                 "\nYour cipher preferences might be incompatible.")
             self.error = Error(messageError)
         return False
Example #9
0
def generate():
    token = request.form.get('token')
    coin = request.form.get('coin')
    description = request.form.get('description')

    if token not in produce_permission.keys():
        raise Error("invalid token")

    coupon = generate_coupon(coin, description, produce_permission[token])

    return jsonify({'status': 'OK', 'coupon': str(coupon.id)})
Example #10
0
    def change_indent(self, indent):
        """
        Generates indent and dedent tokens to change indentation level.
        """
        if not isinstance(indent, int):
            self.error = Error("ValueError: Positive integer expected")
            return
        if indent < 0:
            self.error = Error("ValueError: Positive integer expected")
            return

        while self.position.indent < indent:
            self.position.indent += 1
            self.tokens.append(
                Token(tt._INDENT, "    ", self.position, self.position))

        while self.position.indent > indent:
            self.position.indent -= 1
            self.tokens.append(
                Token(tt._DEDENT, "    ", self.position, self.position))
Example #11
0
def isBool(symbol):
    """
    Checks whether a symbol is a boolean or not.

    PARAMS:
        symbol: the string to test
    RETURNS:
        string | None
    """
    if not isinstance(symbol, str):
        return tt._INVALID, Error(
            "TypeError: 'symbol' expected to be a string")
    if len(symbol) < 1:
        return tt._INVALID, Error(
            "ValueError: 'symbol' is not allowed to be empty string")
    if symbol == "True":
        return tt._TRUE, None
    elif symbol == "False":
        return tt._FALSE, None
    return tt._IDENTIFIER, None
Example #12
0
def getFile(file):
    # open the file and read the lines
    try:
        user_code = open(file)
        lines = user_code.read()
        return lines
    except IOError:
        Error(
            'main',
            f'File: {file} could not be opened please ensure the path is correct or use and absolute path'
        )
Example #13
0
def add_transaction():

    values = request.get_json()

    if not values:
        error = Error()
        error.code = 400
        error.message = 'No Data found for adding transaction. Please provide 1. Amount 2. Recipient !'
        return jsonify(error.__dict__), 400

    else:
        # First check and verify mandatory fields are suppiled in request.
        required_fields = ['recipient', 'amount']

        if not all(field in values for field in required_fields):
            error = Error()
            error.code = 400
            error.message = 'Required fields --> recipient & amount are missing !'

            return jsonify(error.__dict__), 400

        recipient = values['recipient']
        amount = float(values['amount'])
        signature = wallet.sign_transaction(wallet.public_key, recipient,
                                            amount)

        success = blockchain.add_transaction(recipient, wallet.public_key,
                                             amount, signature)

        if isinstance(success, Error):
            return jsonify(error.__dict__), 500

        response = {
            'message': 'Transaction added succesfully !',
            'sender': wallet.public_key,
            'recipient': recipient,
            'amount': amount,
            'signature': signature
        }

        return jsonify(response), 200
Example #14
0
def dashboard_type(type):

    if type not in scenarios_def:
        raise Error('type required')

    scenarios = scenarios_def[type]

    req_fields = ['event_id', 'user_id', 'attr'] \
            + list(map(lambda str: 'scenario__' + str + '__used', scenarios)) \
            + list(map(lambda str: 'scenario__' + str + '__attr', scenarios)) \

    return jsonify(Attendee.objects(type=type).only(*req_fields))
Example #15
0
 def set_config(self):
     """Write any modifications back to the camera.
     Make any modifications with Widget.set_value(), then write back with
     this.
     This method can raise camera.Error.
     """
     logging.debug('writing camera config ...')
     self.camera.connect()
     retval = gp.gp_camera_set_config(self.camera.camera, self.root_widget,
                                      self.camera.context)
     if retval != camera.GP_OK:
         raise Error('Unable to set config')
Example #16
0
    def _validate_save_path(path):
        """
        Ensures download path can be accessed locally.

        :param path: Download path
        :return: Translated path
        """
        import xbmc
        path = xbmc.translatePath(path)
        if "://" in path:
            if sys.platform.startswith('win') and path.lower().startswith(
                    "smb://"):
                path = path.replace("smb:", "").replace("/", "\\")
            else:
                raise Error(
                    "Downloading to an unmounted network share is not supported",
                    Error.INVALID_DOWNLOAD_PATH)
        if not os.path.isdir(ensure_fs_encoding(path)):
            raise Error("Download path doesn't exist (%s)" % path,
                        Error.INVALID_DOWNLOAD_PATH)
        return path
Example #17
0
 def _start(self):
     if not self._is_local():
         return True
     if self.save_path and not os.path.isdir(self.save_path):
         raise Error("Invalid download path (%s)" % self.save_path, Error.INVALID_DOWNLOAD_PATH)
     if sys.platform.startswith("win"):
         return self._start_windows()
     else:
         try:
             self._start_linux()
         except Error:
             self._start_android()
Example #18
0
 def post(self, request, app_name, app_path):
     _purge_domains(json.loads(read_file(app_path.domains)))
     stop_patsaks(get_id(request.dev_name, app_name))
     git_runner = _make_git_runner(request, app_name)
     git_runner.run('add', '-A')
     args = ['commit', '-qm', request.data['message']]
     if request.data.get('amend'):
         args += ('--amend', '--reset-author')
     output = git_runner.run(*args)
     if output:
         raise Error(output)
     return HttpResponse()
Example #19
0
    def crawl(self, folder, full_path):
        try:
            items = os.listdir(full_path)
        except Exception as e:
            items = []
            self.add_to_error_list(Error(e))

        for item in items:
            print("Found: " + item, end="                                          \r", flush=True)
            self.counter += 1
            if self.is_item_folder(item, full_path):
                #folder.add_item_to_folder(Folder(item, []).to_dict())
                folder.add_item_to_folder(self.crawl(Folder(item, []), full_path + self.file_sep + item).to_dict())
            else:
                try:
                    date_modified = os.path.getmtime(full_path + self.file_sep + item)
                except Exception as e:
                    self.add_to_error_list(Error(e))
                    date_modified = 1;
                folder.add_item_to_folder(File(item, date_modified).to_dict())
        return folder
Example #20
0
def solve(A, x):
    res = rref(A, Y=x)
    i = 1
    # No non-zero elements in the (n - i + 1)th row of RREF
    while all(x == 0 for x in res[-i]):
        if any(x != 0
               for x in res.soln[-i]):  # If corresponding b_i is non-zero
            raise Error("No Solution Exists")
        i += 1
    return result(
        span(res, res.soln), r"\text{Solution of System }" + str(A) +
        r' \quad ' + str(x) + r' is \, %s')
Example #21
0
    def parse(line, road_items):
        mo = Traffic_signal.regexp.search(line)
        if not mo:
            return False

        pointer = mo.group(1)
        if pointer in road_items:
            raise Error("traffic-signal: %s already exists in road_items" %
                        pointer)
        data = mo.group(2)
        road_items[pointer] = json.loads(data, object_hook=json_hook)
        return True
Example #22
0
    def check_torrent_error(self, status=None):
        """
        It is recommended to call this method periodically to check if any libtorrent errors occurred.
        Usually libtorrent sets error if it can't download or parse torrent file by specified URI.
        Note that pyrrent2http remains started after such error, so you need to shutdown it manually.

        :param status: Pass return of status() method if you don't want status() called twice
        """
        if not status:
            status = self.status()
        if status.error:
            raise Error("Torrent error: %s" % status.error, Error.TORRENT_ERROR, reason=status.error)
Example #23
0
def dashboard_role(role):

    if role not in scenarios_def:
        raise Error('role required')

    scenarios = scenarios_def[role]

    req_fields = ['event_id', 'user_id', 'attr'] + \
        list(map(lambda str: 'scenario__' + str + '__used', scenarios)) + \
        list(map(lambda str: 'scenario__' + str + '__attr', scenarios)) \

    return jsonify(Attendee.objects(role=role).only(*req_fields))
Example #24
0
    def get_api(self):
        error = 'Don`t type word "WORLD", type valid country'

        headers = {
            'x-rapidapi-host': "covid-19-tracking.p.rapidapi.com",
            'x-rapidapi-key':
            "c5a3cb0bf5msh8ddf0bdd20db605p12b483jsn5661d04d9293"
        }

        if self.__method.upper(
        ) == 'GET' and self.__country.lower() != 'world':
            try:
                req = requests.request(self.__method.upper(),
                                       self.__url,
                                       headers=headers)
                if req.status_code == 200:
                    return req.json()
            except:
                Error('Connection error')
        else:
            Error(error)
Example #25
0
def consume():
    group_id = request.form.get('group_id')
    coupon_id = request.form.get('coupon')

    if group_id is None or coupon_id is None:
        raise Error("group_id and coupon required")

    try:
        coupon = Coupon.objects.with_id(coupon_id)
    except ValidationError:
        raise Error("invalid coupon id")

    if coupon is None:
        raise Error("invalid coupon id")

    if coupon.own_team is None:
        try:
            team = Team.objects(group_id=group_id).get()
        except DoesNotExist:
            raise Error("invalid team id")

        Team.objects(group_id=group_id).update_one(inc__coin=coupon.coin)
        team.reload()
        coupon.own_team = team
        coupon.save()
        bot.sendMessage(
            team.group_id,
            "{} {} {currency_name}\n{} 目前總計擁有 {} {currency_name}".format(
                coupon.description,
                coupon.coin,
                team.name,
                team.coin,
                currency_name=config.CURRENCY_NAME))

        #         if len(set(map(lambda _: _.producer, Coupon.objects(own_team=team)))) == len(produce_permission.keys()):
        #             bot.sendMessage(team.group_id, "「書靈 Lamp 想要幫助學徒尋找真相,因此靠著自己淵博的知識,發動了一個『真實之陣』\n真實之陣,信任正確之人,訴說你的信號,將會返回試金之結論」")

        return jsonify({'status': 'OK'})
    else:
        raise Error("Already used", status_code=409)
Example #26
0
def getReportPath(path, _tips, onlyXlsx = True, canSkip = False):
    _count = 0
    _pathList = []

    _isXls = False

    _files = listdir(path)
    # print file list
    for _file in _files:
        # 去除文件夹,非.xlsx文件以及临时文件
        if (not osPath.isdir(path + '/' + _file)) and "~$" not in _file:
            if ".xlsx" in _file or (not onlyXlsx and ".xls" in _file):
                _count += 1
                _pathList.append(path + '/' + _file)
                print(str(_count) + "、" + _file)

        
        # only at the onlyxlsx mode, will send the warning
        if onlyXlsx and ".xls" in _file and ".xlsx" not in _file :
            _isXls = True

    # do not find file
    if _count == 0:
        ErrorList.addError(Error("./", "do not find files"))
        print("do not find files")
        return None

    # warning find .xls file
    if _isXls:
        ErrorList.addError(Warning("./", "We have found .xls file in report list"))

    # input file number
    _index = 0
    _tipStr = "input number to choose {} file{}:".format(_tips, "(zero for skipping)" if canSkip else "")
    
    while _index <= 0 or _index > _count:
        _input = input(_tipStr)
        if _input == "" or not _input.isdigit():
            continue
        
        _index = int(_input)
        if canSkip and _index == 0 :
            return None

        if _index < 0 or _index > _count:
            print("wrong number\n")
    
    # output \n
    print("\n")
    
    Logger.addLog("GET {} PATH!! Path = {}".format(_tips, _pathList[_index - 1]))
    return _pathList[_index - 1]
Example #27
0
 def verify_pap_password(self, plain_password):
     buf = self.attrs['User-Password'][0]
     # RFC says maximum length == 128 characters, but ignoring rule
     if len(buf) % 16 != 0:
         raise Error("Invalid User-Password length.")
     pw = six.b('')
     last = self.authenticator
     while buf:
         _hash = md5(self.secret + last).digest()
         if six.PY3:
             for i in range(16):
                 pw += bytes((_hash[i] ^ buf[i], ))
         else:
             for i in range(16):
                 pw += chr(ord(_hash[i]) ^ ord(buf[i]))
         (last, buf) = (buf[:16], buf[16:])
     while pw.endswith(six.b('\x00')):
         pw = pw[:-1]
     try:
         return plain_password == pw.decode('utf-8')
     except UnicodeDecodeError:
         raise Error("Invalid secret or User-Password.")
Example #28
0
    def evaluate(self, var):
        Exp = self
        print Exp.exp, " Vars: ", var
        for k in var:
            var[k] = Matrix(var[k])

        try:
            ans = eval(Exp.exp, self.functions, var)
        except:
            raise Error(
                "This expression can't be evaluated. Please check the specs.")

        return ans if isinstance(ans, Matrix) else [[ans]]
Example #29
0
 def _get_code_lexem(self, state):
     if (state == "IDN" or state == "WS" or state == "DEL") and self.curr_lexem in KEYWORDS:
         return KEYWORDS[self.curr_lexem]
     if (state== "IDN") and self.curr_lexem in IDENTIFICATORS:
         return IDENTIFICATORS[self.curr_lexem]
     if (state == "IDN" or state == "NUM"):
         if not self.curr_lexem in CONSTANTS:
             return self._add_constant()
         else:
             return CONSTANTS[self.curr_lexem]
     if state == "DEL" and self.curr_lexem in DELIMITERS:
         return DELIMITERS[self.curr_lexem]
     raise Error('Lexem is not find', self.curr_index, '')
Example #30
0
 def _start_windows(self):
     import _winreg
     try:
         key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                               "Software\\AceStream")
         path = _winreg.QueryValueEx(key, "EnginePath")[0]
     except _winreg.error:
         # trying previous version
         try:
             import _winreg
             key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                   "Software\\TorrentStream")
             path = _winreg.QueryValueEx(key, "EnginePath")[0]
         except _winreg.error:
             raise Error("Can't find AceStream executable",
                         Error.CANT_FIND_EXECUTABLE)
     try:
         self.log.info("Starting AceStream engine for Windows: %s" % path)
         os.startfile(path)
     except:
         raise Error("Can't start AceStream engine",
                     Error.CANT_START_ENGINE)