Unpack the init connect response
480042
def unpack_rsp(cls, rsp_pb):
        """"""
        ret_type = rsp_pb.retType
        ret_msg = rsp_pb.retMsg

        if ret_type != RET_OK:
            return RET_ERROR, ret_msg, None

        res = {}
        if rsp_pb.HasField('s2c'):
            res['server_version'] = rsp_pb.s2c.serverVer
            res['login_user_id'] = rsp_pb.s2c.loginUserID
            res['conn_id'] = rsp_pb.s2c.connID
            res['conn_key'] = rsp_pb.s2c.connAESKey
            res['keep_alive_interval'] = rsp_pb.s2c.keepAliveInterval
        else:
            return RET_ERROR, "rsp_pb error", None

        return RET_OK, "", res
1213682
def unpack(cls, data):
        
        header, data = APPHeader.unpack(data)

        if len(data) < header.payload_length:
            raise ProtocolViolation("Payload too small")
        payload = data[:header.payload_length]
        body = cls()
        body._header = header
        body._payload = payload
        return body, data[header.payload_length:]
459299
function init(options = {}, handlebars) {
  const opts = deepExtend({}, defaults, options);
  normalizePaths(opts);
  opts.handlebars = handlebars || Handlebars.create();
  return Promise.resolve(opts);
}
396579
function init() {
        // This function is called during Ghost's initialization.
        // Reading translation file for messages from core .js files and keeping its content in memory
        // The English file is always loaded, until back-end translations are enabled in future versions.
        // Before that, see previous tasks on issue #6526 (error codes or identifiers, error message
        // translation at the point of display...)
        coreStrings = fs.readFileSync(path.join(__dirname, '..', '..', 'translations', 'en.json'));

        // if translation file is not valid, you will see an error
        try {
            coreStrings = JSON.parse(coreStrings);
        } catch (err) {
            coreStrings = undefined;
            throw err;
        }

        _private.initializeIntl();
    }
51782
function() {
			global.requestSSLInitializing = false;
			global.requestSSLInitialized = true;
			global.requestSSLHooks = null;
			// unpatch ourselves
			request.Request.prototype.init = patchedInit;
			debug('init done');
			return patchedInit.apply(self,args);
		}
1237339
function init() {
    var debugFile = path.join(__dirname, 'debug.js');

    if (debug) {
        if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); }
        debugFD = fs.openSync(debugFile, 'a');
    }

    getFileList(modelsPath).forEach(defineModel);
    processAllRelations(defineRelation);

    if (debug) {
        fs.closeSync(debugFD);
    }
}
914567
def _unpack_object_array(inp, source, prescatter):
    
    raise NotImplementedError("Currently not used with record/struct/object improvements")
    base_rec, attr = source.rsplit(".", 1)
    new_name = "%s_%s_unpack" % (inp["name"], base_rec.replace(".", "_"))
    prescatter[base_rec].append((new_name, attr, _to_variable_type(inp["type"]["items"])))
    return new_name, prescatter
1240446
def unpack_data(self, usnap=.2):  # 2/10th second sleep between empty requests
        
        for new_data in self.socket:
            if new_data:
                self.data_stream.unpack(new_data)
            else:
                sleep(usnap)
111702
def _post_init(self):
        """"""
        try:
            return self.postinit()
        except Exception as exc:
            return self._onerror(Result.from_exception(exc, uuid=self.uuid))
919521
def unpack(rv):
    
    if isinstance(rv, ResponseBase):
        return rv

    status = headers = None
    if isinstance(rv, tuple):
        rv, status, headers = rv + (None,) * (3 - len(rv))

    if rv is None:
        raise ValueError('View function did not return a response')

    if status is None:
        status = 200
    return rv, status, headers or {}
1120109
def unpack_reply(cls, header, payload):
        
        reply = cls(
            header.session_id, header.packet_count,
            segments=tuple(ReplySegment.unpack_from(payload, expected_segments=header.num_segments)),
            header=header
        )
        trace(reply)
        return reply
