Creates rcube_sieve_script object from text script
170213
private function _parse($txt)
    {
        // parse
        $script = new rcube_sieve_script($txt, $this->exts);

        // fix/convert to Roundcube format
        if (!empty($script->content)) {
            // replace all elsif with if+stop, we support only ifs
            foreach ($script->content as $idx => $rule) {
                if (empty($rule['type']) || !preg_match('/^(if|elsif|else)$/', $rule['type'])) {
                    continue;
                }

                $script->content[$idx]['type'] = 'if';

                // 'stop' not found?
                foreach ($rule['actions'] as $action) {
                    if (preg_match('/^(stop|vacation)$/', $action['type'])) {
                        continue 2;
                    }
                }
                if (!empty($script->content[$idx+1]) && $script->content[$idx+1]['type'] != 'if') {
                    $script->content[$idx]['actions'][] = array('type' => 'stop');
                }
            }
        }

        return $script;
    }
74650
def create_script(fname):
    """"""
    text = os.linesep.join(["# -*- coding: utf-8 -*-", "", ""])
    try:
        encoding.write(to_text_string(text), fname, 'utf-8')
    except EnvironmentError as error:
        QMessageBox.critical(_("Save Error"),
                             _("<b>Unable to save file '%s'</b>"
                               "<br><br>Error message:<br>%s"
                               ) % (osp.basename(fname), str(error)))
1050301
def create_lua_script(plugins):
    
    lua_template = pkg_resources.resource_string('detectem', 'script.lua')
    template = Template(lua_template.decode('utf-8'))

    javascript_data = to_javascript_data(plugins)

    return template.substitute(js_data=json.dumps(javascript_data))
761986
def from_file_obj(cls, fp):
        
        log.debug("Parsing email from file object")
        try:
            fp.seek(0)
        except IOError:
            # When stdout is a TTY it's a character device
            # and it's not seekable, you cannot seek in a TTY.
            pass
        finally:
            s = fp.read()

        return cls.from_string(s)
15151
def make_spo(sub, prd, obj):
    '''
    

    '''
    # To establish string as a curie and expand,
    # we use a global curie_map(.yaml)
    # sub are allways uri  (unless a bnode)
    # prd are allways uri (unless prd is 'a')
    # should fail loudly if curie does not exist
    if prd == 'a':
        prd = 'rdf:type'

    try:
        (subcuri, subid) = re.split(r':', sub)
    except Exception:
        LOG.error("not a Subject Curie  '%s'", sub)
        raise ValueError

    try:
        (prdcuri, prdid) = re.split(r':', prd)
    except Exception:
        LOG.error("not a Predicate Curie  '%s'", prd)
        raise ValueError
    objt = ''

    # object is a curie or bnode or literal [string|number]

    objcuri = None
    match = re.match(CURIERE, obj)
    if match is not None:
        try:
            (objcuri, objid) = re.split(r':', obj)
        except ValueError:
            match = None
    if match is not None and objcuri in CURIEMAP:
        objt = CURIEMAP[objcuri] + objid.strip()
        # allow unexpanded bnodes in object
        if objcuri != '_' or CURIEMAP[objcuri] != '_:b':
            objt = '<' + objt + '>'
    elif obj.isnumeric():
        objt = '"' + obj + '"'
    else:
        # Literals may not contain the characters ", LF, CR '\'
        # except in their escaped forms. internal quotes as well.
        obj = obj.strip('"').replace('\\', '\\\\').replace('"', '\'')
        obj = obj.replace('\n', '\\n').replace('\r', '\\r')
        objt = '"' + obj + '"'

    # allow unexpanded bnodes in subject
    if subcuri is not None and subcuri in CURIEMAP and \
            prdcuri is not None and prdcuri in CURIEMAP:
        subjt = CURIEMAP[subcuri] + subid.strip()
        if subcuri != '_' or CURIEMAP[subcuri] != '_:b':
            subjt = '<' + subjt + '>'

        return subjt + ' <' + CURIEMAP[prdcuri] + prdid.strip() + '> ' + objt + ' .'
    else:
        LOG.error(
            'Cant work with: <%s> %s , <%s> %s, %s',
            subcuri, subid, prdcuri, prdid, objt)
        return None
