Convert a Morsel object into a Cookie containing the one k/v pair.
437098
def morsel_to_cookie(morsel):
    """"""

    expires = None
    if morsel['max-age']:
        expires = time.time() + morsel['max-age']
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = time.mktime(
            time.strptime(morsel['expires'], time_template)) - time.timezone
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    )
235813
def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
        """"""
        if not cookies:
            return

        c = SimpleCookie()
        if hdrs.COOKIE in self.headers:
            c.load(self.headers.get(hdrs.COOKIE, ''))
            del self.headers[hdrs.COOKIE]

        if isinstance(cookies, Mapping):
            iter_cookies = cookies.items()
        else:
            iter_cookies = cookies  # type: ignore
        for name, value in iter_cookies:
            if isinstance(value, Morsel):
                # Preserve coded_value
                mrsl_val = value.get(value.key, Morsel())
                mrsl_val.set(value.key, value.value, value.coded_value)  # type: ignore  # noqa
                c[name] = mrsl_val
            else:
                c[name] = value  # type: ignore

        self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip()
352732
def _make_cookie(self):
        
        return struct.pack(self.COOKIE_FMT, self.COOKIE_MAGIC,
                           os.getpid(), id(self), thread.get_ident())
392292
private static Map<String, String> extractDataFromCookie(String cookieValue) {
		HashMap<String, String> data = new HashMap<String, String>();
		String[] fields = cookieValue.split("\\&");
		for (String field : fields) {
			String[] keyValue = field.split("\\=");
			try {
				data.put(keyValue[0], URLDecoder.decode(keyValue[1], "UTF-8"));
			} catch (UnsupportedEncodingException wontHappen) {
			}
		}
		return data;
	}
1229284
function(key, value){
		var ls = this._local.localStorage; // null, sessionStorage, or localStorage

		if( value === undefined ) {
			return ls ? ls.getItem(key) : $.cookie(key);
		} else if ( value === null ) {
			if( ls ) {
				ls.removeItem(key);
			} else {
				$.removeCookie(key);
			}
		} else {
			if( ls ) {
				ls.setItem(key, value);
			} else {
				$.cookie(key, value, this.options.persist.cookie);
			}
		}
	}
1063902
def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40):
    """"""
    fn = float(bytes_)
    if bytes_ >= T:
        return '%.1fT' % (fn / T)
    elif bytes_ >= G:
        return '%.1fG' % (fn / G)
    elif bytes_ >= M:
        return '%.1fM' % (fn / M)
    elif bytes_ >= K:
        return '%.1fK' % (fn / K)
    else:
        return '%d' % bytes_
248010
public static Cookie createCookie(String cookieName, @Sensitive String cookieValue, HttpServletRequest req) {
        return createCookie(cookieName, cookieValue, -1, req);
    }
820578
private HttpCookie convertCookie(Cookie cookie) {
        HttpCookie rc = new HttpCookie(cookie.getName(), cookie.getValue());
        rc.setVersion(cookie.getVersion());
        rc.setComment(cookie.getComment());
        rc.setDomain(cookie.getDomain());
        rc.setPath(cookie.getPath());
        rc.setMaxAge(cookie.getMaxAge());
        rc.setSecure(cookie.getSecure());
        return rc;
    }
469491
function _convertPairToObject(pair) {
  var keyId = pair[0];
  var valueIds = pair[1];
  return {
    keyId: keyId,
    valueIds: valueIds
  };
}
1215115
def set_cookie(self, kaka, request):
        """"""

        if not kaka:
            return

        part = urlparse(request.url)
        _domain = part.hostname
        logger.debug("%s: '%s'", _domain, kaka)

        for cookie_name, morsel in kaka.items():
            std_attr = ATTRS.copy()
            std_attr["name"] = cookie_name
            _tmp = morsel.coded_value
            if _tmp.startswith('"') and _tmp.endswith('"'):
                std_attr["value"] = _tmp[1:-1]
            else:
                std_attr["value"] = _tmp

            std_attr["version"] = 0
            # copy attributes that have values
            for attr in morsel.keys():
                if attr in ATTRS:
                    if morsel[attr]:
                        if attr == "expires":
                            std_attr[attr] = _since_epoch(morsel[attr])
                        elif attr == "path":
                            if morsel[attr].endswith(","):
                                std_attr[attr] = morsel[attr][:-1]
                            else:
                                std_attr[attr] = morsel[attr]
                        else:
                            std_attr[attr] = morsel[attr]
                elif attr == "max-age":
                    if morsel["max-age"]:
                        std_attr["expires"] = time.time() + int(morsel["max-age"])

            for att, item in PAIRS.items():
                if std_attr[att]:
                    std_attr[item] = True

            if std_attr["domain"]:
                if std_attr["domain"].startswith("."):
                    std_attr["domain_initial_dot"] = True
            else:
                std_attr["domain"] = _domain
                std_attr["domain_specified"] = True

            if morsel["max-age"] is 0:
                try:
                    self.cookiejar.clear(domain=std_attr["domain"],
                                         path=std_attr["path"],
                                         name=std_attr["name"])
                except ValueError:
                    pass
            elif std_attr["expires"] and std_attr["expires"] < utc_now():
                try:
                    self.cookiejar.clear(domain=std_attr["domain"],
                                         path=std_attr["path"],
                                         name=std_attr["name"])
                except ValueError:
                    pass
            else:
                new_cookie = http_cookiejar.Cookie(**std_attr)
                self.cookiejar.set_cookie(new_cookie)
