Return a new memo with a new metatabfile argument
541356
def update_mt_arg(self, metatabfile):
        """"""
        o = MetapackCliMemo(self.args)
        o.set_mt_arg(metatabfile)
        return o
233675
def add_metadata_to_archive(self, metadata, meta_path):
        '''
        
        '''
        archive_path = self.get_full_archive_path(meta_path.lstrip('/'))
        write_data_to_file(metadata, archive_path)
384022
function generateMetadataNoteDocument (options) {
  if (!options) {
    throw new Error('Missing required input: options')
  }
  if (!options.title) {
    throw new Error('Missing required input: options.title')
  }
  if (!options.offTitle) {
    throw new Error('Missing required input: options.offTitle')
  }
  if (!options.personalIdNumber) {
    throw new Error('Missing required input: options.personalIdNumber')
  }
  if (!options.schoolName) {
    throw new Error('Missing required input: options.schoolName')
  }
  if (!options.schoolOrgNumber) {
    throw new Error('Missing required input: options.schoolOrgNumber')
  }
  if (!options.file) {
    throw new Error('Missing required input: options.file')
  }
  if (!options.fileTitle) {
    throw new Error('Missing required input: options.fileTitle')
  }
  if (!options.caseNumber) {
    throw new Error('Missing required input: options.caseNumber')
  }

  var schoolGroup = getSchoolStudentAccessGroup(options)
  var meta = {
    'clientService': 'DocumentService',
    'clientMethod': 'CreateDocument',
    'args': {
      'parameter': {
        'AccessCode': '13', // Codetable: Accesscode
        'AccessGroup': schoolGroup, // Codetable: Tilgangsgruppe navn
        'Category': 'Internt notat / e-post MED oppfølging (N)', // Codetable: Document category
        'Contacts': [
          {
            'DocumentContactParameter': [
              {
                'Role': 'Avsender',
                'ReferenceNumber': options.schoolOrgNumber
              },
              {
                'ReferenceNumber': options.schoolOrgNumber, // Personnummer / orgnr
                'Role': 'Mottaker' // 5: Avsender 6: Mottaker Codetable: Activity - Contact Role
              }
            ]
          }
        ],
        'Files': [
          {
            'CreateFileParameter': {
              'Base64Data': options.file, // Must be base64 encoded
              'Category': 'Brev', // Codetable: File category
              'Format': 'PDF', // Codetable: File format
              'Status': 'F', // Codetable: FileStatus
              'Title': options.fileTitle,
              'VersionFormat': 'A' // Codetable: File status
            }
          }
        ],
        'Paragraph': 'Offl §13 jfr Fvl §13.1', // Codetable: Paragraph
        'ResponsibleEnterpriseNumber': options.schoolOrgNumber, // Recnr ansvarlig virksomhet
        'ResponsiblePersonRecno': config.minelev.main_responsiblePersonRecno,
        'Status': 'J', // Codetable: Document status
        'Title': options.offTitle,
        'UnofficialTitle': options.title,
        'Archive': 'Saksdokument', // Codetable: Document archive
        'CaseNumber': options.caseNumber,
        'SendersReference': ''
      }
    }
  }
  return meta
}
249920
def write_file(self, fileobject, skip_unknown=False):
        """"""
        self.set_metadata_version()

        for field in _version2fieldlist(self['Metadata-Version']):
            values = self.get(field)
            if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
                continue
            if field in _ELEMENTSFIELD:
                self._write_field(fileobject, field, ','.join(values))
                continue
            if field not in _LISTFIELDS:
                if field == 'Description':
                    if self.metadata_version in ('1.0', '1.1'):
                        values = values.replace('\n', '\n        ')
                    else:
                        values = values.replace('\n', '\n       |')
                values = [values]

            if field in _LISTTUPLEFIELDS:
                values = [','.join(value) for value in values]

            for value in values:
                self._write_field(fileobject, field, value)
72182
def insert_file(self, f, namespace, timestamp):
        
        doc = f.get_metadata()
        doc["content"] = f.read()
        self.doc_dict[f._id] = Entry(doc=doc, ns=namespace, ts=timestamp)
195462
def add_text_memo(self, memo_text):
        
        memo_text = memo.TextMemo(memo_text)
        return self.add_memo(memo_text)
870731
def add_resource(mt_file, ref, cache):
    """"""

    if isinstance(mt_file, MetapackDoc):
        doc = mt_file
    else:
        doc = MetapackDoc(mt_file)

    if not 'Resources' in doc:
        doc.new_section('Resources')

    doc['Resources'].args = [e for e in set(doc['Resources'].args + ['Name', 'StartLine', 'HeaderLines', 'Encoding']) if
                             e]

    seen_names = set()

    u = parse_app_url(ref)

    # The web and file URLs don't list the same.

    if u.proto == 'file':
        entries = u.list()
    else:
        entries = [ssu for su in u.list() for ssu in su.list()]

    errors = []

    for e in entries:
        if not add_single_resource(doc, e, cache=cache, seen_names=seen_names):
            errors.append(e)

    if errors:
        prt()
        warn("Found, but failed to add these urls:")
        for e in errors:
            print('    ', e)

    write_doc(doc, mt_file)
