def verify_node(node):
    node_string = dump_json(node)
    variables = None
    secrets = None
    if upload_variables:
        variables_in_conf = regex_findall(r'\$ENV\((\S*?)\)',
                                          node_string)  # Find env vars
        variables: dict = load_json(
            open(git_cloned_dir + sync_root + 'node/' + var_file_path).read())
        for var in variables_in_conf:  # Verify they exist in git repo
            if var not in variables:
                logging.error(
                    f'Missing env var {var} in variables file {var_file_path}')
    if upload_secrets:
        secrets_in_conf = regex_findall(r'\$SECRET\((\S*?)\)',
                                        node_string)  # Find secrets
        vault = Vaulter(vault_url, vault_git_token,
                        vault_mounting_point)  # Create keyvault object
        secrets: dict = vault.get_secrets(
            secrets_in_conf)  # Get the secrets from keyvault
        if vault.verify() is False:  # Verify all secrets exist.
            logging.error(
                f'These secrets do not exist in the vault {vault.get_missing_secrets()}'
            )

    return variables, secrets
Esempio n. 2
0
 def validate_serie(self):
     pricelist_item_obj = self.env['product.pricelist.item']
     if self.product_id:
         if self.product_id.tracking == 'serial':
             item_id = pricelist_item_obj.search(
                 [('product_id', '=', self.product_id.id)],
                 order="create_date desc",
                 limit=1)
             if item_id and self.since:
                 prefix = item_id.prefix_request
                 if self.since[0:6] != prefix[0:6]:
                     raise ValidationError(
                         ("Favor de verificar el prefijo de las solicitudes"
                          ))
                 elif len(self.since) > 12 or len(self.since) < 12:
                     raise ValidationError((
                         "El número de serie contiene {} digitos y debería tener 12 digitos, favor de verificarlo"
                         .format(len(self.since))))
                 ### VALIDAR TODOS LOS NÚMEROS DE SERIE
                 caught_initial_number = regex_findall("\d+", self.since)
                 initial_number = caught_initial_number[-1]
                 padding = len(initial_number)
                 # We split the serial number to get the prefix and suffix.
                 splitted = regex_split(initial_number, self.since)
                 # initial_number could appear several times in the SN, e.g. BAV023B00001S00001
                 prefix = initial_number.join(splitted[:-1])
                 suffix = splitted[-1]
                 initial_number = int(initial_number)
                 for i in range(0, int(self.product_qty)):
                     self.validate_exist_serie(
                         self.product_id,
                         '%s%s%s' % (prefix, str(initial_number +
                                                 i).zfill(padding), suffix))
Esempio n. 3
0
def part_1(advent_of_code):
    with open('input.txt', 'r') as input_file:
        valid = 0
        for line in input_file:
            s = regex_search('(\d+)-(\d+) (\w): (\w+)', line)
            if int(s.group(1)) <= len(regex_findall(
                    s.group(3), s.group(4))) <= int(s.group(2)):
                print(s.group(1), s.group(2), s.group(3), s.group(4))
                valid += 1
        print(valid)
        advent_of_code.answer(1, valid)
    def find_input_event_types_for_pattern(pattern):
        """
		Finds all event types that are used in the pattern. They are detected by their CamelCase notation.
		:param pattern: the pattern to find the event types in.
		:return: yields event types that are found, must be caught in a list.
		"""

        matches = regex_findall(r'\W+?(?P<EventType>([A-Z][a-z]+?)+?)\W',
                                pattern)
        for match in matches:
            yield match[0]
Esempio n. 5
0
    def _generate_serial_numbers(self, next_serial_count=False):
        """ This method will generate `lot_name` from a string (field
        `next_serial`) and create a move line for each generated `lot_name`.
        """
        self.ensure_one()

        if not next_serial_count:
            next_serial_count = self.next_serial_count

        # We look if the serial number contains at least one digit.
        caught_initial_number = regex_findall("\d+", self.next_serial)
        if not caught_initial_number:
            raise ValidationError(
                _('The serial number must contain at least one digit.'))
        # We base the serie on the last number find in the base serial number.
        initial_number = caught_initial_number[-1]
        padding = len(initial_number)
        # We split the serial number to get the prefix and suffix.
        splitted = regex_split(initial_number, self.next_serial)
        # initial_number could appear several times in the SN, e.g. BAV023B00001S00001
        prefix = initial_number.join(splitted[:-1])
        suffix = splitted[-1]
        initial_number = int(initial_number)
        serial_range = next_serial_count
        if self.product_id and self.product_id.tracking == 'lot':
            serial_range = int(
                int(self.product_uom_qty) / self.next_serial_qty)
            self.next_serial_count = serial_range
        lot_names = []
        # for i in range(0, next_serial_count):
        for i in range(0, serial_range):
            lot_names.append(
                '%s%s%s' %
                (prefix, str(initial_number + i).zfill(padding), suffix))
        move_lines_commands = self._generate_serial_move_line_commands(
            lot_names)
        if self.product_id and self.product_id.tracking == 'lot':
            for line in move_lines_commands:
                line_vals = line[2]
                if 'qty_done' in line_vals:
                    line_vals.update({'qty_done': self.next_serial_qty})
        self.write({'move_line_ids': move_lines_commands})
        return True