537800
function init(){
    self.type = config.type || 'redis';
    if(config.redisMock){
      self.db = config.redisMock;
    }
    else{
      if(config.redisUrl){
        self.redisData = config.redisUrl || null;
      }
      else if(config.redisEnv){
        self.redisData = process.env[config.redisEnv] || null;
      }
      else if(config.redisData){
        self.redisData = config.redisData;
      }
      self.readOnly = (typeof config.readOnly === 'boolean') ? config.readOnly : false;
      try {
        if (self.redisData) {
          if(typeof self.redisData === 'string'){
            self.db = redis.createClient(self.redisData,
              {'no_ready_check': true,
              retry_strategy: retryStrategy});
          } else {
            self.db = redis.createClient(self.redisData.port,
              self.redisData.hostname, {'no_ready_check': true,
              retry_strategy: retryStrategy});

            // don't call redis auth method if no auth info passed
            if (self.redisData.auth) {
              self.db.auth(self.redisData.auth);
            }
          }
          self.db.on('error', function(err) {
            console.log('Error ' + err);
          });
          process.on('SIGTERM', function() {
            self.db.quit();
          });
          log(false, 'Redis client created with the following defaults:', {expiration: self.defaultExpiration, verbose: self.verbose, readOnly: self.readOnly});
        } else {
          self.db = false;
          log(false, 'Redis client not created: no redis config provided');
        }
      } catch (err) {
        self.db = false;
        log(true, 'Redis client not created:', err);
      }
    }
  }