1200518
def append_cookie(self, cookie, name, payload, typ, domain=None, path=None,
                      timestamp="", max_age=0):
        
        timestamp = str(int(time.time()))

        # create cookie payload
        try:
            _payload = "::".join([payload, timestamp, typ])
        except TypeError:
            _payload = "::".join([payload[0], timestamp, typ])

        content = make_cookie_content(name, _payload, self.sign_key, domain=domain,
                                      path=path, timestamp=timestamp,
                                      enc_key=self.enc_key, max_age=max_age,
                                      sign_alg=self.sign_alg)

        for name, args in content.items():
            cookie[name] = args['value']
            for key, value in args.items():
                if key == 'value':
                    continue
                cookie[name][key] = value

        return cookie
471830
function getValue (key, cookieString, converter = null) {
  let result = createJWPCookie(key, cookieString, converter);

  // if `key` is undefined we want the entire cookie
  return _.isUndefined(key) ? result : result.value;
}
655502
def set_cookie(self, cookie=None):
        """"""
        if cookie:
            self._cookie = cookie.encode()
        else:
            self._cookie = None
1079549
function (str) {
        if (!_.isString(str)) {
            return str;
        }

        var obj = {},
            pairs = str.split(PAIR_SPLIT_REGEX),
            nameval;

        nameval = Cookie.splitParam(pairs.shift()); // The first kvp is the name and value
        obj.key = nameval.key;
        obj.value = nameval.value;

        pairs.forEach(function (pair) {
            var keyval = Cookie.splitParam(pair),
                value = keyval.value,
                keyLower = keyval.key.toLowerCase();

            if (cookieAttributes[keyLower]) {
                obj[cookieAttributes[keyLower]] = value;
            }
            else {
                obj.extensions = obj.extensions || [];
                obj.extensions.push(keyval);
            }
        });
        // Handle the hostOnly flag
        if (!obj.domain) {
            obj.hostOnly = true;
        }
        return obj;
    }
1172365
def sec_to_public_pair(sec, generator=None, strict=True):
    """"""
    byte_count = (generator.p().bit_length() + 7) >> 3 if generator else (len(sec) - 1)
    x = from_bytes_32(sec[1:1 + byte_count])
    sec0 = sec[:1]
    if len(sec) == 1 + byte_count * 2:
        isok = sec0 == b'\4'
        if not strict:
            isok = isok or (sec0 in [b'\6', b'\7'])
        if isok:
            y = from_bytes_32(sec[1+byte_count:1+2*byte_count])
            return (x, y)
    elif len(sec) == 1 + byte_count:
        if not strict or (sec0 in (b'\2', b'\3')):
            is_y_odd = (sec0 != b'\2')
            return generator.points_for_x(x)[is_y_odd]
    raise EncodingError("bad sec encoding for public key")
799530
def from_response(cls, header_data, ignore_bad_cookies=False,
                      ignore_bad_attributes=True):
        ""
        cookies = cls()
        cookies.parse_response(
            header_data,
            ignore_bad_cookies=ignore_bad_cookies,
            ignore_bad_attributes=ignore_bad_attributes)
        return cookies
550278
function (user_id, cookie, passphrase, callback) {
		var packed_user_id = String.fromCharCode(0, 0, 0, 0, user_id >> 24 & 0xFF, user_id >> 16 & 0xFF, user_id >> 8 & 0xFF, user_id & 0xFF);
		var client_nonce = "";
		for (var i = 0; i < 16; ++i) {
			client_nonce += String.fromCharCode(Math.random() * 256);
		}
		var seed = packed_user_id + unescape(encodeURIComponent(passphrase));
		var data = packed_user_id + _server_nonce + client_nonce;
		var d = ecp.mpn_pack(util.hash_string_to_words(seed));
		var z = ecp.mpn_pack(util.hash_string_to_words(data));
		var r = ecp.mpn_new(8), s = ecp.mpn_new(8);
		ecp.ecp_sign(r, s, ecp.secp224k1_p, ecp.secp224k1_a, ecp.secp224k1_G, ecp.secp224k1_n, d, z, 8);
		request({
			method: "Authenticate",
			user_id: user_id,
			cookie: cookie,
			nonce: btoa(client_nonce),
			signature: [ btoa(util.words_to_string(ecp.mpn_unpack(r))), btoa(util.words_to_string(ecp.mpn_unpack(s))) ],
		}, callback);
	}