def getWords(book, stemmer):
    """Return words from the book

    replace contractions
    check spelling
    stem
    """
    words = []
    for page in book["pages"]:
        text = contractions_fix(page["text"])
        text = text.replace("'", "")
        words += [
            stemmer.stem(word).lower()
            for word in regex_findall(r"[a-z]+", text, flags=IGNORECASE)
            # spell.known(words=[word]) and
            if word.lower() not in stop_words
        ]

    return set(words)
Esempio n. 7
0
    def parse_output(self, data, mode="hash"):
        """ This function parses the output produced by ssdeep
        command. This is dirty parsing, but works as intended
        (at least for now).

        @params data - str - The output of ssdeep command.
        @params mode - str - Where did you get the output from?
                           Accepts "hash" or "ratio".

        :returns str/int. ssdeep hash or ratio from the output.
        """
        result = None
        if mode == "hash":
            l = [line for line in data.splitlines() if line][-1]
            result = l.split(",")[0]        
            return result
        elif mode == "ratio":
            l = [line for line in data.splitlines() if line][0]
            # Using regex to find the pattern (<ratio-int>) in the output
            result = int(regex_findall("\(\d{1,3}", l)[0].split("(")[1])
        return result
Esempio n. 8
0
    def generate_lot_names(self, first_lot, count):
        """Generate `lot_names` from a string."""
        # We look if the first lot contains at least one digit.
        caught_initial_number = regex_findall(r"\d+", first_lot)
        if not caught_initial_number:
            return self.generate_lot_names(first_lot + "0", count)
        # We base the series on the last number found in the base lot.
        initial_number = caught_initial_number[-1]
        padding = len(initial_number)
        # We split the lot name to get the prefix and suffix.
        splitted = regex_split(initial_number, first_lot)
        # initial_number could appear several times, e.g. BAV023B00001S00001
        prefix = initial_number.join(splitted[:-1])
        suffix = splitted[-1]
        initial_number = int(initial_number)

        lot_names = []
        for i in range(0, count):
            lot_names.append(
                '%s%s%s' %
                (prefix, str(initial_number + i).zfill(padding), suffix))
        return lot_names
Esempio n. 9
0
 def onchange_serie(self):
   pricelist_item_obj = self.env['product.pricelist.item']
   lot_obj = self.env['stock.production.lot']
   # print("-------------------------------------onchange series_start y series_end---------------------------------------------")
   for record in self:
     record.product_uom_qty = 0
     if record.series_start and record.series_end:
       if '-' in record.series_start and '-' in record.series_end:
         if record.series_end.split('-')[1].isnumeric() and record.series_start.split('-')[1].isnumeric():
           if int(record.series_end.split('-')[1]) >= int(record.series_start.split('-')[1]):
             record.product_uom_qty = int(record.series_end.split('-')[1]) - int(record.series_start.split('-')[1]) + 1
       elif record.series_start.isnumeric() and record.series_end.isnumeric():
         if int(record.series_end) >= int(record.series_start.isnumeric()):
           record.product_uom_qty = int(record.series_end) - int(record.series_start) + 1
     ### Calculando el producto al cual hace referencia la serie
     if record.series_start:
       product_prefix = record.series_start[0:6]
       pricelist_id = pricelist_item_obj.search([
           ('prefix_request','=',product_prefix),('company_id','=',self.company_id.id)],
           order="create_date desc",limit=1)
       if not pricelist_id:
         raise ValidationError((
           'No se pudo validar a que prefijo hace referencia "{}" favor de verificarlo con sistemas'.format(product_prefix)))
       record.product_id = pricelist_id.product_id.id or False
       ### VALIDAR TODOS LOS NÚMEROS DE SERIE
       caught_initial_number = regex_findall("\d+", record.series_start)
       initial_number = caught_initial_number[-1]
       padding = len(initial_number)
       # We split the serial number to get the prefix and suffix.
       splitted = regex_split(initial_number, record.series_start)
       # initial_number could appear several times in the SN, e.g. BAV023B00001S00001
       prefix = initial_number.join(splitted[:-1])
       suffix = splitted[-1]
       initial_number = int(initial_number)
       for i in range(0, int(record.product_uom_qty)):
         self.validate_location_serie(record.picking_id.location_id,'%s%s%s' % (
           prefix,
           str(initial_number + i).zfill(padding),
           suffix))
