Returns a callback to convert test record to proto and save to disk.
555522
def save_to_disk(self, filename_pattern=None):
    """"""
    if not self._converter:
      raise RuntimeError(
          'Must set _converter on subclass or via set_converter before calling '
          'save_to_disk.')

    pattern = filename_pattern or self._default_filename_pattern
    if not pattern:
      raise RuntimeError(
          'Must specify provide a filename_pattern or set a '
          '_default_filename_pattern on subclass.')

    def save_to_disk_callback(test_record_obj):
      proto = self._convert(test_record_obj)
      output_to_file = callbacks.OutputToFile(pattern)

      with output_to_file.open_output_file(test_record_obj) as outfile:
        outfile.write(proto.SerializeToString())

    return save_to_disk_callback
198308
def do_save(self, arg):
        """"""
        #We need to save the full paths to the staging directories for the tests that are loaded
        #so far; then when the session is restored, we can reparse the results.
        from os import path
        import json
        fullpath = path.expanduser(arg)

        data = {
            "tests": [path.abspath(a.stagedir) for a in list(self.tests.values())],
            "args": self.args
        }

        with open(fullpath, 'w') as f:
            json.dump(data, f)
        msg.okay("Saved current session to {}".format(fullpath))
258437
function(data) {
    if(!data || !data.sys) {
      return;
    }
    dict = data.sys.dict;
    var protos = data.sys.protos;

    //Init compress dict
    if(dict) {
      dict = dict;
      abbrs = {};

      for(var route in dict) {
        abbrs[dict[route]] = route;
      }
    }

    //Init protobuf protos
    if(protos) {
      protoVersion = protos.version || 0;
      serverProtos = protos.server || {};
      clientProtos = protos.client || {};

        //Save protobuf protos to localStorage
        window.localStorage.setItem('protos', JSON.stringify(protos));

        if(!!protobuf) {
          protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server});
        }
        if(!!decodeIO_protobuf) {
          decodeIO_encoder = decodeIO_protobuf.loadJson(clientProtos);
          decodeIO_decoder = decodeIO_protobuf.loadJson(serverProtos);
        }
      }
    }
210342
def from_record(cls, record, crs):
        """"""
        if 'type' not in record:
            raise TypeError("The data isn't a valid record.")

        return cls(to_shape(record), crs)
933375
def save(self):
        
        if 'save' not in self._supports:
            raise AssertionError('Can not save this object type')

        values = {}
        for key in [key for key in self.keys() if key not in self._save_ignore]:
            if not getattr(self, key) and getattr(self, key) != False:
                continue

            if isinstance(getattr(self, key, None), list):
                value = list()
                for item in getattr(self, key):
                    if isinstance(item, dict):
                        value.append(item)
                    elif hasattr(item, '_save_as'):
                        value.append(item._save_as())
                    elif hasattr(item, '_ref') and getattr(item, '_ref'):
                        value.append(getattr(item, '_ref'))
                    else:
                        LOGGER.warning('Cant assign %r', item)
                values[key] = value
            elif getattr(self, key, None):
                values[key] = getattr(self, key)
        if not self._ref:
            response = self._session.post(self._path, values)
        else:
            values['_ref'] = self._ref
            response = self._session.put(self._path, values)
        LOGGER.debug('Response: %r, %r', response.status_code, response.content)
        if 200 <= response.status_code <= 201:
            self.fetch()
            return True
        else:
            try:
                error = response.json()
                raise exceptions.ProtocolError(error['text'])
            except ValueError:
                raise exceptions.ProtocolError(response.content)
672771
def dumper(args, config, transform_func=None):
    """"""
    args = process_args(args)
    submit_args = get_submit_args(args)

    submit_outcome = submit_if_ready(args, submit_args, config)
    if submit_outcome is not None:
        # submitted, nothing more to do
        return submit_outcome

    import_time = datetime.datetime.utcnow()

    try:
        records = dump2polarion.import_results(args.input_file, older_than=import_time)
        testrun_id = get_testrun_id(args, config, records.testrun)
        exporter = dump2polarion.XunitExport(
            testrun_id, records, config, transform_func=transform_func
        )
        output = exporter.export()
    except NothingToDoException as info:
        logger.info(info)
        return 0
    except (EnvironmentError, Dump2PolarionException) as err:
        logger.fatal(err)
        return 1

    if args.output_file or args.no_submit:
        # when no output file is specified, the 'testrun_TESTRUN_ID-TIMESTAMP'
        # file will be created in current directory
        exporter.write_xml(output, args.output_file)

    if not args.no_submit:
        response = dump2polarion.submit_and_verify(output, config=config, **submit_args)

        __, ext = os.path.splitext(args.input_file)
        if ext.lower() in dbtools.SQLITE_EXT and response:
            dbtools.mark_exported_sqlite(args.input_file, import_time)

        return 0 if response else 2

    return 0
