Register a comm and return a serializable object with target name
510111
def create_event_handler(event_type, handler):
    """"""

    target_name = '{hash}_{event_type}'.format(hash=hash(handler), event_type=event_type)

    def handle_comm_opened(comm, msg):
        @comm.on_msg
        def _handle_msg(msg):
            data = msg['content']['data']
            event = json.loads(data)
            return_value = handler(event)
            if return_value:
                comm.send(return_value)

        comm.send('Comm target "{target_name}" registered by vdom'.format(target_name=target_name))

    # Register a new comm for this event handler
    if get_ipython():
        get_ipython().kernel.comm_manager.register_target(target_name, handle_comm_opened)

    # Return a serialized object
    return target_name
845929
function register(app, targetEndpoint) {
  var builder = new Builder(app, targetEndpoint);

  // create and update APIs
  app.put('/apiql/apis/:name', bodyParsers(), function (req, res, done) {
    builder.buildAPI(req.params.name, req.headers['content-type'], req.body, function (err) {
      if (err) {
        res.sendStatus(400);
      } else {
        res.sendStatus(204);
      }
      done();
    });
  });

  app.get('/apiql/apis', function (req, res, done) {
    API.listAPIs(function (err, apis) {
      if (err) {
        console.log(err);
      }
      res.format({
        json: function () {
          res.json({ items: _.map(apis, (api) => api.toJson()) }); // returns empty array even with error
        },
        default: function () {
          res.sendStatus(406);
        }
      });
      done();
    });
  });

  app.get('/apiql/apis/:name', function (req, res, done) {
    API.findByName(req.params.name, function (err, api) {
      if (err) {
        res.sendStatus(404);
      } else {
        res.format({
          html: function () {
            res.send(docs({ name: req.params.name, description: api.description }));
          },
          json: function () {
            res.json(api.toJson());
          },
          'application/openapi+json': function () {
            res.json(api.formattedDescription(OPENAPI_JSON));
          },
          'application/openapi+yaml': function () {
            res.send(api.formattedDescription(OPENAPI_YAML));
          },
          default: function () {
            res.sendStatus(406);
          }
        });
      }
      done();
    });
  });

  app.delete('/apiql/apis/:name', function (req, res, done) {
    builder.removeExistingAPI(req.params.name)(function (err) {
      if (err) {
        if (err.message == NOT_FOUND) {
          res.sendStatus(404);
        } else {
          res.status(500).send(err.message);
        }
      } else {
        res.sendStatus(204); // return the deleted item
      }
      done();
    });
  });

  // returns apiql OpenApi 3.0 API Description document or rendered documentation via conneg
  app.get('/apiql/api-description', function (req, res, done) {
    var description;

    try {
      description = yaml.safeLoad(fs.readFileSync(descriptionFilePath, 'utf8'));
    } catch (err) {
      console.log(err);
      res.status(500).send(err.message);
    }

    res.format({
      html: function () {
        res.send(docs({ name: 'APIQL Docs', description: description }));
      },
      'application/openapi+json': function () {
        res.send(description);
      },
      'application/openapi+yaml': function () {
        res.send(yaml.safeDump(description));
      },
      default: function () {
        res.sendStatus(406);
      }
    });
    done();
  });
}
529330
def _generate_serializable_funcs(self, data_type_name):
        """"""
        with self.block_func(
                func='serialize',
                args=fmt_func_args_declaration([('instance', 'id')]),
                return_type='nullable NSDictionary<NSString *, id>  *',
                class_func=True):
            func_call = fmt_func_call(
                caller=fmt_serial_class(data_type_name),
                callee='serialize',
                args=fmt_func_args([('instance', 'instance')]))
            self.emit('return {};'.format(func_call))
        self.emit()

        with self.block_func(
                func='deserialize',
                args=fmt_func_args_declaration([('dict', 'NSDictionary<NSString *, id>  *')]),
                return_type='id',
                class_func=True):
            self.emit('return {};'.format(
                fmt_func_call(
                    caller=fmt_serial_class(data_type_name),
                    callee='deserialize',
                    args=fmt_func_args([('dict', 'dict')]))))
        self.emit()