Esempio n. 10
0
 def find_variables_and_secrets(self):
     str_conf = dump_json(self.conf)
     self.config_vars = regex_findall(r'\$ENV\((\S*?)\)', str_conf)
     self.config_secrets = regex_findall(r'\$SECRET\((\S*?)\)', str_conf)
Esempio n. 11
0
    def create_serial_num(self):
        """
            Purpose: to create the serial numbers we want including the first serial number
            Method   Method logic is created based off stock move method (_generate_serial_numbers)
        """
        caught_initial_number = regex_findall("\d+", self.first_serial)
        initial_number = caught_initial_number[-1]
        padding = len(initial_number)
        splitted = regex_split(
            initial_number, self.first_serial
        )  # We split the serial number to get the prefix and suffix.
        prefix = initial_number.join(
            splitted[:-1]
        )  #initial_number could appear several times in the SN, e.g. BAV023B00001S00001
        suffix = splitted[-1]
        initial_number = int(initial_number)
        lot_names = []
        for i in range(0, self.serial_count):
            lot_names.append(
                '%s%s%s' %
                (prefix, str(initial_number + i).zfill(padding), suffix))

        # existing serial numbers in the range in stock.production.lot
        existing_lots = self.env['stock.production.lot'].search([
            ('name', 'in', lot_names), ('product_id', '=', self.product_id.id),
            ('company_id', '=', self.company_id.id)
        ])

        # all created serial numbers in stock.production.lot associated with the order_id
        created_lot_names = self.env['flsp.serialnumline'].search([
            ('order_id', '=', self.id)
        ]).mapped('serial_num')

        if len(existing_lots) > 0 or (len(created_lot_names) > len(lot_names)):
            self._write_existing_serialnum_lines(existing_lots)

            absent_lot_names = []
            for line in lot_names:
                if not line in existing_lots.mapped('name'):
                    absent_lot_names.append(line)

            extra_lot_names = []
            for line in created_lot_names:
                if not line in lot_names:
                    extra_lot_names.append(line)

            # open wizard to let user choose what to do next
            return {
                'name':
                'FLSP Serial Number Wizard',
                'view_mode':
                'form',
                'view_id':
                self.env.ref(
                    'flspserialnum.flsp_serial_num_wizard_form_view').id,
                'res_model':
                'flsp.serial.num.wizard',
                'type':
                'ir.actions.act_window',
                'target':
                'new',
                'context': {
                    'default_order_id': self.id,
                    'default_existing_lot_names': existing_lots.mapped('name'),
                    'default_absent_lot_names': absent_lot_names,
                    'default_extra_lot_names': extra_lot_names,
                }
            }
        else:
            lots = self.create_absent_serial_num(lot_names)
            self._write_existing_serialnum_lines(lots)

        return True