580789
def btc_script_deserialize(script):
    

    if isinstance(script, str) and re.match('^[0-9a-fA-F]*$', script):
       script = binascii.unhexlify(script)

    # output buffer
    out = []
    pos = 0

    while pos < len(script):
        # next script op...
        code = encoding.from_byte_to_int(script[pos])

        if code == 0:
            # empty (OP_0)
            out.append(None)
            pos += 1

        elif code <= 75:
            # literal numeric constant, followed by a slice of data.
            # push the slice of data.
            out.append(script[pos+1:pos+1+code])
            pos += 1 + code

        elif code <= 78:
            # OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4, followed by length and data
            # push the data itself
            szsz = pow(2, code - 76)
            sz = encoding.decode(script[pos+szsz: pos:-1], 256)
            out.append(script[pos + 1 + szsz : pos + 1 + szsz + sz])
            pos += 1 + szsz + sz

        elif code <= 96:
            # OP_1NEGATE, OP_RESERVED, OP_1 thru OP_16
            # pass -1 for OP_1NEGATE
            # pass 0 for OP_RESERVED (shouldn't be used anyway)
            # pass 1 thru 16 for OP_1 thru OP_16
            out.append(code - 80)
            pos += 1

        else:
            # raw opcode
            out.append(code)
            pos += 1

    # make sure each string is hex'ed
    out = encoding.json_changebase(out, lambda x: encoding.safe_hexlify(x))
    return out
731923
def from_text(text):
    

    if text.isdigit():
        v = int(text)
        if v >= 0 and v <= 4095:
            return v
    v = _by_text.get(text.upper())
    if v is None:
        raise UnknownRcode
    return v
1299644
def _script_to_har_entry(cls, script, url):
        '''  '''
        entry = {
            'request': {'url': url},
            'response': {'url': url, 'content': {'text': script}}
        }

        cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY)

        return entry
140952
def _create_sentence_objects(self):
        """"""
        sentence_objects = []
        sentences = sent_tokenize(self.raw, tokenizer=self.tokenizer)
        char_index = 0  # Keeps track of character index within the blob
        for sent in sentences:
            # Compute the start and end indices of the sentence
            # within the blob. This only works if the sentence splitter
            # does not perform any character replacements or changes to
            # white space.
            # Working: NLTKPunktTokenizer
            # Not working: PatternTokenizer
            try:
                start_index = self.raw.index(sent, char_index)
                char_index += len(sent)
                end_index = start_index + len(sent)
            except ValueError:
                start_index = None
                end_index = None
            # Sentences share the same models as their parent blob
            s = Sentence(
                sent,
                start_index=start_index,
                end_index=end_index,
                tokenizer=self.tokenizer,
                np_extractor=self.np_extractor,
                pos_tagger=self.pos_tagger,
                analyzer=self.analyzer,
                parser=self.parser,
                classifier=self.classifier)
            sentence_objects.append(s)
        return sentence_objects
514810
def create_table_from_object(self, obj):
        '''
        
        '''
        get_type = lambda item: str(type(item)).split("'")[1]
        if not os.path.exists(os.path.join(self.db_path, obj._TABLE)):
            with gzip.open(os.path.join(self.db_path, obj._TABLE), 'wb') as table_file:
                csv.writer(table_file).writerow(['{col}:{type}'.format(col=elm[0], type=get_type(elm[1]))
                                                 for elm in tuple(obj.__dict__.items())])
            self._tables[obj._TABLE] = self._load_table(obj._TABLE)
873047
def from_text(name, ttl, rdclass, rdtype, *text_rdatas):
    

    return from_text_list(name, ttl, rdclass, rdtype, text_rdatas)
