modified from suvi code by vhsu
327066
def save(self):
        
        pri_hdu = fits.PrimaryHDU(data=self.thmap)

        # Temporal Information
        date_fmt = '%Y-%m-%dT%H:%M:%S.%f'
        date_beg = self.start_time.strftime(date_fmt)
        date_end = self.end_time.strftime(date_fmt)
        date_now = datetime.utcnow().strftime(date_fmt)
        self.set_fits_header("TIMESYS", self.ref_hdr, pri_hdu)
        pri_hdu.header.append(("DATE-BEG", date_beg, "sun observation start time on sat"))
        pri_hdu.header.append(("DATE-END", date_end, "sun observation end time on sat"))
        pri_hdu.header.append(("DATE", date_now, "file generation time"))
        pri_hdu.header.append(("EXPERT", self.config.expert, "person who labeled image"))
        pri_hdu.header.append(("DATE-LAB", date_now, "date of labeling for the image"))

        # Instrument & Spacecraft State during Observation
        pri_hdu.header.append(("EXPTIME", 1., "[s] effective imaging exposure time"))
        self.set_fits_header("YAW_FLIP", self.ref_hdr, pri_hdu)
        self.set_fits_header("ECLIPSE", self.ref_hdr, pri_hdu)

        # Pointing & Projection
        self.set_fits_header("WCSNAME", self.ref_hdr, pri_hdu)
        self.set_fits_header("CTYPE1", self.ref_hdr, pri_hdu)
        self.set_fits_header("CTYPE2", self.ref_hdr, pri_hdu)
        self.set_fits_header("CUNIT1", self.ref_hdr, pri_hdu)
        self.set_fits_header("CUNIT2", self.ref_hdr, pri_hdu)
        self.set_fits_header("PC1_1", self.ref_hdr, pri_hdu)
        self.set_fits_header("PC1_2", self.ref_hdr, pri_hdu)
        self.set_fits_header("PC2_1", self.ref_hdr, pri_hdu)
        self.set_fits_header("PC2_2", self.ref_hdr, pri_hdu)
        self.set_fits_header("CDELT1", self.ref_hdr, pri_hdu)
        self.set_fits_header("CDELT2", self.ref_hdr, pri_hdu)
        self.set_fits_header("CRVAL1", self.ref_hdr, pri_hdu)
        self.set_fits_header("CRVAL2", self.ref_hdr, pri_hdu)
        self.set_fits_header("CRPIX1", self.ref_hdr, pri_hdu)
        self.set_fits_header("CRPIX2", self.ref_hdr, pri_hdu)
        self.set_fits_header("DIAM_SUN", self.ref_hdr, pri_hdu)
        self.set_fits_header("LONPOLE", self.ref_hdr, pri_hdu)
        self.set_fits_header("CROTA", self.ref_hdr, pri_hdu)
        self.set_fits_header("SOLAR_B0", self.ref_hdr, pri_hdu)

        # File Provenance
        pri_hdu.header.append(("TITLE", "Expert Labeled Thematic Map Image", "image title"))
        pri_hdu.header.append(("MAP_MTHD", "human", "thematic map classifier method"))
        try:
            # Add COMMENT cards
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 1,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 2, ("COMMENT", 'USING SUVI THEMATIC MAP FILES'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 3,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 4,
                                  ("COMMENT", 'Map labels are described in the FITS extension.'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 5, ("COMMENT", 'Example:'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 6, ("COMMENT", 'from astropy.io import fits as pyfits'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 7, ("COMMENT", 'img = pyfits.open(<filename>)'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 8, ("COMMENT", 'map_labels = img[1].data'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 9,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 10, ("COMMENT", 'TEMPORAL INFORMATION'))
            pri_hdu.header.insert(pri_hdu.header.index("TITLE") + 11,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("DATE") + 1,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("DATE") + 2,
                                  ("COMMENT", 'INSTRUMENT & SPACECRAFT STATE DURING OBSERVATION'))
            pri_hdu.header.insert(pri_hdu.header.index("DATE") + 3,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("ECLIPSE") + 1,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("ECLIPSE") + 2, ("COMMENT", 'POINTING & PROJECTION'))
            pri_hdu.header.insert(pri_hdu.header.index("ECLIPSE") + 3,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("SOLAR_B0") + 1,
                                  ("COMMENT", '------------------------------------------------------------------------'))
            pri_hdu.header.insert(pri_hdu.header.index("SOLAR_B0") + 2, ("COMMENT", 'FILE PROVENANCE'))
            pri_hdu.header.insert(pri_hdu.header.index("SOLAR_B0") + 3,
                                  ("COMMENT", '------------------------------------------------------------------------'))
        except:
            print("This thematic map may be degraded and missing many keywords.")

        # Thematic map feature list (Secondary HDU extension)
        map_val = []
        map_label = []
        for key, value in self.config.solar_class_index.items(): #sorted(SOLAR_CLASS_INDEX.items(), key=lambda p: (lambda k, v: (v, k))):
            map_label.append(key)
            map_val.append(value)
        c1 = fits.Column(name="Thematic Map Value", format="B", array=np.array(map_val))
        c2 = fits.Column(name="Feature Name", format="22A", array=np.array(map_label))
        bintbl_hdr = fits.Header([("XTENSION", "BINTABLE")])
        sec_hdu = fits.BinTableHDU.from_columns([c1, c2], header=bintbl_hdr)

        # Output thematic map as the primary HDU and the list of map features as an extension BinTable HDU
        hdu = fits.HDUList([pri_hdu, sec_hdu])
        hdu.writeto(self.filename, overwrite=True, checksum=True)
54959
def susvd(x, x_obs, rho, penalties):
    

    assert type(x) == Tensor, "Input array must be a Tensor"

    while True:

        # proximal operator for the Fro. norm
        x = squared_error(x, rho, x_obs)

        # sequential singular value thresholding
        for ix, penalty in enumerate(penalties):
            x = x.unfold(ix).svt(penalty / rho).fold()

        yield x
24148
def _paload32(ins):
    ''' 
    '''
    output = _paddr(ins.quad[2])

    output.append('call __ILOAD32')
    output.append('push de')
    output.append('push hl')

    REQUIRES.add('iload32.asm')

    return output
217176
def sighash_for_witness(index, script_pubkey_or_script_code, hash_type, amount, skip_separator_index)
      hash_prevouts = Bitcoin.double_sha256(inputs.map{|i|i.out_point.to_payload}.join)
      hash_sequence = Bitcoin.double_sha256(inputs.map{|i|[i.sequence].pack('V')}.join)
      outpoint = inputs[index].out_point.to_payload
      amount = [amount].pack('Q')
      nsequence = [inputs[index].sequence].pack('V')
      hash_outputs = Bitcoin.double_sha256(outputs.map{|o|o.to_payload}.join)

      script_code = script_pubkey_or_script_code.to_script_code(skip_separator_index)

      case (hash_type & 0x1f)
      when SIGHASH_TYPE[:single]
        hash_outputs = index >= outputs.size ? "\x00".ljust(32, "\x00") : Bitcoin.double_sha256(outputs[index].to_payload)
        hash_sequence = "\x00".ljust(32, "\x00")
      when SIGHASH_TYPE[:none]
        hash_sequence = hash_outputs = "\x00".ljust(32, "\x00")
      end

      if (hash_type & SIGHASH_TYPE[:anyonecanpay]) != 0
        hash_prevouts = hash_sequence ="\x00".ljust(32, "\x00")
      end
      hash_type |= (Bitcoin.chain_params.fork_id << 8) if Bitcoin.chain_params.fork_chain?
      buf = [ [version].pack('V'), hash_prevouts, hash_sequence, outpoint,
              script_code ,amount, nsequence, hash_outputs, [@lock_time, hash_type].pack('VV')].join
      Bitcoin.double_sha256(buf)
    end
832068
public static void horizontal(Kernel1D_S32 kernel, InterleavedU16 src, InterleavedI16 dst ) {
		InputSanityCheck.checkSameShapeB(src, dst);

		boolean processed = BOverrideConvolveImageNormalized.invokeNativeHorizontal(kernel,src,dst);
		
		if( !processed ) {
			if( kernel.width >= src.width ) {
				ConvolveNormalizedNaive_IL.horizontal(kernel, src, dst);
			} else {
				ConvolveImageNoBorder.horizontal(kernel, src, dst, kernel.computeSum());
				ConvolveNormalized_JustBorder_IL.horizontal(kernel, src, dst);
			}
		}
	}
1014775
private void reComputeHashCode()
    {
        ivCurHashCode = (ivAppName != null ? ivAppName.hashCode() : 0) // d437828
                        + (ivModJarName != null ? ivModJarName.hashCode() : 0)
                        + (ivPuName != null ? ivPuName.hashCode() : 0);
    }
1218098
def cublasDtpsv(handle, uplo, trans, diag, n, AP, x, incx):
    

    status = _libcublas.cublasDtpsv_v2(handle, 
                                       _CUBLAS_FILL_MODE[uplo], 
                                       _CUBLAS_OP[trans], 
                                       _CUBLAS_DIAG[diag], 
                                       n, int(AP), int(x), incx)
    cublasCheckStatus(status)
969432
def step4(self, encrypted_data):
        """"""
        chacha = chacha20.Chacha20Cipher(self._session_key, self._session_key)
        decrypted_tlv_bytes = chacha.decrypt(
            encrypted_data, nounce='PS-Msg06'.encode())
        if not decrypted_tlv_bytes:
            raise Exception('data decrypt failed')  # TODO: new exception
        decrypted_tlv = tlv8.read_tlv(decrypted_tlv_bytes)
        _LOGGER.debug('PS-Msg06: %s', decrypted_tlv)

        atv_identifier = decrypted_tlv[tlv8.TLV_IDENTIFIER]
        atv_signature = decrypted_tlv[tlv8.TLV_SIGNATURE]
        atv_pub_key = decrypted_tlv[tlv8.TLV_PUBLIC_KEY]
        log_binary(_LOGGER,
                   'Device',
                   Identifier=atv_identifier,
                   Signature=atv_signature,
                   Public=atv_pub_key)

        # TODO: verify signature here

        return Credentials(atv_pub_key, self._signing_key.to_seed(),
                           atv_identifier, self.pairing_id)
136393
function _hsv2rgb(data, addr, H,S,V) {
	if (V < 0.0001) {
		data[addr] = data[addr+1] = data[addr+2] = 0;
		return;
	}

	if (V>1) V = 1;

	if (S == 0) {
		data[addr] = data[addr+1] = data[addr+2] = v2b(V);
		return;
	}

	if (S>1) S = 1;

	var hue = H < 0 ? (H + 360) : (H >= 360 ? H - 360 : H),
	    st = (hue/60),
	    oct = st-(st|0), // [0...1]
	    y = hsv_angle_correction ? /* istanbul ignore next */ Math.sin((oct-.5)*1.0471975512)+.5 : oct,
	    s = S*V,
	    ns = V - s,
	    _ns = v2b(ns),
	    _v = v2b(V);

	switch (st|0) {
	case 0: data[addr] = _v;          data[addr+1] = v2b(ns+s*y); data[addr+2] = _ns;         return;
	case 1: data[addr] = v2b(V-s*y);  data[addr+1] = _v;          data[addr+2] = _ns;         return;
	case 2: data[addr] = _ns;         data[addr+1] = _v;          data[addr+2] = v2b(ns+s*y); return;
	case 3: data[addr] = _ns;         data[addr+1] = v2b(V-s*y);  data[addr+2] = _v;          return;
	case 4: data[addr] = v2b(ns+s*y); data[addr+1] = _ns;         data[addr+2] = _v;          return;
	}
	/*   5: */
	        data[addr] = _v;          data[addr+1] = _ns;         data[addr+2] = v2b(V-s*y);
}
1042600
def crc16jit(buf, offset, crc, length):
  """"""
  for index in range(offset, offset + length):
    data = buf[index]
    lookup = crc16_tab[((nb.u2(crc) >> 8) & nb.u2(0xFF)) ^ (data & nb.u2(0xFF))]
    crc = ((nb.u2(crc) << nb.u2(8)) & nb.u2(0xFFFF)) ^ lookup
    crc = nb.u2(crc) & nb.u2(0xFFFF)
  return crc
53888
def clean_vcf_output(orig_file, clean_fn, config, name="clean"):
    
    base, ext = utils.splitext_plus(orig_file)
    out_file = "{0}-{1}{2}".format(base, name, ext)
    if not utils.file_exists(out_file):
        with open(orig_file) as in_handle:
            with file_transaction(config, out_file) as tx_out_file:
                with open(tx_out_file, "w") as out_handle:
                    for line in in_handle:
                        update_line = clean_fn(line)
                        if update_line:
                            out_handle.write(update_line)
        move_vcf(orig_file, "{0}.orig".format(orig_file))
        move_vcf(out_file, orig_file)
        with open(out_file, "w") as out_handle:
            out_handle.write("Moved to {0}".format(orig_file))
1269355
private boolean checkNlVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(10) - '0';
    final int sum = (pvatId.charAt(2) - '0') * 9 + (pvatId.charAt(3) - '0') * 8
        + (pvatId.charAt(4) - '0') * 7 + (pvatId.charAt(5) - '0') * 6 + (pvatId.charAt(6) - '0') * 5
        + (pvatId.charAt(7) - '0') * 4 + (pvatId.charAt(8) - '0') * 3
        + (pvatId.charAt(9) - '0') * 2;
    final int calculatedCheckSum = sum % MODULO_11;
    return checkSum == calculatedCheckSum;
  }
305011
def _encode(segments, error, version, mask, eci, boost_error, sa_info=None):
    
    is_micro = version < 1
    sa_mode = sa_info is not None
    buff = Buffer()
    ver = version
    ver_range = version
    if not is_micro:
        ver = None
        ver_range = version_range(version)
    if boost_error:
        error = boost_error_level(version, error, segments, eci, is_sa=sa_mode)
    if sa_mode:
        # ISO/IEC 18004:2015(E) -- 8 Structured Append (page 59)
        for i in sa_info[:3]:
            buff.append_bits(i, 4)
        buff.append_bits(sa_info.parity, 8)
    # ISO/IEC 18004:2015(E) -- 7.4 Data encoding (page 22)
    for segment in segments:
        write_segment(buff, segment, ver, ver_range, eci)
    capacity = consts.SYMBOL_CAPACITY[version][error]
    # ISO/IEC 18004:2015(E) -- 7.4.9 Terminator (page 32)
    write_terminator(buff, capacity, ver, len(buff))
    #  ISO/IEC 18004:2015(E) -- 7.4.10 Bit stream to codeword conversion (page 34)
    write_padding_bits(buff, version, len(buff))
    # ISO/IEC 18004:2015(E) -- 7.4.10 Bit stream to codeword conversion (page 34)
    write_pad_codewords(buff, version, capacity, len(buff))
    # ISO/IEC 18004:2015(E) -- 7.6 Constructing the final message codeword sequence (page 45)
    buff = make_final_message(version, error, buff.toints())
    # Matrix with timing pattern and reserved format / version regions
    matrix = make_matrix(version)
    # ISO/IEC 18004:2015 -- 6.3.3 Finder pattern (page 16)
    add_finder_patterns(matrix, is_micro)
    # ISO/IEC 18004:2015 -- 6.3.6 Alignment patterns (page 17)
    add_alignment_patterns(matrix, version)
    # ISO/IEC 18004:2015 -- 7.7 Codeword placement in matrix (page 46)
    add_codewords(matrix, buff, version)
    # ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
    # ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
    mask = find_and_apply_best_mask(matrix, version, is_micro, mask)
    # ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
    add_format_info(matrix, version, error, mask)
    # ISO/IEC 18004:2015(E) -- 7.10 Version information (page 58)
    add_version_info(matrix, version)
    return Code(matrix, version, error, mask, segments)
557274
def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset):
        '''
        
        '''
        # VDR's VXRhead
        self._update_offset_value(f, vdr_offset+28, 8, VXRoffset)
        # VDR's VXRtail
        self._update_offset_value(f, vdr_offset+36, 8, VXRoffset)
907072
function vchar() {
        return wrap('vchar', compareToken(function vcharFunc(tok) {
            var code = tok.charCodeAt(0);
            var accept = (0x21 <= code && code <= 0x7E);
            if (opts.rfc6532) {
                accept = accept || isUTF8NonAscii(tok);
            }
            return accept;
        }));
    }
255047
def modify_prefix(arg, opts, shell_opts):
    

    modify_confirmed = shell_opts.force

    spec = { 'prefix': arg }
    v = get_vrf(opts.get('vrf_rt'), abort=True)
    spec['vrf_rt'] = v.rt

    res = Prefix.list(spec)
    if len(res) == 0:
        print("Prefix %s not found in %s." % (arg, vrf_format(v)), file=sys.stderr)
        return

    p = res[0]

    if 'prefix' in opts:
        p.prefix = opts['prefix']
    if 'description' in opts:
        p.description = opts['description']
    if 'comment' in opts:
        p.comment = opts['comment']
    if 'tags' in opts:
        tags = list(csv.reader([opts.get('tags', '')], escapechar='\\'))[0]
        p.tags = {}
        for tag_name in tags:
            tag = Tag()
            tag.name = tag_name
            p.tags[tag_name] = tag
    if 'node' in opts:
        p.node = opts['node']
    if 'type' in opts:
        p.type = opts['type']
    if 'status' in opts:
        p.status = opts['status']
    if 'country' in opts:
        p.country = opts['country']
    if 'order_id' in opts:
        p.order_id = opts['order_id']
    if 'customer_id' in opts:
        p.customer_id = opts['customer_id']
    if 'vlan' in opts:
        p.vlan = opts['vlan']
    if 'alarm_priority' in opts:
        p.alarm_priority = opts['alarm_priority']
    if 'monitor' in opts:
        p.monitor = _str_to_bool(opts['monitor'])
    if 'expires' in opts:
        p.expires = opts['expires']

    for avp in opts.get('extra-attribute', []):
        try:
            key, value = avp.split('=', 1)
        except ValueError:
            print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr)
            return
        p.avps[key] = value


    # Promt user if prefix has authoritative source != nipap
    if not modify_confirmed and p.authoritative_source.lower() != 'nipap':

        res = input("Prefix %s in %s is managed by system '%s'. Are you sure you want to modify it? [y/n]: " %
            (p.prefix, vrf_format(p.vrf), p.authoritative_source))

        # If the user declines, short-circuit...
        if res.lower() not in [ 'y', 'yes' ]:
            print("Operation aborted.")
            return

    try:
        p.save()
    except NipapError as exc:
        print("Could not save prefix changes: %s" % str(exc), file=sys.stderr)
        sys.exit(1)

    print("Prefix %s in %s saved." % (p.display_prefix, vrf_format(p.vrf)))
710131
def customPRF512(key, amac, smac, anonce, snonce):
    """"""
    A = b"Pairwise key expansion"
    B = b"".join(sorted([amac, smac]) + sorted([anonce, snonce]))

    blen = 64
    i = 0
    R = b''
    while i <= ((blen * 8 + 159) / 160):
        hmacsha1 = hmac.new(key, A + chb(0x00) + B + chb(i), hashlib.sha1)
        i += 1
        R = R + hmacsha1.digest()
    return R[:blen]