type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
MethodDeclaration
|
public findServers(callback: ResponseCallback<ApplicationDescription[]>): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public findServers(...args: any[]): any {
if (!this._secureChannel) {
setImmediate(() => {
callback(new Error("Invalid Secure Channel"));
});
return;
}
if (args.length === 1) {
return this.findServers({}, args[0]);
}
const options = args[0] as FindServersRequestLike;
const callback = args[1] as ResponseCallback<ApplicationDescription[]>;
const request = new FindServersRequest({
endpointUrl: options.endpointUrl || this.endpointUrl,
localeIds: options.localeIds || [],
serverUris: options.serverUris || []
});
this.performMessageTransaction(request, (err: Error | null, response?: Response) => {
if (err) {
return callback(err);
}
if (!response || !(response instanceof FindServersResponse)) {
return callback(new Error("Internal Error"));
}
response.servers = response.servers || [];
callback(null, response.servers);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public findServersOnNetwork(options?: FindServersOnNetworkRequestLike): Promise<ServerOnNetwork[]>;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public findServersOnNetwork(callback: ResponseCallback<ServerOnNetwork[]>): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public findServersOnNetwork(
options: FindServersOnNetworkRequestLike, callback: ResponseCallback<ServerOnNetwork[]>): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public findServersOnNetwork(...args: any[]): any {
if (args.length === 1) {
return this.findServersOnNetwork({}, args[0]);
}
const options = args[0] as FindServersOnNetworkRequestOptions;
const callback = args[1] as ResponseCallback<ServerOnNetwork[]>;
if (!this._secureChannel) {
setImmediate(() => {
callback(new Error("Invalid Secure Channel"));
});
return;
}
const request = new FindServersOnNetworkRequest(options);
this.performMessageTransaction(request, (err: Error | null, response?: Response) => {
if (err) {
return callback(err);
}
if (!response || !(response instanceof FindServersOnNetworkResponse)) {
return new Error("Internal Error");
}
response.servers = response.servers || [];
callback(null, response.servers);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public _removeSession(session: ClientSessionImpl) {
const index = this._sessions.indexOf(session);
if (index >= 0) {
const s = this._sessions.splice(index, 1)[0];
assert(s === session);
assert(!_.contains(this._sessions, session));
assert(session._client === this);
session._client = null;
}
assert(!_.contains(this._sessions, session));
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public disconnect(): Promise<void>;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public disconnect(callback: ErrorCallback): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public disconnect(...args: any[]): any {
const callback = args[0];
assert(_.isFunction(callback), "expecting a callback function here");
debugLog("ClientBaseImpl#disconnect", this.endpointUrl);
if (this.isReconnecting) {
debugLog("ClientBaseImpl#disconnect called while reconnection is in progress");
// let's abort the reconnection process
return this._cancel_reconnection((err?: Error) => {
debugLog("ClientBaseImpl#disconnect reconnection has been canceled");
assert(!err, " why would this fail ?");
assert(!this.isReconnecting);
// sessions cannot be cancelled properly and must be discarded.
this.disconnect(callback);
});
}
if (this._sessions.length && !this.keepPendingSessionsOnDisconnect) {
debugLog("warning : disconnection : closing pending sessions");
// disconnect has been called whereas living session exists
// we need to close them first ....
this._close_pending_sessions((/*err*/) => {
this.disconnect(callback);
});
return;
}
if (this._sessions.length) {
// transfer active session to orphan and detach them from channel
_.forEach(this._sessions, (session: ClientSessionImpl) => {
this._removeSession(session);
});
this._sessions = [];
}
assert(this._sessions.length === 0, " attempt to disconnect a client with live sessions ");
OPCUAClientBase.registry.unregister(this);
uninstallPeriodicClockAdjustmement();
if (this._secureChannel) {
let tmpChannel: any = this._secureChannel;
this._secureChannel = null;
tmpChannel.close(() => {
this._secureChannel = tmpChannel;
tmpChannel = null;
this._destroy_secure_channel();
setImmediate(callback);
});
} else {
this.emit("close", null);
setImmediate(callback);
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
// override me !
public _on_connection_reestablished(callback: ErrorCallback) {
callback();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public toString(): string {
let str = "";
str += " defaultSecureTokenLifetime.... " + this.defaultSecureTokenLifetime + "\n";
str += " securityMode.................. " + this.securityMode.toString() + "\n";
str += " securityPolicy................ " + this.securityPolicy.toString() + "\n";
str += " certificate fingerprint....... " + makeSHA1Thumbprint(this.getCertificate()).toString("hex") + "\n";
// this.serverCertificate = options.serverCertificate || null + "\n";
str += " keepSessionAlive.............. " + this.keepSessionAlive + "\n";
str += " bytesRead..................... " + this.bytesRead + "\n";
str += " bytesWritten.................. " + this.bytesWritten + "\n";
str += " transactionsPerformed......... " + this.transactionsPerformed + "\n";
str += " timedOutRequestCount.......... " + this.timedOutRequestCount + "\n";
str += " connectionStrategy." + "\n";
str += " .maxRetry............... " + this.connectionStrategy.maxRetry + "\n";
str += " .initialDelay........... " + this.connectionStrategy.initialDelay + "\n";
str += " .maxDelay............... " + this.connectionStrategy.maxDelay + "\n";
str += " .randomisationFactor.... " + this.connectionStrategy.randomisationFactor + "\n";
str += " keepSessionAlive.............. " + this.keepSessionAlive + "\n";
if (this._secureChannel) {
str += "secureChannel:\n" + this._secureChannel.toString();
}
return str;
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
protected _addSession(session: ClientSessionImpl) {
assert(!session._client || session._client === this);
assert(!_.contains(this._sessions, session), "session already added");
session._client = this;
this._sessions.push(session);
if (this.keepSessionAlive) {
session.startKeepAliveManager();
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
private fetchServerCertificate(endpointUrl: string, callback: (err?: Error) => void): void {
const discoveryUrl = this.discoveryUrl.length > 0 ? this.discoveryUrl : endpointUrl;
debugLog("OPCUAClientImpl : getting serverCertificate");
// we have not been given the serverCertificate but this certificate
// is required as the connection is to be secured.
//
// Let's explore the server endpoint that matches our security settings
// This will give us the missing Certificate as well from the server.
// todo :
// Once we have the certificate, we cannot trust it straight away
// we have to verify that the certificate is valid and not outdated and not revoked.
// if the certificate is self-signed the certificate must appear in the trust certificate
// list.
// if the certificate has been certified by an Certificate Authority we have to
// verify that the certificates in the chain are valid and not revoked.
//
const certificateFile = this.certificateFile || "certificates/client_selfsigned_cert_2048.pem";
const privateKeyFile = this.privateKeyFile || "certificates/client_key_2048.pem";
const applicationName = (this as any).applicationName || "NodeOPCUA-Client";
const params = {
connectionStrategy: this.connectionStrategy,
endpoint_must_exist: false,
securityMode: this.securityMode,
securityPolicy: this.securityPolicy,
applicationName,
certificateFile,
privateKeyFile
};
return __findEndpoint(this, discoveryUrl, params, (err: Error | null, result?: FindEndpointResult) => {
if (err) {
this.emit("connection_failed", err);
return callback(err);
}
if (!result) {
const err1 = new Error("internal error");
this.emit("connection_failed", err1);
return callback(err1);
}
const endpoint = result.selectedEndpoint;
if (!endpoint) {
// no matching end point can be found ...
const err1 = new Error("cannot find endpoint");
this.emit("connection_failed", err1);
return callback(err1);
}
assert(endpoint);
_verify_serverCertificate(endpoint.serverCertificate, (err1?: Error) => {
if (err1) {
this.emit("connection_failed", err1);
return callback(err1);
}
this.serverCertificate = endpoint.serverCertificate;
callback();
});
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
private _acculumate_statistics() {
if (this._secureChannel) {
// keep accumulated statistics
this._byteWritten += this._secureChannel.bytesWritten;
this._byteRead += this._secureChannel.bytesRead;
this._transactionsPerformed += this._secureChannel.transactionsPerformed;
this._timedOutRequestCount += this._secureChannel.timedOutRequestCount;
if (doDebug) {
debugLog("byteWritten = ", this._byteWritten);
debugLog("byteRead = ", this._byteRead);
debugLog("transactions = ", this._transactionsPerformed);
}
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
private _destroy_secure_channel() {
if (this._secureChannel) {
if (doDebug) {
debugLog(" DESTROYING SECURE CHANNEL (isTransactionInProgress ?", this._secureChannel.isTransactionInProgress(), ")");
}
this._acculumate_statistics();
this._secureChannel.dispose();
this._secureChannel.removeAllListeners();
this._secureChannel = null;
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
private _close_pending_sessions(callback: ErrorCallback) {
assert(_.isFunction(callback));
const sessions = _.clone(this._sessions);
async.map(sessions, (session: ClientSessionImpl, next: () => void) => {
assert(session._client === this);
// note: to prevent next to be call twice
let _next_already_call = false;
session.close((err?: Error) => {
if (_next_already_call) {
return;
}
_next_already_call = true;
// We should not bother if we have an error here
// Session may fail to close , if they haven't been activate and forcefully closed by server
// in a attempt to preserve resources in the case of a DDOS attack for instance.
if (err) {
const msg = session.authenticationToken ? session.authenticationToken.toString() : "";
debugLog(" failing to close session " + msg);
}
next();
});
}, (err) => {
// istanbul ignore next
if (this._sessions.length > 0) {
debugLog(this._sessions.map((s: ClientSessionImpl) =>
s.authenticationToken ? s.authenticationToken.toString() : "").join(" "));
}
assert(this._sessions.length === 0, " failed to disconnect exiting sessions ");
callback(err!);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
private _install_secure_channel_event_handlers(secureChannel: ClientSecureChannelLayer) {
assert(this instanceof ClientBaseImpl);
secureChannel.on("send_chunk", (chunk: Buffer) => {
/**
* notify the observer that a message_chunk has been sent
* @event send_chunk
* @param message_chunk
*/
this.emit("send_chunk", chunk);
});
secureChannel.on("receive_chunk", (chunk: Buffer) => {
/**
* notify the observer that a message_chunk has been received
* @event receive_chunk
* @param message_chunk
*/
this.emit("receive_chunk", chunk);
});
secureChannel.on("send_request", (message: Request) => {
/**
* notify the observer that a request has been sent to the server.
* @event send_request
* @param message
*/
this.emit("send_request", message);
});
secureChannel.on("receive_response", (message: Response) => {
/**
* notify the observer that a response has been received from the server.
* @event receive_response
* @param message
*/
this.emit("receive_response", message);
});
secureChannel.on("lifetime_75", (token: SecurityToken) => {
// secureChannel requests a new token
debugLog("SecureChannel Security Token ", token.tokenId, "live time was =", token.revisedLifetime,
" is about to expired , it's time to request a new token");
// forward message to upper level
this.emit("lifetime_75", token, secureChannel);
});
secureChannel.on("security_token_renewed", () => {
// forward message to upper level
this.emit("security_token_renewed", secureChannel);
});
secureChannel.on("close", (err?: Error) => {
debugLog(chalk.yellow.bold(" ClientBaseImpl emitting close"), err);
if (!err || !this.reconnectOnFailure) {
// this is a normal close operation initiated byu
/**
* @event close
* @param error
*/
this.emit("close", err);
setImmediate(() => {
this._destroy_secure_channel();
});
return;
} else {
this.emit("connection_lost");
setImmediate(() => {
debugLog("recreating new secure channel ");
this._recreate_secure_channel((err1?: Error) => {
debugLog("secureChannel#on(close) => _recreate_secure_channel returns ",
err1 ? err1.message : "OK");
if (err1) {
// xx assert(!this._secureChannel);
debugLog("_recreate_secure_channel has failed");
// xx this.emit("close", err1);
return;
} else {
/**
* @event connection_reestablished
* send when the connection is reestablished after a connection break
*/
this.emit("connection_reestablished");
// now delegate to upper class the
if (this._on_connection_reestablished) {
assert(_.isFunction(this._on_connection_reestablished));
this._on_connection_reestablished((err2?: Error) => {
if (err2) {
debugLog("connection_reestablished has failed");
this.disconnect(() => {
// callback(err);
// tslint:disable-next-line: no-console
console.log("Disconnected following reconnection failure", err2.message);
});
}
});
}
}
});
});
}
});
secureChannel.on("timed_out_request", (request: Request) => {
/**
* send when a request has timed out without receiving a response
* @event timed_out_request
* @param request
*/
this.emit("timed_out_request", request);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ClassDeclaration
|
// tslint:disable:no-stateless-class // Grandfathered in
export class TemporaryFile {
static async create(fileName: string): Promise<string> {
let folderName = getRandomHexString(12);
let filePath = path.join(os.tmpdir(), folderName, fileName);
await fse.ensureFile(filePath);
return filePath;
}
}
|
Bhaskers-Blu-Org2/vscode-azurestorage
|
src/utils/temporaryFile.ts
|
TypeScript
|
MethodDeclaration
|
static async create(fileName: string): Promise<string> {
let folderName = getRandomHexString(12);
let filePath = path.join(os.tmpdir(), folderName, fileName);
await fse.ensureFile(filePath);
return filePath;
}
|
Bhaskers-Blu-Org2/vscode-azurestorage
|
src/utils/temporaryFile.ts
|
TypeScript
|
ArrowFunction
|
async () => {
let info = await gateway.info()
console.log('info=====', info)
let session = await gateway.create()
console.dir(session)
let handle = await session.attach('janus.plugin.streaming')
console.dir(handle)
let streams = await handle.request({
request: 'list'
})
console.log(streams)
let streaminfo = await handle.request({
request: 'info',
id: 1
})
console.log(streaminfo)
// create stream
let created = await handle.request({
request: 'create',
type:'rtp',
audio:true,
video:true,
audioport:10006,
audiopt:100,
audiortpmap:'opus/48000/2',
videoport:10008,
videopt:101,
videortpmap:'VP8/90000',
videobufferkf:true,
})
console.log(created.plugindata.data.stream)
}
|
notedit/janus-ts
|
tests/test_janus.ts
|
TypeScript
|
ClassDeclaration
|
export class OptionViewModel {
title: string;
answer: boolean;
}
|
saykat/client-preparations.xyz
|
src/app/ViewModels/option.view.model.ts
|
TypeScript
|
ClassDeclaration
|
/** Provides operations to manage the userFlowAttributes property of the microsoft.graph.identityContainer entity. */
export class IdentityUserFlowAttributeItemRequestBuilder {
/** Path parameters for the request */
private readonly pathParameters: Record<string, unknown>;
/** The request adapter to use to execute the requests. */
private readonly requestAdapter: RequestAdapter;
/** Url template to use to build the URL for the current request builder */
private readonly urlTemplate: string;
/**
* Instantiates a new IdentityUserFlowAttributeItemRequestBuilder and sets the default values.
* @param pathParameters The raw url or the Url template parameters for the request.
* @param requestAdapter The request adapter to use to execute the requests.
*/
public constructor(pathParameters: Record<string, unknown> | string | undefined, requestAdapter: RequestAdapter) {
if(!pathParameters) throw new Error("pathParameters cannot be undefined");
if(!requestAdapter) throw new Error("requestAdapter cannot be undefined");
this.urlTemplate = "{+baseurl}/identity/userFlowAttributes/{identityUserFlowAttribute%2Did}{?%24select,%24expand}";
const urlTplParams = getPathParameters(pathParameters);
this.pathParameters = urlTplParams;
this.requestAdapter = requestAdapter;
};
/**
* Delete navigation property userFlowAttributes for identity
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @returns a RequestInformation
*/
public createDeleteRequestInformation(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderDeleteRequestConfiguration | undefined) : RequestInformation {
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.DELETE;
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
return requestInfo;
};
/**
* Represents entry point for identity userflow attributes.
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @returns a RequestInformation
*/
public createGetRequestInformation(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderGetRequestConfiguration | undefined) : RequestInformation {
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.GET;
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.setQueryStringParametersFromRawObject(requestConfiguration.queryParameters);
requestInfo.addRequestOptions(requestConfiguration.options);
}
return requestInfo;
};
/**
* Update the navigation property userFlowAttributes in identity
* @param body
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @returns a RequestInformation
*/
public createPatchRequestInformation(body: IdentityUserFlowAttribute | undefined, requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderPatchRequestConfiguration | undefined) : RequestInformation {
if(!body) throw new Error("body cannot be undefined");
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.PATCH;
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
requestInfo.setContentFromParsable(this.requestAdapter, "application/json", body);
return requestInfo;
};
/**
* Delete navigation property userFlowAttributes for identity
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @param responseHandler Response handler to use in place of the default response handling provided by the core service
*/
public delete(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderDeleteRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<void> {
const requestInfo = this.createDeleteRequestInformation(
requestConfiguration
);
const errorMapping: Record<string, ParsableFactory<Parsable>> = {
"4XX": createODataErrorFromDiscriminatorValue,
"5XX": createODataErrorFromDiscriminatorValue,
};
return this.requestAdapter?.sendNoResponseContentAsync(requestInfo, responseHandler, errorMapping) ?? Promise.reject(new Error('http core is null'));
};
/**
* Represents entry point for identity userflow attributes.
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @param responseHandler Response handler to use in place of the default response handling provided by the core service
* @returns a Promise of IdentityUserFlowAttribute
*/
public get(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderGetRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<IdentityUserFlowAttribute | undefined> {
const requestInfo = this.createGetRequestInformation(
requestConfiguration
);
const errorMapping: Record<string, ParsableFactory<Parsable>> = {
"4XX": createODataErrorFromDiscriminatorValue,
"5XX": createODataErrorFromDiscriminatorValue,
};
return this.requestAdapter?.sendAsync<IdentityUserFlowAttribute>(requestInfo, createIdentityUserFlowAttributeFromDiscriminatorValue, responseHandler, errorMapping) ?? Promise.reject(new Error('http core is null'));
};
/**
* Update the navigation property userFlowAttributes in identity
* @param body
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @param responseHandler Response handler to use in place of the default response handling provided by the core service
*/
public patch(body: IdentityUserFlowAttribute | undefined, requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderPatchRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<void> {
if(!body) throw new Error("body cannot be undefined");
const requestInfo = this.createPatchRequestInformation(
body, requestConfiguration
);
const errorMapping: Record<string, ParsableFactory<Parsable>> = {
"4XX": createODataErrorFromDiscriminatorValue,
"5XX": createODataErrorFromDiscriminatorValue,
};
return this.requestAdapter?.sendNoResponseContentAsync(requestInfo, responseHandler, errorMapping) ?? Promise.reject(new Error('http core is null'));
};
}
|
microsoftgraph/msgraph-sdk-typescript
|
src/identity/userFlowAttributes/item/identityUserFlowAttributeItemRequestBuilder.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Delete navigation property userFlowAttributes for identity
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @returns a RequestInformation
*/
public createDeleteRequestInformation(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderDeleteRequestConfiguration | undefined) : RequestInformation {
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.DELETE;
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
return requestInfo;
}
|
microsoftgraph/msgraph-sdk-typescript
|
src/identity/userFlowAttributes/item/identityUserFlowAttributeItemRequestBuilder.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Represents entry point for identity userflow attributes.
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @returns a RequestInformation
*/
public createGetRequestInformation(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderGetRequestConfiguration | undefined) : RequestInformation {
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.GET;
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.setQueryStringParametersFromRawObject(requestConfiguration.queryParameters);
requestInfo.addRequestOptions(requestConfiguration.options);
}
return requestInfo;
}
|
microsoftgraph/msgraph-sdk-typescript
|
src/identity/userFlowAttributes/item/identityUserFlowAttributeItemRequestBuilder.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Update the navigation property userFlowAttributes in identity
* @param body
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @returns a RequestInformation
*/
public createPatchRequestInformation(body: IdentityUserFlowAttribute | undefined, requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderPatchRequestConfiguration | undefined) : RequestInformation {
if(!body) throw new Error("body cannot be undefined");
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.PATCH;
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
requestInfo.setContentFromParsable(this.requestAdapter, "application/json", body);
return requestInfo;
}
|
microsoftgraph/msgraph-sdk-typescript
|
src/identity/userFlowAttributes/item/identityUserFlowAttributeItemRequestBuilder.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Delete navigation property userFlowAttributes for identity
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @param responseHandler Response handler to use in place of the default response handling provided by the core service
*/
public delete(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderDeleteRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<void> {
const requestInfo = this.createDeleteRequestInformation(
requestConfiguration
);
const errorMapping: Record<string, ParsableFactory<Parsable>> = {
"4XX": createODataErrorFromDiscriminatorValue,
"5XX": createODataErrorFromDiscriminatorValue,
};
return this.requestAdapter?.sendNoResponseContentAsync(requestInfo, responseHandler, errorMapping) ?? Promise.reject(new Error('http core is null'));
}
|
microsoftgraph/msgraph-sdk-typescript
|
src/identity/userFlowAttributes/item/identityUserFlowAttributeItemRequestBuilder.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Represents entry point for identity userflow attributes.
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @param responseHandler Response handler to use in place of the default response handling provided by the core service
* @returns a Promise of IdentityUserFlowAttribute
*/
public get(requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderGetRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<IdentityUserFlowAttribute | undefined> {
const requestInfo = this.createGetRequestInformation(
requestConfiguration
);
const errorMapping: Record<string, ParsableFactory<Parsable>> = {
"4XX": createODataErrorFromDiscriminatorValue,
"5XX": createODataErrorFromDiscriminatorValue,
};
return this.requestAdapter?.sendAsync<IdentityUserFlowAttribute>(requestInfo, createIdentityUserFlowAttributeFromDiscriminatorValue, responseHandler, errorMapping) ?? Promise.reject(new Error('http core is null'));
}
|
microsoftgraph/msgraph-sdk-typescript
|
src/identity/userFlowAttributes/item/identityUserFlowAttributeItemRequestBuilder.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Update the navigation property userFlowAttributes in identity
* @param body
* @param requestConfiguration Configuration for the request such as headers, query parameters, and middleware options.
* @param responseHandler Response handler to use in place of the default response handling provided by the core service
*/
public patch(body: IdentityUserFlowAttribute | undefined, requestConfiguration?: IdentityUserFlowAttributeItemRequestBuilderPatchRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<void> {
if(!body) throw new Error("body cannot be undefined");
const requestInfo = this.createPatchRequestInformation(
body, requestConfiguration
);
const errorMapping: Record<string, ParsableFactory<Parsable>> = {
"4XX": createODataErrorFromDiscriminatorValue,
"5XX": createODataErrorFromDiscriminatorValue,
};
return this.requestAdapter?.sendNoResponseContentAsync(requestInfo, responseHandler, errorMapping) ?? Promise.reject(new Error('http core is null'));
}
|
microsoftgraph/msgraph-sdk-typescript
|
src/identity/userFlowAttributes/item/identityUserFlowAttributeItemRequestBuilder.ts
|
TypeScript
|
ArrowFunction
|
(theme: Theme) => ({
...styled(theme),
expired: {
color: theme.color.red
},
root: {
display: 'flex',
[theme.breakpoints.up('md')]: {
justifyContent: 'space-between'
}
},
label: {
[theme.breakpoints.only('sm')]: {
minWidth: 150
}
},
result: {
marginLeft: theme.spacing(1),
[theme.breakpoints.up('md')]: {
textAlign: 'right'
}
}
})
|
DevDW/manager
|
packages/manager/src/features/Billing/BillingPanels/SummaryPanel/PanelCards/CreditCard.tsx
|
TypeScript
|
ArrowFunction
|
props => {
const { expiry, lastFour } = props;
const classes = useStyles();
return (
<>
<div className={`${classes.section} ${classes.root}`}
|
DevDW/manager
|
packages/manager/src/features/Billing/BillingPanels/SummaryPanel/PanelCards/CreditCard.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface Props {
lastFour?: string;
expiry?: string;
}
|
DevDW/manager
|
packages/manager/src/features/Billing/BillingPanels/SummaryPanel/PanelCards/CreditCard.tsx
|
TypeScript
|
TypeAliasDeclaration
|
export type CombinedProps = Props;
|
DevDW/manager
|
packages/manager/src/features/Billing/BillingPanels/SummaryPanel/PanelCards/CreditCard.tsx
|
TypeScript
|
FunctionDeclaration
|
export async function testFunc(): Promise<MongoClient> {
const testClient: MongoClient = await MongoClient.connect(connectionString);
return testClient;
}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
FunctionDeclaration
|
// Streams
export function gridTest(bucket: GridFSBucket): void {
const openUploadStream = bucket.openUploadStream('file.dat');
openUploadStream.on('close', () => {});
openUploadStream.on('end', () => {});
expectType<Promise<void>>(openUploadStream.abort()); // $ExpectType void
expectType<void>(
openUploadStream.abort(() => {
openUploadStream.removeAllListeners();
})
);
openUploadStream.abort(error => {
error; // $ExpectType MongoError
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
openUploadStream.abort((error, result) => {});
}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
ArrowFunction
|
(err, client?: MongoClient) => {
if (err || !client) throw err;
const db = client.db('test');
db.collection('test_crud');
// Let's close the db
client.close();
}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
ArrowFunction
|
err => {
if (err instanceof MongoError) {
expectType<boolean>(err.hasErrorLabel('label'));
}
}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
ArrowFunction
|
() => {
openUploadStream.removeAllListeners();
}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
ArrowFunction
|
error => {
error; // $ExpectType MongoError
}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
ArrowFunction
|
(error, result) => {}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
MethodDeclaration
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
checkServerIdentity(host, cert) {
return undefined;
}
|
ImRodry/node-mongodb-native
|
test/types/community/client.test-d.ts
|
TypeScript
|
ArrowFunction
|
(response) => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('token', response.token);
const tokenPayload = JSON.parse(atob(response.token.split('.')[1]));
const user = {name: tokenPayload.name, id: tokenPayload.sub};
this.saveUserToStorage(user);
this.currentUserSubject.next(user);
return user;
}
|
ccims/ccims-frontend
|
src/app/auth/authentication.service.ts
|
TypeScript
|
ClassDeclaration
|
/**
* Responsible for saving user name, id and jwt token in localstorage
* and exposing the name and id through currentUserSubject
*/
@Injectable({providedIn: 'root'})
export class AuthenticationService {
readonly userStorageKey = 'currentUser';
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient, private router: Router) {
this.currentUserSubject = new BehaviorSubject<User>(this.fetchUserFromStorage());
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
fetchUserFromStorage(): User {
return JSON.parse(localStorage.getItem(this.userStorageKey));
}
saveUserToStorage(user: User): void {
localStorage.setItem(this.userStorageKey, JSON.stringify(user));
}
/**
* If login is sucessfull save the user name, id and jwt token to local storage and expose the name and id
* through currentUserSubject. If the login fails the returned observable errors.
* @param username provided by user to LoginComponent
* @param password provided by user to LoginComponent
* @returns the logged in user, errors if login is not successful
*/
login(username: string, password: string): Observable<User> {
return this.http.post<any>(environment.loginUrl, {username, password}).pipe(
map((response) => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('token', response.token);
const tokenPayload = JSON.parse(atob(response.token.split('.')[1]));
const user = {name: tokenPayload.name, id: tokenPayload.sub};
this.saveUserToStorage(user);
this.currentUserSubject.next(user);
return user;
})
);
}
/**
* remove user from local storage and set subject holding the current user to null
*/
logout(): void {
localStorage.removeItem('currentUser');
localStorage.removeItem('token');
this.router.navigate(['login']);
this.currentUserSubject.next(null);
}
}
|
ccims/ccims-frontend
|
src/app/auth/authentication.service.ts
|
TypeScript
|
InterfaceDeclaration
|
interface User {
name: string;
id: string;
}
|
ccims/ccims-frontend
|
src/app/auth/authentication.service.ts
|
TypeScript
|
MethodDeclaration
|
fetchUserFromStorage(): User {
return JSON.parse(localStorage.getItem(this.userStorageKey));
}
|
ccims/ccims-frontend
|
src/app/auth/authentication.service.ts
|
TypeScript
|
MethodDeclaration
|
saveUserToStorage(user: User): void {
localStorage.setItem(this.userStorageKey, JSON.stringify(user));
}
|
ccims/ccims-frontend
|
src/app/auth/authentication.service.ts
|
TypeScript
|
MethodDeclaration
|
/**
* If login is sucessfull save the user name, id and jwt token to local storage and expose the name and id
* through currentUserSubject. If the login fails the returned observable errors.
* @param username provided by user to LoginComponent
* @param password provided by user to LoginComponent
* @returns the logged in user, errors if login is not successful
*/
login(username: string, password: string): Observable<User> {
return this.http.post<any>(environment.loginUrl, {username, password}).pipe(
map((response) => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('token', response.token);
const tokenPayload = JSON.parse(atob(response.token.split('.')[1]));
const user = {name: tokenPayload.name, id: tokenPayload.sub};
this.saveUserToStorage(user);
this.currentUserSubject.next(user);
return user;
})
);
}
|
ccims/ccims-frontend
|
src/app/auth/authentication.service.ts
|
TypeScript
|
MethodDeclaration
|
/**
* remove user from local storage and set subject holding the current user to null
*/
logout(): void {
localStorage.removeItem('currentUser');
localStorage.removeItem('token');
this.router.navigate(['login']);
this.currentUserSubject.next(null);
}
|
ccims/ccims-frontend
|
src/app/auth/authentication.service.ts
|
TypeScript
|
InterfaceDeclaration
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export interface AddressDTO {
AddressId: string;
City: string;
Country: string;
CountryRegion: string;
District: string;
FirstName: string;
LastName: string;
PhoneNumber: string;
State: string;
Street1: string;
Street2: string;
Street3: string;
Type: string;
ZipCode: string;
}
|
microsoft/Dynamics-365-Fraud-Protection-ManualReview
|
frontend/src/data-services/api-services/models/address-dto.ts
|
TypeScript
|
FunctionDeclaration
|
function PageHeader(){
function handleGoBack(){
}
return (
<View style={styles.container}>
<View style={styles.topBar}>
<BorderlessButton onPress={handleGoBack}>
<Image source={}></Image>
</BorderlessButton>
</View>
</View>
)
}
|
gutoisa/Proffy
|
mobile/.history/src/components/PageHeader/index_20200808170713.tsx
|
TypeScript
|
FunctionDeclaration
|
function handleGoBack(){
}
|
gutoisa/Proffy
|
mobile/.history/src/components/PageHeader/index_20200808170713.tsx
|
TypeScript
|
ArrowFunction
|
() => {
test('when there is only one duplicated url', () => {
const content = {
pages: [
{
meta: {
url: '/something/cool'
}
},
{
meta: {
url: '/something/cool'
}
}
]
};
uniquefyUrls(content as Context);
expect(content.pages.map((page) => page.meta.url)).toEqual([
'/something/cool',
'/something/cool-1'
]);
});
test('when there are more then one duplicated url', () => {
const content = {
pages: [
{
meta: {
url: '/something/cool'
}
},
{
meta: {
url: '/something/cool'
}
},
{
meta: {
url: '/something/cool'
}
}
]
};
uniquefyUrls(content as Context);
expect(content.pages.map((page) => page.meta.url)).toEqual([
'/something/cool',
'/something/cool-1',
'/something/cool-2'
]);
});
test('when there are duplicated index pages', () => {
const content = {
pages: [
{
meta: {
url: '/something/blog/'
}
},
{
meta: {
url: '/something/blog/'
}
}
]
};
uniquefyUrls(content as Context);
expect(content.pages.map((page) => page.meta.url)).toEqual([
'/something/blog/',
'/something/blog/index-1'
]);
});
}
|
jamiebuilds/docfy
|
packages/@docfy/core/tests/uniquefy-urls.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
const content = {
pages: [
{
meta: {
url: '/something/cool'
}
},
{
meta: {
url: '/something/cool'
}
}
]
};
uniquefyUrls(content as Context);
expect(content.pages.map((page) => page.meta.url)).toEqual([
'/something/cool',
'/something/cool-1'
]);
}
|
jamiebuilds/docfy
|
packages/@docfy/core/tests/uniquefy-urls.test.ts
|
TypeScript
|
ArrowFunction
|
(page) => page.meta.url
|
jamiebuilds/docfy
|
packages/@docfy/core/tests/uniquefy-urls.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
const content = {
pages: [
{
meta: {
url: '/something/cool'
}
},
{
meta: {
url: '/something/cool'
}
},
{
meta: {
url: '/something/cool'
}
}
]
};
uniquefyUrls(content as Context);
expect(content.pages.map((page) => page.meta.url)).toEqual([
'/something/cool',
'/something/cool-1',
'/something/cool-2'
]);
}
|
jamiebuilds/docfy
|
packages/@docfy/core/tests/uniquefy-urls.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
const content = {
pages: [
{
meta: {
url: '/something/blog/'
}
},
{
meta: {
url: '/something/blog/'
}
}
]
};
uniquefyUrls(content as Context);
expect(content.pages.map((page) => page.meta.url)).toEqual([
'/something/blog/',
'/something/blog/index-1'
]);
}
|
jamiebuilds/docfy
|
packages/@docfy/core/tests/uniquefy-urls.test.ts
|
TypeScript
|
ArrowFunction
|
({ children })=>{
const [logedIn, setLoggedIn] = useState(false)
const [userDetail, setUserDetail] = useState({})
return (
<p></p>
)
}
|
infsolution/invit
|
src/utils/authProvider.tsx
|
TypeScript
|
ArrowFunction
|
(e) => !e.startsWith('/~/')
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
const eachGroup: Path[] = [];
eachGroup.push(e);
if (this.props.associations) {
let name = e;
if (e in this.props.associations) {
name =
this.props.associations[e].metadata.title !== ''
? this.props.associations[e].metadata.title
: e;
}
eachGroup.push(name);
}
return Array.from(eachGroup);
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(group, path) => {
if (group.members.size > 0) {
const groupEntries = group.members.values();
for (const member of groupEntries) {
peerSet.add(member);
}
}
const groupContacts = this.props.contacts[path];
if (groupContacts) {
const groupEntries = group.members.values();
for (const member of groupEntries) {
if (groupContacts[member]) {
if (contacts.has(member)) {
contacts
.get(member)
.push(groupContacts[member].nickname);
} else {
contacts.set(member, [
groupContacts[member].nickname,
]);
}
}
}
}
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
return (
e[0].includes(searchTerm) || e[1].toLowerCase().includes(searchTerm)
);
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
return (
e.includes(searchTerm) && !props.invites.ships.includes(e)
);
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
return e.toLowerCase().includes(searchTerm);
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(s) => s === searchTerm
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
([path]) => path === selected
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(ship) => ship === selected
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
([, name]) =>
name
.toLowerCase()
.split(' ')
.some((s) => s.startsWith(searchTerm))
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(s) => s.startsWith(searchTerm)
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(a, b) => a[1].length - b[1].length
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
e.preventDefault();
e.stopPropagation();
this.nextSelection();
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
e.preventDefault();
e.stopPropagation();
this.nextSelection(true);
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
e.preventDefault();
e.stopPropagation();
const { selected } = this.state;
if (selected && selected.startsWith('/')) {
this.addGroup(selected);
} else if (selected) {
this.addShip(selected);
}
this.setState({ selected: null });
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
return e !== ship;
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(group) => {
return (
<li
key={group[0]}
className={
'list white-d f8 pv2 ph3 pointer' +
' hover-bg-gray4 hover-bg-gray1-d ' +
(group[1] ? 'inter' : 'mono') +
(group[0] === state.selected ? ' bg-gray1-d bg-gray4' : '')
}
onClick={()
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(ship) => {
const nicknames = (this.state.contacts.get(ship) || [])
.filter((e) => {
return !(e === '');
})
.join(', ');
return (
<li
key={ship}
className={
'list mono white-d f8 pv1 ph3 pointer' +
' hover-bg-gray4 hover-bg-gray1-d relative' +
(ship === state.selected ? ' bg-gray1-d bg-gray4' : '')
}
onClick={(e) => this.addShip(ship)}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(e) => {
return !(e === '');
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(group) => {
return (
<span
key={group[0]}
className={
'f9 mono black pa2 bg-gray5 bg-gray1-d' +
' ba b--gray4 b--gray2-d white-d dib mr2 mt2 c-default'
}
>
{group}
<span
className='white-d ml3 mono pointer'
onClick={(e)
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
(ship) => {
return (
<span
key={ship}
className={
'f9 mono black pa2 bg-gray5 bg-gray1-d' +
' ba b--gray4 b--gray2-d white-d dib mr2 mt2 c-default'
}
>
{'~' + ship}
<span
className='white-d ml3 mono pointer'
onClick={(e)
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
InterfaceDeclaration
|
export interface Invites {
ships: PatpNoSig[];
groups: string[][];
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface InviteSearchProps {
groups: Groups;
contacts: Rolodex;
groupResults: boolean;
shipResults: boolean;
invites: Invites;
setInvite: (inv: Invites) => void;
disabled?: boolean;
associations?: Associations;
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface InviteSearchState {
groups: string[][];
peers: PatpNoSig[];
contacts: Map<PatpNoSig, string[]>;
searchValue: string;
searchResults: Invites;
selected: PatpNoSig | Path | null;
inviteError: boolean;
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
componentDidMount() {
this.peerUpdate();
this.bindShortcuts();
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
componentDidUpdate(prevProps) {
if (prevProps !== this.props) {
this.peerUpdate();
}
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
peerUpdate() {
const groups = Array.from(Object.keys(this.props.contacts))
.filter((e) => !e.startsWith('/~/'))
.map((e) => {
const eachGroup: Path[] = [];
eachGroup.push(e);
if (this.props.associations) {
let name = e;
if (e in this.props.associations) {
name =
this.props.associations[e].metadata.title !== ''
? this.props.associations[e].metadata.title
: e;
}
eachGroup.push(name);
}
return Array.from(eachGroup);
});
let peers: PatpNoSig[] = [];
const peerSet = new Set<PatpNoSig>();
const contacts = new Map();
_.map(this.props.groups, (group, path) => {
if (group.members.size > 0) {
const groupEntries = group.members.values();
for (const member of groupEntries) {
peerSet.add(member);
}
}
const groupContacts = this.props.contacts[path];
if (groupContacts) {
const groupEntries = group.members.values();
for (const member of groupEntries) {
if (groupContacts[member]) {
if (contacts.has(member)) {
contacts
.get(member)
.push(groupContacts[member].nickname);
} else {
contacts.set(member, [
groupContacts[member].nickname,
]);
}
}
}
}
});
peers = Array.from(peerSet);
this.setState({ groups: groups, peers: peers, contacts: contacts });
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
search(event) {
const searchTerm = event.target.value.toLowerCase().replace('~', '');
const { state, props } = this;
this.setState({ searchValue: event.target.value });
if (searchTerm.length < 1) {
this.setState({ searchResults: { groups: [], ships: [] } });
}
if (searchTerm.length > 0) {
if (state.inviteError === true) {
this.setState({ inviteError: false });
}
let groupMatches = !props.groupResults ? [] :
state.groups.filter((e) => {
return (
e[0].includes(searchTerm) || e[1].toLowerCase().includes(searchTerm)
);
});
let shipMatches = !props.shipResults ? [] :
state.peers.filter((e) => {
return (
e.includes(searchTerm) && !props.invites.ships.includes(e)
);
});
for (const contact of state.contacts.keys()) {
const thisContact = state.contacts.get(contact) || [];
const match = thisContact.filter((e) => {
return e.toLowerCase().includes(searchTerm);
});
if (match.length > 0) {
if (!(contact in shipMatches)) {
shipMatches.push(contact);
}
}
}
let isValid = true;
if (!urbitOb.isValidPatp('~' + searchTerm)) {
isValid = false;
}
if (props.shipResults && isValid && shipMatches.findIndex((s) => s === searchTerm) < 0) {
shipMatches.unshift(searchTerm);
}
const { selected } = state;
const groupIdx = groupMatches.findIndex(([path]) => path === selected);
const shipIdx = shipMatches.findIndex((ship) => ship === selected);
const staleSelection = groupIdx < 0 && shipIdx < 0;
if (!selected || staleSelection) {
const newSelection = _.get(groupMatches, '[0][0]') || shipMatches[0];
this.setState({ selected: newSelection });
}
if (searchTerm.length < 3) {
groupMatches = groupMatches
.filter(([, name]) =>
name
.toLowerCase()
.split(' ')
.some((s) => s.startsWith(searchTerm))
)
.sort((a, b) => a[1].length - b[1].length);
shipMatches = shipMatches.slice(0, 3);
}
this.setState({
searchResults: { groups: groupMatches, ships: shipMatches },
});
}
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
bindShortcuts() {
const mousetrap = Mousetrap(this.textarea.current);
mousetrap.bind(['down', 'tab'], (e) => {
e.preventDefault();
e.stopPropagation();
this.nextSelection();
});
mousetrap.bind(['up', 'shift+tab'], (e) => {
e.preventDefault();
e.stopPropagation();
this.nextSelection(true);
});
mousetrap.bind('enter', (e) => {
e.preventDefault();
e.stopPropagation();
const { selected } = this.state;
if (selected && selected.startsWith('/')) {
this.addGroup(selected);
} else if (selected) {
this.addShip(selected);
}
this.setState({ selected: null });
});
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
nextSelection(backward = false) {
const { selected, searchResults } = this.state;
const { ships, groups } = searchResults;
if (!selected) {
return;
}
let groupIdx = groups.findIndex(([path]) => path === selected);
let shipIdx = ships.findIndex((ship) => ship === selected);
if (groupIdx >= 0) {
backward ? groupIdx-- : groupIdx++;
let selected = _.get(groups, [groupIdx, 0]);
if (groupIdx === groups.length) {
selected = ships.length === 0 ? groups[0][0] : ships[0];
}
if (groupIdx < 0) {
selected =
ships.length === 0
? groups[groups.length - 1][0]
: ships[ships.length - 1];
}
this.setState({ selected });
return;
}
if (shipIdx >= 0) {
backward ? shipIdx-- : shipIdx++;
let selected = ships[shipIdx];
if (shipIdx === ships.length) {
selected = groups.length === 0 ? ships[0] : groups[0][0];
}
if (shipIdx < 0) {
selected =
groups.length === 0
? ships[ships.length - 1]
: groups[groups.length - 1][0];
}
this.setState({ selected });
}
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
deleteGroup() {
const { ships } = this.props.invites;
this.setState({
searchValue: '',
searchResults: { groups: [], ships: [] },
});
this.props.setInvite({ groups: [], ships: ships });
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
deleteShip(ship) {
let { groups, ships } = this.props.invites;
this.setState({
searchValue: '',
searchResults: { groups: [], ships: [] },
});
ships = ships.filter((e) => {
return e !== ship;
});
this.props.setInvite({ groups: groups, ships: ships });
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
addGroup(group) {
this.setState({
searchValue: '',
searchResults: { groups: [], ships: [] },
});
this.props.setInvite({ groups: [group], ships: [] });
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
addShip(ship) {
const { groups, ships } = this.props.invites;
this.setState({
searchValue: '',
searchResults: { groups: [], ships: [] },
});
if (!ships.includes(ship)) {
ships.push(ship);
}
if (groups.length > 0) {
return false;
}
this.props.setInvite({ groups: groups, ships: ships });
return true;
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
submitShipToAdd(ship) {
const searchTerm = ship.toLowerCase().replace('~', '').trim();
let isValid = true;
if (!urbitOb.isValidPatp('~' + searchTerm)) {
isValid = false;
}
if (!isValid) {
this.setState({ inviteError: true, searchValue: '' });
} else if (isValid) {
this.addShip(searchTerm);
this.setState({ searchValue: '' });
}
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
MethodDeclaration
|
render() {
const { props, state } = this;
let searchDisabled = props.disabled;
if (props.invites.groups) {
if (props.invites.groups.length > 0) {
searchDisabled = true;
}
}
let participants = <div />;
let searchResults = <div />;
let placeholder = '';
if (props.shipResults) {
placeholder = 'ships';
}
if (props.groupResults) {
if (placeholder.length > 0) {
placeholder = placeholder + ' or ';
}
placeholder = placeholder + 'existing groups';
}
placeholder = 'Search for ' + placeholder;
let invErrElem = <span />;
if (state.inviteError) {
invErrElem = (
<span className='f9 inter red2 db pt2'>
Invited ships must be validly formatted ship names.
</span>
);
}
if (
state.searchResults.groups.length > 0 ||
state.searchResults.ships.length > 0
) {
const groupHeader =
state.searchResults.groups.length > 0 ? (
<p className='f9 gray2 ph3 pb2'>Groups</p>
) : (
''
);
const shipHeader =
state.searchResults.ships.length > 0 ? (
<p className='f9 gray2 pv2 ph3'>Ships</p>
) : (
''
);
const groupResults = state.searchResults.groups.map((group) => {
return (
<li
key={group[0]}
className={
'list white-d f8 pv2 ph3 pointer' +
' hover-bg-gray4 hover-bg-gray1-d ' +
(group[1] ? 'inter' : 'mono') +
(group[0] === state.selected ? ' bg-gray1-d bg-gray4' : '')
}
onClick={() => this.addGroup(group[0])}
>
<span className='mix-blend-diff white'>
{group[1] ? group[1] : group[0]}
</span>
</li>
);
}
|
ejdiv/urbit
|
pkg/interface/src/components/InviteSearch.tsx
|
TypeScript
|
ArrowFunction
|
() => {
let wrapper: NgxTestWrapper<ElementWrapperComponent>;
beforeEach(async() => {
wrapper = await mount({
component: ElementWrapperComponent,
schemas: [ NO_ERRORS_SCHEMA ],
propsData: {
element: document.createElement('div'),
}
});
});
it('should create', () => {
expect(wrapper.componentInstance).toBeTruthy();
});
}
|
Migushthe2nd/altair
|
packages/altair-app/src/app/modules/altair/components/element-wrapper/element-wrapper.component.spec.ts
|
TypeScript
|
ArrowFunction
|
async() => {
wrapper = await mount({
component: ElementWrapperComponent,
schemas: [ NO_ERRORS_SCHEMA ],
propsData: {
element: document.createElement('div'),
}
});
}
|
Migushthe2nd/altair
|
packages/altair-app/src/app/modules/altair/components/element-wrapper/element-wrapper.component.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
expect(wrapper.componentInstance).toBeTruthy();
}
|
Migushthe2nd/altair
|
packages/altair-app/src/app/modules/altair/components/element-wrapper/element-wrapper.component.spec.ts
|
TypeScript
|
ArrowFunction
|
(_, k) => k
|
JoelLefkowitz/calculator
|
app/src/utils/strings.ts
|
TypeScript
|
ArrowFunction
|
(x: string): boolean =>
// typeof x === "string" && x.length === 1 && digits.includes(parseInt(x, 10));
typeof x === "string" && x.length === 1 && digits.includes(parseInt(x, 10))
|
JoelLefkowitz/calculator
|
app/src/utils/strings.ts
|
TypeScript
|
ArrowFunction
|
(x: string): boolean =>
typeof x === "string" &&
all([
all(x.split("").map((i) => i == "." || digits.includes(parseInt(i, 10)))),
allIndicesOf(x.split(""), ".").length <= 1,
])
|
JoelLefkowitz/calculator
|
app/src/utils/strings.ts
|
TypeScript
|
ArrowFunction
|
(i) => i == "." || digits.includes(parseInt(i, 10))
|
JoelLefkowitz/calculator
|
app/src/utils/strings.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.