939440
def init(i): # pragma: no cover
    

    global cfg, work, initialized, paths_repos, type_long, string_io

    if initialized:
       return {'return':0}

    # Split version
    cfg['version']=__version__.split('.')

    # Default URL. FIXME: should be formed from wfe_host and wfe_port when they are known.
    # cfg['wfe_url_prefix'] = 'http://%s:%s/web?' % (cfg['default_host'], cfg['default_port'])

    # Check long/int types
    try:
       x=long
    except Exception as e:
       type_long=int
    else:
       type_long=long

    # Import StringIO
    if sys.version_info[0]>2:
       import io
       string_io=io.StringIO
    else:
       from StringIO import StringIO
       string_io=StringIO

    # Check where are repos (to keep compatibility with past CK < V1.5)
    p=''

    import inspect
    pxx=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    px=os.path.dirname(pxx)
    py=os.path.join(pxx, cfg['subdir_default_repo'])
    if os.path.isdir(py):
       p=py

    if p=='':
       from distutils.sysconfig import get_python_lib
       px=get_python_lib()
       py=os.path.join(px, cfg['kernel_dir'], cfg['subdir_default_repo'])
       if os.path.isdir(py):
          p=py

    if p=='':
       import site
       for px in site.getsitepackages():
           py=os.path.join(px, cfg['kernel_dir'],cfg['subdir_default_repo'])
           if os.path.isdir(py):
              p=py
              break

    # Check CK_ROOT environment variable
    s=os.environ.get(cfg['env_key_root'],'').strip()
    if s!='':
       work['env_root']=os.path.realpath(s)

       for px in cfg['kernel_dirs']:
           py=os.path.join(work['env_root'], px, cfg['subdir_default_repo'])
           if os.path.isdir(py):
              p=py
              break
    elif px!='':
      work['env_root']=px

    if p=='':
       return {'return':1, 'error':'Internal CK error (can\'t find default repo) - please report to authors'}

    # Check default repo
    work['dir_default_repo']=p
    work['dir_default_repo_path']=os.path.join(work['dir_default_repo'], cfg['module_repo_name'], cfg['repo_name_default'])
    work['dir_default_kernel']=os.path.join(work['dir_default_repo'], cfg['subdir_kernel'])
    work['dir_default_cfg']=os.path.join(work['dir_default_kernel'], cfg['subdir_kernel_default'], cfg['subdir_ck_ext'], cfg['file_meta'])

    work['dir_work_repo']=work['dir_default_repo']
    work['dir_work_repo_path']=work['dir_default_repo_path']
    work['dir_work_kernel']=work['dir_default_kernel']
    work['dir_work_cfg']=work['dir_default_cfg']

    work['repo_name_work']=cfg['repo_name_default']
    work['repo_uid_work']=cfg['repo_uid_default']

    # Check external repos
    rps=os.environ.get(cfg['env_key_repos'],'').strip()
    if rps=='': 
       # Get home user directory
       from os.path import expanduser
       home = expanduser("~")

       # In the original version, if path to repos was not defined, I was using CK path,
       # however, when installed as root, it will fail
       # rps=os.path.join(work['env_root'],cfg['subdir_default_repos'])
       # hence I changed to <user home dir>/CK
       rps=os.path.join(home, cfg['user_home_dir_ext'])
       if not os.path.isdir(rps):
          os.makedirs(rps)

    work['dir_repos']=rps

    # Check CK_LOCAL_REPO environment variable - if doesn't exist, create in user space
    s=os.environ.get(cfg['env_key_local_repo'],'').strip()

    if s=='':
       # Set up local default repository
       s=os.path.join(rps, cfg['repo_name_local'])
       if not os.path.isdir(s):
          os.makedirs(s)

          # Create description
          rq=save_json_to_file({'json_file':os.path.join(s,cfg['repo_file']),
                                'dict':{'data_alias':cfg['repo_name_local'],
                                        'data_uoa':cfg['repo_name_local'],
                                        'data_name':cfg['repo_name_local'],
                                        'data_uid':cfg['repo_uid_local']},
                                'sort_keys':'yes'})
          if rq['return']>0: return rq

    if s!='':
       work['local_kernel_uoa']=cfg['subdir_kernel_default']
       x=os.environ.get(cfg['env_key_local_kernel_uoa'],'').strip()
       if x!='': work['local_kernel_uoa']=x

       work['dir_local_repo']=os.path.realpath(s)
       work['dir_local_repo_path']=os.path.join(work['dir_local_repo'], cfg['module_repo_name'], cfg['repo_name_local'])
       work['dir_local_kernel']=os.path.join(work['dir_local_repo'], cfg['subdir_kernel'])
       work['dir_local_cfg']=os.path.join(work['dir_local_kernel'], work['local_kernel_uoa'], cfg['subdir_ck_ext'], cfg['file_meta'])

       # Update work repo!
       work['dir_work_repo']=work['dir_local_repo']
       work['dir_work_repo_path']=work['dir_local_repo_path']
       work['dir_work_kernel']=work['dir_local_kernel']
       work['dir_work_cfg']=work['dir_local_cfg']

       work['repo_name_work']=cfg['repo_name_local']
       work['repo_uid_work']=cfg['repo_uid_local']

       paths_repos.append({'path':work['dir_local_repo'],
                           'repo_uoa':cfg['repo_name_local'],
                           'repo_uid':cfg['repo_uid_local'],
                           'repo_alias':cfg['repo_name_local']})

    paths_repos.append({'path':work['dir_default_repo'],
                        'repo_uoa':cfg['repo_name_default'],
                        'repo_uid':cfg['repo_uid_default'],
                        'repo_alias':cfg['repo_name_default']})

    # Prepare repo cache
    work['dir_cache_repo_uoa']=os.path.join(work['dir_work_repo'],cfg['file_cache_repo_uoa'])
    work['dir_cache_repo_info']=os.path.join(work['dir_work_repo'],cfg['file_cache_repo_info'])

    # Check if first time and then copy local cache files (with remote-ck)
    if not os.path.isfile(work['dir_cache_repo_uoa']) and not os.path.isfile(work['dir_cache_repo_info']):
       rx=load_text_file({'text_file':os.path.join(work['dir_default_repo'],cfg['file_cache_repo_uoa'])})
       if rx['return']>0: return rx
       x1=rx['string']

       rx=load_text_file({'text_file':os.path.join(work['dir_default_repo'],cfg['file_cache_repo_info'])})
       if rx['return']>0: return rx
       x2=rx['string']

       rx=save_text_file({'text_file':work['dir_cache_repo_info'], 'string':x2})
       if rx['return']>0: return rx

       rx=save_text_file({'text_file':work['dir_cache_repo_uoa'], 'string':x1})
       if rx['return']>0: return rx

    # Check if local configuration exists, and if not, create it
    if not os.path.isfile(work['dir_local_cfg']):
       # Create empty local configuration
       rx=add({'repo_uoa':cfg['repo_name_local'],
               'module_uoa':cfg['subdir_kernel'],
               'data_uoa':work['local_kernel_uoa']})
       if rx['return']>0:
          return {'return':rx['return'],
                  'error':'can\'t create local configuration entry'}

    # Read kernel configuration (if exists)
    if os.path.isfile(work['dir_work_cfg']):
       r=load_json_file({'json_file':work['dir_work_cfg']})
       if r['return']>0: return r
       cfg1=r['dict']

       # Update cfg
       r=merge_dicts({'dict1':cfg, 'dict2':cfg1})
       if r['return']>0: return r

    initialized=True

    return {'return':0}