720416
def convert_by_record(self, url_record):
        ''''''
        filename = url_record.filename

        if not os.path.exists(filename):
            return

        if url_record.link_type:
            if url_record.link_type not in ('css', 'html'):
                return
            else:
                link_type = url_record.link_type
        else:
            with open(filename, 'rb') as in_file:
                if HTMLScraper.is_supported(
                        file=in_file, url_info=url_record.url_info):
                    link_type = 'html'
                elif CSSScraper.is_supported(
                        file=in_file, url_info=url_record.url_info):
                    link_type = 'css'
                else:
                    link_type = None

        _logger.info(__(
            _('Converting links in file ‘{filename}’ (type={type}).'),
            filename=filename, type=link_type
        ))

        if self._backup_enabled:
            shutil.copy2(filename, filename + '.orig')

        temp_filename = filename + '-new'

        if link_type == 'css':
            self._css_converter.convert(
                filename, temp_filename, base_url=url_record.url)
        elif link_type == 'html':
            self._html_converter.convert(
                filename, temp_filename, base_url=url_record.url)
        else:
            raise Exception('Unknown link type.')

        os.remove(filename)
        os.rename(temp_filename, filename)
200690
def save(self, idempotency_key=None):
        """"""
        updated_params = self.serialize(None)
        headers = populate_headers(idempotency_key)

        if not updated_params:
            util.logger.debug("Trying to save already saved object %r", self)
            return defer.succeed(self)

        d = self.request('post', self.instance_url(), updated_params, headers)
        return d.addCallback(self.refresh_from).addCallback(lambda _: self)
166241
def MakeProto():
  """"""
  # Start running from one directory above the grr directory which is found by
  # this scripts's location as __file__.
  cwd = os.path.dirname(os.path.abspath(__file__))

  # Find all the .proto files.
  protos_to_compile = []
  for (root, _, files) in os.walk(cwd):
    for filename in files:
      full_filename = os.path.join(root, filename)
      if full_filename.endswith(".proto"):
        proto_stat = os.stat(full_filename)

        pb2_path = full_filename.rsplit(".", 1)[0] + "_pb2.py"
        try:
          pb2_stat = os.stat(pb2_path)
          if pb2_stat.st_mtime >= proto_stat.st_mtime:
            continue

        except (OSError, IOError):
          pass

        protos_to_compile.append(full_filename)

  if protos_to_compile:
    # Find the protoc compiler.
    protoc = os.environ.get("PROTOC", "protoc")
    try:
      output = subprocess.check_output([protoc, "--version"])
    except (IOError, OSError):
      raise RuntimeError("Unable to launch %s protoc compiler. Please "
                         "set the PROTOC environment variable.", protoc)

    if b"3.6.1" not in output:
      raise RuntimeError("Incompatible protoc compiler detected. "
                         "We need 3.6.1 not %s" % output)

    for proto in protos_to_compile:
      command = [
          protoc,
          # Write the python files next to the .proto files.
          "--python_out",
          ROOT,
          "--proto_path=%s" % ROOT,
          proto
      ]
      print(
          "Compiling %s with (cwd: %s): %s" % (proto, ROOT, " ".join(command)))
      # The protoc compiler is too dumb to deal with full paths - it expects a
      # relative path from the current working directory.
      subprocess.check_call(command, cwd=ROOT)
216260
public Future<WriteResponse> write(D record, @Nullable WriteCallback callback) {
    try {
      Future<RecordMetadata> future = this.accumulator.append(record, callback);
      return new WriteResponseFuture (future, WRITE_RESPONSE_WRAPPER);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
1242152
def _get_proto():
    '''
    
    '''
    use_ssl = config.get_cloud_config_value(
        'use_ssl',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default=True
    )
    if use_ssl is True:
        return 'https'
    return 'http'
1184500
def transform_record(self, pid, record, links_factory=None, **kwargs):
        """"""
        context = kwargs.get('marshmallow_context', {})
        context.setdefault('pid', pid)
        return self.dump(self.preprocess_record(pid, record,
                         links_factory=links_factory, **kwargs), context)
936383
def _serialize_call(self, format_, call):
        """'"""
        if isinstance(call, record.UnparsedCall):
            return call.unparsed_data
        else:
            result = [
                format_value(self.header.get_format_field_info(key), call.data.get(key), "FORMAT")
                for key in format_
            ]
            return ":".join(result)
616616
function saveRecord(rType, idFun) {
  return function(records, callback) {
    GLOBAL.debug('inserting', records.length, rType);
    if (!_.isArray(records)) {
      records = [records];
    }
    var tc = [];
    records.forEach(function(d) {
      var meta = {_index : GLOBAL.config.ESEARCH._index, _type : rType};
      if (idFun) {
        meta._id = idFun(d);
      }
      tc.push({ index : meta});
      tc.push(d);
    });
    getEs().bulk(tc, function (err, data) {
      callback(err, data, records);
    });
  };
}
610802
private GenericRecord convertRowToAvroRecord(Schema schema, Row row) {
		final List<Schema.Field> fields = schema.getFields();
		final int length = fields.size();
		final GenericRecord record = new GenericData.Record(schema);
		for (int i = 0; i < length; i++) {
			final Schema.Field field = fields.get(i);
			record.put(i, convertFlinkType(field.schema(), row.getField(i)));
		}
		return record;
	}
766886
def serialize(self, pid, record, links_factory=None):
        
        return simpledc.tostring(
            self.transform_record(pid, record, links_factory))
393349
function(key, value, proto, parseProtoCheck, reviveDate) {
        if (reviveDate && (typeof value==='string')) {
            return value.toDate() || value;
        }
        if (!Object.isObject(value)) {
            return value;
        }
        // only first level of objects can be given the specified prototype
        if ((typeof parseProtoCheck === 'function') && !parseProtoCheck(value)) {
            return value;
        }
        if (PROTO_SUPPORTED) {
            value.__proto__ = proto;
            return value;
        }
        return value.deepClone(null, proto);
    }