Esempio n. 12
0
  def create(self, vals):
    picking_obj = self.env['stock.picking']
    move_line_obj = self.env['stock.move.line']
    lot_obj = self.env['stock.production.lot']
    pricelist_item_obj = self.env['product.pricelist.item']
    product_obj = self.env['product.product']
    picking_id = picking_obj.browse(vals.get('picking_id'))
    if picking_id.type_transfer == 'as-ov':
      if vals.get('product_id'):
        product_id = product_obj.browse(vals.get('product_id'))
        if product_id.tracking == 'serial':
          item_id = pricelist_item_obj.search([('product_id','=',product_id.id),('company_id','=',vals.get('company_id'))],
            order="create_date desc",limit=1)
          if item_id:
            vals['papeleria'] = item_id.stationery
    res = super(StockMove, self).create(vals)
    if vals.get('picking_id'):
      if picking_id.type_transfer in ('ov-as','as-ov','cont-ov'):
        lot_id = lot_obj.search([('name','=',res.series),('company_id','=',vals.get('company_id'))],limit=1)
        data = {
          'picking_id' : picking_id.id,
          'move_id': res.id,
          'product_id': res.product_id.id,
          'product_uom_id' : res.product_id.uom_id.id,
          'qty_done' : 1,
          'lot_id' : lot_id.id or False,
          'location_id' : picking_id.location_id.id,
          'location_dest_id' : picking_id.location_dest_id.id,
          'state' : 'assigned',
          'reference' : res.reference,
        }
        move_line_obj.create(data)
        lot_id.employee_id = picking_id.employee_id.id or False

        # as-ov Validar enganche > 0
        if picking_id.type_transfer == 'as-ov':
          origen = ""
          if vals.get('origen_solicitud'):
            origen = vals.get('origen_solicitud')
          else:
            origen = self.origen_solicitud

          if not origen in ('cancelada','extravio','sobrantes'):
            inversion_inicial = 0
            if vals.get('inversion_inicial'):
              inversion_inicial = vals.get('inversion_inicial')
            else:
              inversion_inicial = self.inversion_inicial
            
            if inversion_inicial <= 0:
              raise ValidationError("La inversión inicial de una solicitud está en cero")

            if self.amount_received < self.papeleria:
              raise ValidationError("El importe recibido de una solicitud es menor a la papeleria")

        ### SI EL MOVIMIENTO ES OFICINA DE VENTAS - ASISTENTE
        if picking_id.type_transfer == 'ov-as':
          location_id = picking_id.location_id
        ### SI NO, VIENE DEL ASISTENTE A LA OFICINA DE VENTAS
        else:
          location_id = picking_id.location_dest_id
        ### SI HAY UBICACIÓN
        if location_id:
          ### BUSCA EL ALMACÉN AL QUE PERTENECE LA TRANSFERENCIA
          warehouse_id = picking_id.location_id.get_warehouse()
          ### SI SE ENCONTRÓ EL ALMACÉN
          if warehouse_id:
            ### PONE LA SOLICITUD EN EL ALMACÉN DE LA TRANSFERENCIA
            lot_id.warehouse_id = warehouse_id.id
        res.state = 'assigned'
      if picking_id.type_transfer in ('ac-ov','ov-ac'):
        ### VALIDAR TODOS LOS NÚMEROS DE SERIE
        caught_initial_number = regex_findall("\d+", res.series_start)
        initial_number = caught_initial_number[-1]
        padding = len(initial_number)
        # We split the serial number to get the prefix and suffix.
        splitted = regex_split(initial_number, res.series_start)
        # initial_number could appear several times in the SN, e.g. BAV023B00001S00001
        prefix = initial_number.join(splitted[:-1])
        suffix = splitted[-1]
        initial_number = int(initial_number)
        for i in range(0, int(res.product_uom_qty)):
          serie = '{}{}{}'.format(prefix,str(initial_number + i).zfill(padding),suffix)
          lot_id = lot_obj.search([('name','=',serie),('company_id','=',vals.get('company_id'))],limit=1) or False
          data = {
            'picking_id' : picking_id.id,
            'move_id': res.id,
            'product_id': res.product_id.id,
            'product_uom_id' : res.product_id.uom_id.id,
            'qty_done' : 1,
            'lot_id' : lot_id.id,
            'location_id' : picking_id.location_id.id,
            'location_dest_id' : picking_id.location_dest_id.id,
            'state' : 'assigned',
            'reference' : res.reference,
          }
          move_line_obj.create(data)
        res.state = 'assigned'
      if picking_id.type_transfer in ('servicios','reparaciones'):
        lot_id = lot_obj.search([('product_id','=', res.product_id.id), ('name','=',res.service_item_number), ('company_id','=',vals.get('company_id'))],limit=1)
        data = {
          'picking_id' : picking_id.id,
          'move_id': res.id,
          'product_id': res.product_id.id,
          'product_uom_id' : res.product_id.uom_id.id,
          'qty_done' : 1,
          'lot_id' : lot_id.id or False,
          'location_id' : picking_id.location_id.id,
          'location_dest_id' : picking_id.location_dest_id.id,
          'state' : 'assigned',
          'reference' : res.reference,
        }
        #raise ValidationError("{}".format(data) )
        move_line_obj.create(data)
        res.state = 'assigned'
      ##### Salida a consumo
      if picking_id.type_transfer == 'consumo':
        data = {
          'picking_id' : picking_id.id,
          'move_id': res.id,
          'product_id': res.product_id.id,
          'product_uom_id' : res.product_id.uom_id.id,
          'qty_done' : res.product_uom_qty,
          'location_id' : picking_id.location_id.id,
          'location_dest_id' : picking_id.location_dest_id.id,
          'state' : 'assigned',
          'reference' : res.reference,
        }
        move_line_obj.create(data)
        res.state = 'assigned'
    return res