1220659
def update_metatab(self, doc, resources):
        """"""

        if not 'Documentation' in doc:

            doc.new_section("Documentation")

        ds = doc['Documentation']

        if not 'Name' in ds.args:
            ds.add_arg('Name', prepend=True)

        # This is the main output from the HTML exporter, not a resource.
        ds.new_term('Root.Documentation', 'docs/notebook.html', name="notebook.html", title='Jupyter Notebook (HTML)')

        for name, data in resources.get('outputs', {}).items():

            if name == 'documentation.html':
                ds.new_term('Root.Documentation', 'docs/' + name, name=name, title='Primary Documentation (HTML)')

            elif name == 'html_basic_body.html':
                pass
            elif name.endswith('.html'):
                ds.new_term('Root.Documentation', 'docs/' + name, name=name, title='Documentation (HTML)')
            elif name.endswith('.md'):
                ds.new_term('Root.Documentation', 'docs/' + name, name=name, title='Documentation (Markdown)')
            elif name.endswith('.pdf'):
                ds.new_term('Root.Documentation', 'docs/' + name, name=name, title='Documentation (PDF)')
            elif name.endswith('.png'):
                ds.new_term('Root.Image', 'docs/' + name, name=name, title='Image for HTML Documentation')
            else:
                pass
791185
def append(self, newContent, keep=True):
        
        content = self.__content + newContent
        if keep:
            self.__content = content

        if self.__needsRewrite:
            """
            Replace the content of the file.
            A temporary file is used to avoid loss of data through an interrupt.
            """
            tmpFilename = self.filename + ".tmp"

            util.write_file(content, tmpFilename)

            os.rename(tmpFilename, self.filename)
        else:
            with open(self.filename, "a") as file:
                file.write(newContent)

        self.__needsRewrite = not keep
471844
def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File':
        
        if not secure:
            raise NotImplementedError("We only support secure files at this point")

        # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

        newFileNum, newFileRealPath = tempfile.mkstemp(
            suffix=suffix, prefix=prefix, dir=self._path)
        os.close(newFileNum)

        relativePath = os.path.relpath(newFileRealPath, self.path)

        file = File(self, pathName=relativePath, exists=True)
        self._files[file.pathName] = file
        return file
265983
def atomic_write(path, mode):
  """"""
  tmp_path = "%s%s_%s" % (path, constants.INCOMPLETE_SUFFIX, uuid.uuid4().hex)
  with tf.io.gfile.GFile(tmp_path, mode) as file_:
    yield file_
  tf.io.gfile.rename(tmp_path, path, overwrite=True)
586016
def UpdateParameters(Overwrite=False):
	'''
	
	
	'''
	

	print('This process may take a while, please be patient')
	time.sleep(1.0)
	
	
	#Download Tsyganenko data
	_DownloadTS05Data(Overwrite)
	
	#Download Kp Index data
	kp.UpdateLocalData()
	
	#list the files
	tabdir = Globals.DataPath+'tab/'
	if not os.path.isdir(tabdir):
		os.system('mkdir -pv '+tabdir)
	files = os.listdir(tabdir)
	nf = np.size(files)
	Years = 1995 + np.arange(nf)
	
	#read in Tsyganenko tab files
	tabs = []
	for i in range(0,nf):
		print('\rReading Year {:04d}'.format(Years[i]),end='')
		tabs.append(_ReadTab(Years[i]))
	print()
	
	#combine to one recarray
	print('Combining Yearly Data...') 
	n = 0
	for i in range(0,nf):
		n += tabs[i].size
	data = np.recarray(n,dtype=tabs[0].dtype)
	
	p = 0
	for i in range(0,nf):
		data[p:p+tabs[i].size] = tabs[i]
		p += tabs[i].size

	#get Kp indices
	udate = np.unique(data.Date)
	nu = np.size(udate)
	for i in range(0,nu):
		print('\rFinding Kp Index {:6.2f}%'.format(100.0*(i+1)/nu),end='')
		use = np.where(data.Date == udate[i])[0]
		k = kp.GetKp(udate[i])
		if k.size > 0:
			kind = np.int32(data.ut[use]/3.0)
			data.Kp[use] = k.Kp[kind]
		else:
			data.Kp[use] = 1
	print()
	
	#get G1 and G2
	for i in range(0,n):
		print('\rCalculating G param {0} of {1}'.format(i+1,n),end='')
		i0 = np.max([0,i-11])
		i1 = i + 1
		
		tmp = data[i0:i1]
		use = np.where(np.isfinite(tmp.By) & np.isfinite(tmp.Bz) & (tmp.IMFFlag > -1) & (tmp.ISWFlag > -1))[0]
		if use.size > 0:
			CA = np.arctan2(-tmp.By,tmp.Bz)
			Bp = np.sqrt(tmp.By**2 + tmp.Bz**2)
			Bs = np.abs(tmp.Bz)
			pos = np.where(tmp.Bz > 0)[0]
			Bs[pos] = 0.0
			h = ((Bp/40.0)**2)/(1.0 + Bp/40.0)
			data.G1[i] = np.sum(400.0*h*(np.sin(CA/2))**3)/use.size
			data.G2[i] = 0.005*np.sum(400.0*Bs)/use.size
		else:
			data.G1[i] = 0.0
			data.G2[i] = 0.0		
	
	print()
	
	#save the data
	fname = Globals.DataPath+'TSdata.bin'
	RT.SaveRecarray(data,fname)