644774
def _serialize(self, value, attr, obj):
        """"""
        value = super(PhoneNumberField, self)._serialize(value, attr, obj)

        if value:
            value = self._format_phone_number(value, attr)

        return value
584538
def register(self):
        """"""
        # Assume utf8 encoding
        utf8 = encodings.search_function('utf8')

        class StreamReader(utf_8.StreamReader):
            """Used by cPython to deal with a spec file"""
            def __init__(sr, stream, *args, **kwargs):
                codecs.StreamReader.__init__(sr, stream, *args, **kwargs)
                data = self.dealwith(sr.stream.readline)
                sr.stream = StringIO(data)

        def decode(text, *args, **kwargs):
            """Used by pypy and pylint to deal with a spec file"""
            return_tuple = kwargs.get("return_tuple", True)

            if six.PY3:
                if hasattr(text, 'tobytes'):
                    text = text.tobytes().decode('utf8')
                else:
                    text = text.decode('utf8')

            buffered = StringIO(text)

            # Determine if we need to have imports for this string
            # It may be a fragment of the file
            has_spec = regexes['encoding_matcher'].search(buffered.readline())
            no_imports = not has_spec
            buffered.seek(0)

            # Translate the text
            if six.PY2:
                utf8 = encodings.search_function('utf8') # Assume utf8 encoding
                reader = utf8.streamreader(buffered)
            else:
                reader = buffered

            data = self.dealwith(reader.readline, no_imports=no_imports)

            # If nothing was changed, then we want to use the original file/line
            # Also have to replace indentation of original line with indentation of new line
            # To take into account nested describes
            if text and not regexes['only_whitespace'].match(text):
                if regexes['whitespace'].sub('', text) == regexes['whitespace'].sub('', data):
                    bad_indentation = regexes['leading_whitespace'].search(text).groups()[0]
                    good_indentation = regexes['leading_whitespace'].search(data).groups()[0]
                    data = '%s%s' % (good_indentation, text[len(bad_indentation):])

            # If text is empty and data isn't, then we should return text
            if len(text) == 0 and len(data) == 1:
                if return_tuple:
                    return "", 0
                else:
                    return ""

            # Return translated version and it's length
            if return_tuple:
                return data, len(data)
            else:
                return data

        incrementaldecoder = utf8.incrementaldecoder
        if six.PY3:
            def incremental_decode(decoder, *args, **kwargs):
                """Wrapper for decode from IncrementalDecoder"""
                kwargs["return_tuple"] = False
                return decode(*args, **kwargs)
            incrementaldecoder = type("IncrementalDecoder", (utf8.incrementaldecoder, ), {"decode": incremental_decode})

        def search_function(s):
            """Determine if a file is of spec encoding and return special CodecInfo if it is"""
            if s != 'spec': return None
            return codecs.CodecInfo(
                  name='spec'
                , encode=utf8.encode
                , decode=decode
                , streamreader=StreamReader
                , streamwriter=utf8.streamwriter
                , incrementalencoder=utf8.incrementalencoder
                , incrementaldecoder=incrementaldecoder
                )

        # Do the register
        codecs.register(search_function)
1052379
def _register_parser(cls):
    ''''''
    assert cls.cls_msg_type is not None
    assert cls.cls_msg_type not in _MSG_PARSERS
    _MSG_PARSERS[cls.cls_msg_type] = cls.parser
    return cls
492716
def ref2names2commdct(ref2names, commdct):
    """"""
    for comm in commdct:
        for cdct in comm:
            try:
                refs = cdct['object-list'][0]
                validobjects = ref2names[refs]
                cdct.update({'validobjects':validobjects})
            except KeyError as e:
                continue
    return commdct
1211862
def _StructMessageToJsonObject(self, message):
    """"""
    fields = message.fields
    ret = {}
    for key in fields:
      ret[key] = self._ValueMessageToJsonObject(fields[key])
    return ret