27701
def extract_script(embedded_hex):
    
    hex_lines = embedded_hex.split('\n')
    script_addr_high = hex((_SCRIPT_ADDR >> 16) & 0xffff)[2:].upper().zfill(4)
    script_addr_low = hex(_SCRIPT_ADDR & 0xffff)[2:].upper().zfill(4)
    start_script = None
    within_range = False
    # Look for the script start address
    for loc, val in enumerate(hex_lines):
        if val[0:9] == ':02000004':
            # Reached an extended address record, check if within script range
            within_range = val[9:13].upper() == script_addr_high
        elif within_range and val[0:3] == ':10' and \
                val[3:7].upper() == script_addr_low:
            start_script = loc
            break
    if start_script:
        # Find the end of the script
        end_script = None
        for loc, val in enumerate(hex_lines[start_script:]):
            if val[9:41] == 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF':
                end_script = loc + start_script
                break
        # Pass the extracted hex through unhexlify
        return unhexlify('\n'.join(
            hex_lines[start_script - 1:end_script if end_script else -6]))
    return ''
1058696
protected function init_script()
    {
        if (!$this->sieve->script) {
            return;
        }

        $this->script = $this->sieve->script->as_array();

        $headers    = array();
        $exceptions = array('date', 'currentdate', 'size', 'body');

        // find common headers used in script, will be added to the list
        // of available (predefined) headers (#1489271)
        foreach ($this->script as $rule) {
            foreach ((array) $rule['tests'] as $test) {
                if ($test['test'] == 'header') {
                    foreach ((array) $test['arg1'] as $header) {
                        $lc_header = strtolower($header);

                        // skip special names to not confuse UI
                        if (in_array($lc_header, $exceptions)) {
                            continue;
                        }

                        if (!isset($this->headers[$lc_header]) && !isset($headers[$lc_header])) {
                            $headers[$lc_header] = $header;
                        }
                    }
                }
            }
        }

        ksort($headers);

        $this->headers += $headers;
    }
422554
def transform_source(text):
    '''
    '''

    loop_keyword = 'repeat'

    nb = text.count(loop_keyword)
    if nb == 0:
        return text

    var_names = get_unique_variable_names(text, nb)

    toks = tokenize.generate_tokens(StringIO(text).readline)
    result = []
    replacing_keyword = False
    for toktype, tokvalue, _, _, _ in toks:
        if toktype == tokenize.NAME and tokvalue == loop_keyword:
            result.extend([
                (tokenize.NAME, 'for'),
                (tokenize.NAME, var_names.pop()),
                (tokenize.NAME, 'in'),
                (tokenize.NAME, 'range'),
                (tokenize.OP, '(')
            ])
            replacing_keyword = True
        elif replacing_keyword and tokvalue == ':':
            result.extend([
                (tokenize.OP, ')'),
                (tokenize.OP, ':')
            ])
            replacing_keyword = False
        else:
            result.append((toktype, tokvalue))
    return tokenize.untokenize(result)
102068
def make_multisig_segwit_address_from_witness_script(script):
    
    script_hash = hashing.bin_sha256(script.decode('hex')).encode('hex')
    scriptsig_script = '0020' + script_hash
    addr = btc_make_p2sh_address(scriptsig_script)
    return addr
534448
def to_script_code(skip_separator_index = 0)
      payload = to_payload
      if p2wpkh?
        payload = Script.to_p2pkh(chunks[1].pushed_data.bth).to_payload
      elsif skip_separator_index > 0
        payload = subscript_codeseparator(skip_separator_index)
      end
      Bitcoin.pack_var_string(payload)
    end
970013
def generate_slug(obj, text, tail_number=0):
    from panya.models import ModelBase
    
    # use django slugify filter to slugify
    slug = slugify(text)
    
    existing_slugs = [item.slug for item in ModelBase.objects.filter(slug__regex=r'^%s(-\d+)?' % slug).exclude(id=obj.id)]
    
    tail_number = 0
    new_slug = slug
    while new_slug in existing_slugs:
        new_slug = slugify("%s-%s" % (slug, tail_number))
        tail_number += 1
    
    return new_slug