Export image anchore data to a JSON file.
164897
def export(outfile):
    """"""

    if not nav:
        sys.exit(1)

    ecode = 0
    savelist = list()
    for imageId in imagelist:

        try:
            record = {}
            record['image'] = {}
            record['image']['imageId'] = imageId
            record['image']['imagedata'] = contexts['anchore_db'].load_image_new(imageId)
        
            savelist.append(record)
        except Exception as err:
            anchore_print_err("could not find record for image ("+str(imageId)+")")
            ecode = 1

    if ecode == 0:
        try:
            if outfile == '-':
                print json.dumps(savelist, indent=4)
            else:
                with open(outfile, 'w') as OFH:
                    OFH.write(json.dumps(savelist))
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            ecode = 1

    sys.exit(ecode)
172756
def _get_anchor_data(anchor_data, glyphSet, components, anchor_name):
    """"""

    anchors = []
    for component in components:
        for anchor in glyphSet[component.baseGlyph].anchors:
            if anchor.name == anchor_name:
                anchors.append((anchor, component))
                break
    if len(anchors) > 1:
        for i, (anchor, component) in enumerate(anchors):
            t = Transform(*component.transformation)
            name = '%s_%d' % (anchor.name, i + 1)
            anchor_data[name] = t.transformPoint((anchor.x, anchor.y))
    elif anchors:
        anchor, component = anchors[0]
        t = Transform(*component.transformation)
        anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))
781980
def export_to_html(
    table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs
):
    """"""

    serialized_table = serialize(table, *args, **kwargs)
    fields = next(serialized_table)
    result = ["<table>\n\n"]
    if caption and table.name:
        result.extend(["  <caption>", table.name, "</caption>\n\n"])
    result.extend(["  <thead>\n", "    <tr>\n"])
    # TODO: set @name/@id if self.meta["name"] is set
    header = ["      <th> {} </th>\n".format(field) for field in fields]
    result.extend(header)
    result.extend(["    </tr>\n", "  </thead>\n", "\n", "  <tbody>\n", "\n"])
    for index, row in enumerate(serialized_table, start=1):
        css_class = "odd" if index % 2 == 1 else "even"
        result.append('    <tr class="{}">\n'.format(css_class))
        for value in row:
            result.extend(["      <td> ", escape(value), " </td>\n"])
        result.append("    </tr>\n\n")
    result.append("  </tbody>\n\n</table>\n")
    html = "".join(result).encode(encoding)

    return export_data(filename_or_fobj, html, mode="wb")
894549
def _download_images(data, img_cols):
  """"""

  images = collections.defaultdict(list)
  for d in data:
    for img_col in img_cols:
      if d.get(img_col, None):
        if isinstance(d[img_col], Image.Image):
          # If it is already an Image, just copy and continue.
          images[img_col].append(d[img_col])
        else:
          # Otherwise it is image url. Load the image.
          with file_io.FileIO(d[img_col], 'rb') as fi:
            im = Image.open(fi)
          images[img_col].append(im)
      else:
        images[img_col].append('')

  return images
6155
protected function buildJSON()
    {
        $json = $this->parent->createFileJson($this->file);
        $json['created'] = $this->file->obj('Created')->FormatFromSettings();
        $json['lastEdited'] = $this->file->obj('LastEdited')->FormatFromSettings();
        $json['url'] = $this->file->getAbsoluteURL();

        $json['size'] = $this->file->getSize();
        $json['folder'] = $this->file->Parent()->Filename;

        if ($this->file instanceof Image) {
            $preview = $this->file->Fill(400, 133);
            $detail = $this->file->getKickAssetsDetailImage();
            $json['previewImage'] = $preview ? $preview->URL : $this->file->getPreviewThumbnail(128, 128)->URL;
            $json['detailImage'] = $detail ? $detail->URL : $this->file->getPreviewThumbnail(128, 128)->URL;
        }

        return $json;
    }
104685
def to_json(data):
    """"""
    return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)
528482
def load_data_file_to_net(self, filename):
    '''
    
    '''
    inst_dat = self.load_json_to_dict(filename)
    load_data.load_data_to_net(self, inst_dat)
378171
def as_json(self, ensure_ascii=False):
        """"""
        return json.dumps(self.as_dict, ensure_ascii=ensure_ascii)
1241544
def from_json(data):
        
        memfiles = InMemoryFiles()
        memfiles.files = json.loads(data)
        return memfiles
178298
def export_to_file(self, filename):
        
        instr_json = self.export_struct()

        with open(filename, 'w') as fp:
            json.dump(instr_json, fp, indent=2)
693512
def to_json(self, filename):
        
        with open(filename, 'w') as fp:
            json.dump(dict(stimuli=self.stimuli, inhibitors=self.inhibitors, readouts=self.readouts), fp)
738968
def to_json_file(self, path, file_name=None):
        """"""
        if bool(path) and os.path.isdir(path):
            self.write_to_json(path, file_name)
        else:
            self.write_to_json(os.getcwd(), file_name)
582792
def fromJSON(value):
        """"""
        if isinstance(value, str):
            value = json.loads(value)
        elif isinstance(value, dict): pass
        else:
            raise AttributeError("Invalid input")
        return Extension(typeName=value['typeName'],
                         capabilities=value['capabilities'],
                         enabled=value['enabled'] == "true",
                         maxUploadFileSize=value['maxUploadFileSize'],
                         allowedUploadFileType=value['allowedUploadFileTypes'],
                         properties=value['properties'])
1143972
def savejson(filename, datadict):
    
    for key, value in datadict.items():
        if type(value) == np.ndarray:
            datadict[key] = value.tolist()
        if type(value) == dict:
            for key2, value2 in value.items():
                if type(value2) == np.ndarray:
                    datadict[key][key2] = value2.tolist()
    with open(filename, "w") as f:
        f.write(json.dumps(datadict, indent=4))
1099708
def image_import(infile, force):
    """"""
    ecode = 0
    
    try:
        with open(infile, 'r') as FH:
            savelist = json.loads(FH.read())
    except Exception as err:
        anchore_print_err("could not load input file: " + str(err))
        ecode = 1

    if ecode == 0:
        for record in savelist:
            try:
                imageId = record['image']['imageId']
                if contexts['anchore_db'].is_image_present(imageId) and not force:
                    anchore_print("image ("+str(imageId)+") already exists in DB, skipping import.")
                else:
                    imagedata = record['image']['imagedata']
                    try:
                        rc = contexts['anchore_db'].save_image_new(imageId, report=imagedata)
                        if not rc:
                            contexts['anchore_db'].delete_image(imageId)
                            raise Exception("save to anchore DB failed")
                    except Exception as err:
                        contexts['anchore_db'].delete_image(imageId)
                        raise err
            except Exception as err:
                anchore_print_err("could not store image ("+str(imageId)+") from import file: "+ str(err))
                ecode = 1

    sys.exit(ecode)
174714
def download_json(local_filename, url, clobber=False):
    """"""
    with open(local_filename, 'w') as json_file:
        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))
972063
def getJson(url):
    """"""
    site = urllib2.urlopen(url, timeout=300)
    return json.load(site)