745415
def construct(cls, name, *args, **kwargs):
        
        return cls.REGISTRY[name](*args, **kwargs)
81284
def handle_comm_opened(comm, msg):
        """"""
        version = msg.get('metadata', {}).get('version', '')
        if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
            raise ValueError("Incompatible widget protocol versions: received version %r, expected version %r"%(version, __protocol_version__))
        data = msg['content']['data']
        state = data['state']

        # Find the widget class to instantiate in the registered widgets
        widget_class = Widget.widget_types.get(state['_model_module'],
                                               state['_model_module_version'],
                                               state['_model_name'],
                                               state['_view_module'],
                                               state['_view_module_version'],
                                               state['_view_name'])
        widget = widget_class(comm=comm)
        if 'buffer_paths' in data:
            _put_buffers(state, data['buffer_paths'], msg['buffers'])
        widget.set_state(state)
220529
def ctcp(self, target, message, nowait=False):
        """"""
        if target and message:
            messages = utils.split_message(message, self.config.max_length)
            f = None
            for message in messages:
                f = self.send_line('PRIVMSG %s :\x01%s\x01' % (target,
                                                               message),
                                   nowait=nowait)
            return f
1078990
public <TMessage> void register(final Class<TMessage> msgMetaClass) {
    final String classId = getClassId(msgMetaClass);
    LOG.log(Level.INFO, "Registering message: {0}", classId);
    this.nameToSerializerMap.put(classId, SerializationFactory.createSerializer(msgMetaClass));
    this.nameToDeserializerMap.put(classId, SerializationFactory.createDeserializer(msgMetaClass));
  }