1099913
protected void handlePacket(IncomingPacket incomingPacket) {
    String typeName = incomingPacket.unpackString();
    REQID rid = incomingPacket.unpackREQID();
    if (contextMap.containsKey(rid)) {
      // This incomingPacket contains the response of Request
      Object ctx = contextMap.get(rid);
      Message.Builder bldr = responseMessageMap.get(rid);
      contextMap.remove(rid);
      responseMessageMap.remove(rid);
      incomingPacket.unpackMessage(bldr);
      // Call onResponse to handle it
      if (bldr.isInitialized()) {
        Message response = bldr.build();
        onResponse(StatusCode.OK, ctx, response);
        return;
      } else {
        onResponse(StatusCode.INVALID_PACKET, ctx, null);
        return;
      }
    } else if (rid.equals(REQID.zeroREQID)) {
      // If rid is REQID.zeroREQID, this is a Message, e.g. no need send back response.
      // Convert it into message and call onIncomingMessage() to handle it
      Message.Builder bldr = messageMap.get(typeName);
      if (bldr != null) {
        bldr.clear();
        incomingPacket.unpackMessage(bldr);
        if (bldr.isInitialized()) {
          onIncomingMessage(bldr.build());
        } else {
          // We just need to log here
          // TODO:- log
        }
      } else {
        // We got a message but we didn't register
        // TODO:- log here
      }
    } else {
      // This might be a timeout response
      // TODO:- log here
    }
  }
975963
function init() {
    network = [];
    netindex = new Int32Array(256);
    bias = new Int32Array(netsize);
    freq = new Int32Array(netsize);
    radpower = new Int32Array(netsize >> 3);

    var i, v;
    for (i = 0; i < netsize; i++) {
      v = (i << (netbiasshift + 8)) / netsize;
      network[i] = new Float64Array([v, v, v, 0]);
      //network[i] = [v, v, v, 0]
      freq[i] = intbias / netsize;
      bias[i] = 0;
    }
  }
1321517
def unpack(cls, msg, client, server, request_id):
        
        payload_document = OrderedDict()
        flags, = _UNPACK_UINT(msg[:4])
        pos = 4
        if flags != 0 and flags != 2:
            raise ValueError('OP_MSG flag must be 0 or 2 not %r' % (flags,))

        while pos < len(msg):
            payload_type, = _UNPACK_BYTE(msg[pos:pos + 1])
            pos += 1
            payload_size, = _UNPACK_INT(msg[pos:pos + 4])
            if payload_type == 0:
                doc = bson.decode_all(msg[pos:pos + payload_size],
                                      CODEC_OPTIONS)[0]
                payload_document.update(doc)
                pos += payload_size
            elif payload_type == 1:
                section_size, = _UNPACK_INT(msg[pos:pos + 4])
                pos += 4
                identifier, pos = _get_c_string(msg, pos)
                # Section starts w/ 4-byte size prefix, identifier ends w/ nil.
                documents_len = section_size - len(identifier) - 1 - 4
                documents = bson.decode_all(msg[pos:pos + documents_len],
                                            CODEC_OPTIONS)
                payload_document[identifier] = documents
                pos += documents_len

        database = payload_document['$db']
        return OpMsg(payload_document, namespace=database, flags=flags,
                     _client=client, request_id=request_id,
                     _server=server)
1257702
function readInit(message, tokens) {
	var i;
	message.parameters = {};
	for (i = 0; i < tokens.length; i = i + 4) {
		message.parameters[protocol.decodeString(tokens[i + 1])] = protocol.decodeString(tokens[i + 3]);
	}
}