843574
def new_data(self, mem, addr, data):
        """"""
        if mem.id == self.id:
            if addr == LocoMemory2.ADR_ID_LIST:
                self._handle_id_list_data(data)
            elif addr == LocoMemory2.ADR_ACTIVE_ID_LIST:
                self._handle_active_id_list_data(data)
            else:
                id = int((addr - LocoMemory2.ADR_ANCHOR_BASE) /
                         LocoMemory2.ANCHOR_PAGE_SIZE)
                self._handle_anchor_data(id, data)
4559
def create_metadata_file(output_path, data_dir):
    '''
    '''

    # Relative path to all (BASIS).metadata.json files
    meta_filelist, table_filelist, _, _ = get_all_filelist(data_dir)

    metadata = {}
    for meta_file_relpath in meta_filelist:

        # Read in the metadata for a single basis set
        meta_file_path = os.path.join(data_dir, meta_file_relpath)
        bs_metadata = read_json_basis(meta_file_path)

        # Base of the filename for table basis sets
        # Basename is something like '6-31G.', including the last period
        base_relpath, meta_filename = os.path.split(meta_file_relpath)
        base_filename = meta_filename.split('.')[0] + '.'

        # All the table files that correspond to this metadata file
        # (relative to data_dir)

        this_filelist = [
            x for x in table_filelist
            if os.path.dirname(x) == base_relpath and os.path.basename(x).startswith(base_filename)
        ]

        # The 'versions' dict that will go into the metadata
        version_info = {}

        # Make sure function types are the same
        function_types = None

        # For each table basis, compose it
        for table_file in this_filelist:
            # Obtain just the filename of the table basis
            table_filename = os.path.basename(table_file)

            # Obtain the base filename and version from the filename
            # The base filename is the part before the first period
            # (filebase.ver.table.json)
            table_filebase, ver, _, _ = table_filename.split('.')

            # Fully compose the basis set from components
            bs = compose_table_basis(table_file, data_dir)

            # Elements for which this basis is defined
            defined_elements = sorted(list(bs['elements'].keys()), key=lambda x: int(x))

            # Determine the types of functions contained in the basis
            # (gto, ecp, etc)
            if function_types is None:
                function_types = bs['function_types']
            elif function_types != bs['function_types']:
                raise RuntimeError("Differing function types across versions for " + base_filename)

            # Create the metadata for this specific version
            # yapf: disable
            version_info[ver] = { 'file_relpath': table_file,
                                  'revdesc': bs['revision_description'],
                                  'elements': defined_elements
                                }
            # yapf: enable

        # Sort the version dicts
        version_info = dict(sorted(version_info.items()))
        # Find the maximum version for this basis
        latest_ver = max(version_info.keys())

        # Create the common metadata for this basis set
        # display_name and other_names are placeholders to keep order
        # yapf: disable
        common_md = { 'display_name': None,
                      'other_names': None,
                      'description': bs['description'],
                      'latest_version': latest_ver,
                      'basename': base_filename[:-1], # Strip off that trailing period
                      'relpath': base_relpath,
                      'family': bs['family'],
                      'role': bs['role'],
                      'functiontypes': function_types,
                      'auxiliaries': bs['auxiliaries'],
                      'versions': version_info }
        # yapf: enable

        # Loop through all the common names, translate them, and then add the data
        for bs_name in bs_metadata['names']:
            tr_name = transform_basis_name(bs_name)

            if tr_name in metadata:
                raise RuntimeError("Duplicate basis set name: " + tr_name)

            # Create a new entry, with all the common metadata
            # Also, store the other names for this basis
            other_names = bs_metadata['names'].copy()
            other_names.remove(bs_name)
            metadata[tr_name] = common_md.copy()
            metadata[tr_name]['display_name'] = bs_name
            metadata[tr_name]['other_names'] = other_names

    # Write out the metadata
    metadata = dict(sorted(metadata.items()))
    _write_plain_json(output_path, metadata)
1325804
def memo_update(self, tid, session, memo=None, flag=None, reset=None):
        ''''''
        request = TOPRequest('taobao.trade.memo.update')
        request['tid'] = tid
        if memo!=None: request['memo'] = memo
        if flag!=None: request['flag'] = flag
        if reset!=None: request['reset'] = reset
        self.create(self.execute(request, session)['trade'])
        return self
1136571
def _copy_with_changed_callback(self, new_callback):
        '''  '''
        return TimeoutCallback(self._document, new_callback, self._timeout, self._id)
469241
def metadata(ctx, archive_name):
    '''
    
    '''

    _generate_api(ctx)
    var = ctx.obj.api.get_archive(archive_name)
    click.echo(pprint.pformat(var.get_metadata()))