410232
def Register():
  """"""
  # pyformat: disable

  # Command parsers.
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Dpkg", linux_cmd_parser.DpkgCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Dmidecode", linux_cmd_parser.DmidecodeCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Mount", config_file.MountCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "OsxSpHardware", osx_file_parser.OSXSPHardwareDataTypeParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Ps", linux_cmd_parser.PsCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Rpm", linux_cmd_parser.RpmCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "SshdConfig", config_file.SshdConfigCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Sysctl", linux_sysctl_parser.SysctlCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "YumList", linux_cmd_parser.YumListCmdParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "YumRepolist", linux_cmd_parser.YumRepolistCmdParser)

  # Grep parsers.
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Passwd", linux_file_parser.PasswdBufferParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "Netgroup", linux_file_parser.NetgroupBufferParser)

  # WMI query parsers.
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WmiEventConsumer", wmi_parser.WMIEventConsumerParser)
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WmiInstalledSoftware", wmi_parser.WMIInstalledSoftwareParser)
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WmiHotfixesSoftware", wmi_parser.WMIHotfixesSoftwareParser)
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WmiUser", wmi_parser.WMIUserParser)
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WmiLogicalDisks", wmi_parser.WMILogicalDisksParser)
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WmiCsp", wmi_parser.WMIComputerSystemProductParser)
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WmiInterfaces", wmi_parser.WMIInterfacesParser)

  # Registry value parsers.
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinCcs", windows_registry_parser.CurrentControlSetKBParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinCodepage", windows_registry_parser.CodepageParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinEnvironment", windows_registry_parser.WinEnvironmentParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinServices", windows_registry_parser.WinServicesParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinSystemDrive", windows_registry_parser.WinSystemDriveParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinSystemRoot", windows_registry_parser.WinSystemRootParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinTimezone", windows_registry_parser.WinTimezoneParser)

  # Registry parsers.
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinAllUsersProfileEnvVar",
      windows_registry_parser.AllUsersProfileEnvironmentVariable)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinProfileDirEnvVar",
      windows_registry_parser.ProfilesDirectoryEnvironmentVariable)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WinUserSids",
      windows_registry_parser.WinUserSids)

  # Artifact file parsers.
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "DarwinPersistenceMechanism",
      osx_launchd.DarwinPersistenceMechanismsParser)
  parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register(
      "WindowsPersistenceMechanism",
      windows_persistence.WindowsPersistenceMechanismsParser)

  # Registry multi-parsers.
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "WinUserSpecialDirs", windows_registry_parser.WinUserSpecialDirs)

  # Artifact file multi-parsers.
  parsers.MULTI_RESPONSE_PARSER_FACTORY.Register(
      "OsxUsers", osx_file_parser.OSXUsersParser)

  # File parsers.
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "ChromeHistory", chrome_history.ChromeHistoryParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "CronAtAllAllowDeny", config_file.CronAtAllowDenyParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "CronTab", cron_file_parser.CronTabParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "FirefoxHistory", firefox3_history.FirefoxHistoryParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "IeHistory", ie_history.IEHistoryParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "LinuxWtmp", linux_file_parser.LinuxWtmpParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "Mtab", config_file.MtabParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "Netgroup", linux_file_parser.NetgroupParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "NfsExports", config_file.NfsExportsParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "Ntpd", config_file.NtpdParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "PackageSource", config_file.PackageSourceParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "Passwd", linux_file_parser.PasswdParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "Path", linux_file_parser.PathParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "SshdConfigFile", config_file.SshdConfigParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "Sudoers", config_file.SudoersParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "OsxLaunchdPlist", osx_file_parser.OSXLaunchdPlistParser)
  parsers.SINGLE_FILE_PARSER_FACTORY.Register(
      "OSXInstallHistoryPlist", osx_file_parser.OSXInstallHistoryPlistParser)

  try:
    from debian import deb822  # pylint: disable=g-import-not-at-top
    parsers.SINGLE_FILE_PARSER_FACTORY.Register(
        "DpkgStatusParser",
        lambda: linux_software_parser.DebianPackagesStatusParser(deb822))
  except ImportError:
    pass


  # File multi-parsers.
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "LinuxBaseShadow", linux_file_parser.LinuxBaseShadowParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "LinuxLsbInit", linux_service_parser.LinuxLSBInitParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "LinuxXinetd", linux_service_parser.LinuxXinetdParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "LinuxSysvInit", linux_service_parser.LinuxSysVInitParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "LinuxPam", linux_pam_parser.PAMParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "LinuxReleaseInfo", linux_release_parser.LinuxReleaseParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "PciDevicesInfo", linux_file_parser.PCIDevicesInfoParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "ProcSys", linux_sysctl_parser.ProcSysParser)
  parsers.MULTI_FILE_PARSER_FACTORY.Register(
      "Rsyslog", config_file.RsyslogParser)
672797
def _construct_register(reg, default_reg):
    """"""
    if reg:
        x = dict((k, reg.get(k, d)) for k, d in default_reg.items())
    else:
        x = dict(default_reg)
    return x
1167108
def getfieldcomm(bunchdt, data, commdct, idfobject, fieldname):
    """"""
    key = idfobject.obj[0].upper()
    keyi = data.dtls.index(key)
    fieldi = idfobject.objls.index(fieldname)
    thiscommdct = commdct[keyi][fieldi]
    return thiscommdct
727351
def take_register(self, rtype = SharedData.TYPES.NO_TYPE):
        """"""
        if len(self.free_registers) == 0:
            self.error("no more free registers")
        reg = self.free_registers.pop()
        self.used_registers.append(reg)
        self.symtab.set_type(reg, rtype)
        return reg
220267
def _serialized(self):
        """"""
        return {'title': self.title,
                'summary': self.summary,
                'areadesc': self.areadesc,
                'event': self.event,
                'samecodes': self.samecodes,
                'zonecodes': self.zonecodes,
                'expiration': self.expiration,
                'updated': self.updated,
                'effective': self.effective,
                'published': self.published,
                'severity': self.severity,
                'category': self.category,
                'urgency': self.urgency,
                'msgtype': self.msgtype,
                'link': self.link,
                }