type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
ArrowFunction |
() => import("components/system/Files/FileEntry/RenameBox") | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
(
name: string,
fontSize: string,
fontFamily: string,
maxWidth: number
): string => {
const nonBreakingName = name.replace(/-/g, NON_BREAKING_HYPHEN);
const { lines } = getTextWrapData(
nonBreakingName,
fontSize,
fontFamily,
maxWidth
);
if (lines.length > 2) {
const text = !name.includes(" ") ? lines[0] : lines.slice(0, 2).join("");
return `${text.slice(0, -3)}...`;
}
return nonBreakingName;
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
(iconEntry) => iconEntry !== SHORTCUT_ICON | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
(subIcon) => subIcon !== icon | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
async (fileDropName, data) => {
if (!focusedEntries.includes(fileName)) {
const uniqueName = await createPath(fileDropName, directory, data);
if (uniqueName) updateFolder(directory, uniqueName);
}
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
() =>
buttonRef.current?.parentElement?.classList.remove("focus-within") | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
() =>
buttonRef.current?.parentElement?.classList.add("focus-within") | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
() =>
truncateName(
name,
sizes.fileEntry.fontSize,
formats.systemFont,
sizes.fileEntry[
listView ? "maxListTextDisplayWidth" : "maxIconTextDisplayWidth"
]
) | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
async (): Promise<void> => {
if (!isLoadingFileManager && !isIconCached.current) {
if (icon.startsWith("blob:")) {
isIconCached.current = true;
const cachedIconPath = join(ICON_CACHE, `${path}.cache`);
if (
urlExt !== ".ico" &&
!url.startsWith(ICON_PATH) &&
!url.startsWith(USER_ICON_PATH) &&
!(await exists(cachedIconPath)) &&
iconRef.current instanceof HTMLImageElement
) {
const cacheIcon = async (): Promise<void> => {
if (iconRef.current instanceof HTMLImageElement) {
const htmlToImage = await import("html-to-image");
const generatedIcon = await htmlToImage.toPng(iconRef.current);
cacheQueue.push(async () => {
const baseCachedPath = dirname(cachedIconPath);
await mkdirRecursive(baseCachedPath);
await writeFile(
cachedIconPath,
Buffer.from(
generatedIcon.replace("data:image/png;base64,", ""),
"base64"
),
true
);
updateFolder(baseCachedPath, cachedIconPath);
cacheQueue.shift();
await cacheQueue[0]?.();
});
if (cacheQueue.length === 1) await cacheQueue[0]();
}
};
if (iconRef.current.complete) cacheIcon();
else iconRef.current.addEventListener("load", cacheIcon);
}
} else if (getIcon) {
const cachedIconPath = join(ICON_CACHE, `${path}.cache`);
if (await exists(cachedIconPath)) {
isIconCached.current = true;
const cachedIconData = await readFile(cachedIconPath);
setInfo((info) => ({ ...info, icon: bufferToUrl(cachedIconData) }));
} else if (!isDynamicIconLoaded.current) {
isDynamicIconLoaded.current = true;
getIcon();
}
}
}
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
async (): Promise<void> => {
if (iconRef.current instanceof HTMLImageElement) {
const htmlToImage = await import("html-to-image");
const generatedIcon = await htmlToImage.toPng(iconRef.current);
cacheQueue.push(async () => {
const baseCachedPath = dirname(cachedIconPath);
await mkdirRecursive(baseCachedPath);
await writeFile(
cachedIconPath,
Buffer.from(
generatedIcon.replace("data:image/png;base64,", ""),
"base64"
),
true
);
updateFolder(baseCachedPath, cachedIconPath);
cacheQueue.shift();
await cacheQueue[0]?.();
});
if (cacheQueue.length === 1) await cacheQueue[0]();
}
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
async () => {
const baseCachedPath = dirname(cachedIconPath);
await mkdirRecursive(baseCachedPath);
await writeFile(
cachedIconPath,
Buffer.from(
generatedIcon.replace("data:image/png;base64,", ""),
"base64"
),
true
);
updateFolder(baseCachedPath, cachedIconPath);
cacheQueue.shift();
await cacheQueue[0]?.();
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
(info) => ({ ...info, icon: bufferToUrl(cachedIconData) }) | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
(): string => {
if (stats.isDirectory() && !MOUNTABLE_EXTENSIONS.has(extension)) {
return "";
}
if (isShortcut) {
if (comment) return comment;
if (url) {
if (url.startsWith("http:") || url.startsWith("https:")) return url;
return `Location: ${basename(url, extname(url))} (${dirname(url)})`;
}
return "";
}
const type =
extensions[extension as ExtensionType]?.type ||
`${extension.toUpperCase().replace(".", "")} File`;
const { size: sizeInBytes } = stats;
const modifiedTime = getModifiedTime(path, stats);
const size = getFormattedSize(sizeInBytes);
const toolTip = `Type: ${type}\nSize: ${size}`;
const date = new Date(modifiedTime).toISOString().slice(0, 10);
const time = new Intl.DateTimeFormat(
DEFAULT_LOCALE,
formats.dateModified
).format(modifiedTime);
const dateModified = `${date} ${time}`;
return `${toolTip}\nDate modified: ${dateModified}`;
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
() => {
updateIcon();
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
() => {
if (buttonRef.current) {
const inFocusedEntries = focusedEntries.includes(fileName);
const inFocusing = focusing.includes(fileName);
const isFocused = inFocusedEntries || inFocusing;
if (inFocusedEntries && inFocusing) {
focusing.splice(focusing.indexOf(fileName), 1);
}
if (selectionRect && fileManagerRef.current) {
const selected = isSelectionIntersecting(
buttonRef.current.getBoundingClientRect(),
fileManagerRef.current.getBoundingClientRect(),
selectionRect,
fileManagerRef.current.scrollTop
);
if (selected && !isFocused) {
focusing.push(fileName);
focusEntry(fileName);
buttonRef.current.focus(PREVENT_SCROLL);
} else if (!selected && isFocused) {
blurEntry(fileName);
}
} else if (
isFocused &&
focusedEntries.length === 1 &&
!buttonRef.current.contains(document.activeElement)
) {
blurEntry();
focusEntry(fileName);
buttonRef.current.focus(PREVENT_SCROLL);
}
}
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
() => {
if (
openInFileExplorer &&
fileManagerId &&
!MOUNTABLE_EXTENSIONS.has(urlExt)
) {
changeUrl(fileManagerId, url);
blurEntry();
} else if (openInFileExplorer && listView) {
setShowInFileManager((currentState) => !currentState);
} else {
openFile(pid, !isDynamicIcon ? icon : undefined);
}
} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
(currentState) => !currentState | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
(entryIcon) => (
<Icon
key={entryIcon} | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
TypeAliasDeclaration |
type FileEntryProps = {
fileActions: FileActions;
fileManagerId?: string;
fileManagerRef: React.MutableRefObject<HTMLOListElement | null>;
focusedEntries: string[];
focusFunctions: FocusEntryFunctions;
hideShortcutIcon?: boolean;
isLoadingFileManager: boolean;
name: string;
path: string;
readOnly?: boolean;
renaming: boolean;
selectionRect?: SelectionRect;
setRenaming: React.Dispatch<React.SetStateAction<string>>;
stats: FileStat;
useNewFolderIcon?: boolean;
view: FileManagerViewNames;
}; | alphabreacher/wagmi-OS | components/system/Files/FileEntry/index.tsx | TypeScript |
ArrowFunction |
async (uiState: UiState, holderState: HolderState): Promise<FhirConnection> => {
const state = base64url.encode(crypto.randomBytes(32));
const redirect_uri = window.location.origin + window.location.pathname + 'authorized.html';
const smartConfig = (await axios.get(uiState.fhirClient.server + '/.well-known/smart-configuration')).data;
const authorize = smartConfig.authorization_endpoint;
const token = smartConfig.token_endpoint;
const authzWindow = window.open(authorize + '?' + qs.stringify({
scope: uiState.fhirClient.scope,
state,
client_id: uiState.fhirClient.client_id,
response_type: 'code',
redirect_uri,
aud: uiState.fhirClient.server
}), '_blank');
const code: string = await new Promise((resolve) => {
window.addEventListener("message", function onAuth({ data, source, origin }) {
if (origin !== window.location.origin)
return;
if (source !== authzWindow)
return;
const dataParsed = qs.parse(data);
if (dataParsed.state !== state)
return;
window.removeEventListener("message", onAuth);
authzWindow.close();
resolve(dataParsed.code as string);
});
});
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${uiState.fhirClient.client_id}:${uiState.fhirClient.client_secret}`).toString("base64")}`
};
const accessTokenResponse = (await axios.post(token, qs.stringify({
grant_type: "authorization_code",
code,
redirect_uri
}), { headers })).data;
const newSmartState: SmartState = { ...accessTokenResponse };
return {
newSmartState,
};
} | Muflhi01/health-cards-tests | src/FhirConnector.ts | TypeScript |
ArrowFunction |
(resolve) => {
window.addEventListener("message", function onAuth({ data, source, origin }) {
if (origin !== window.location.origin)
return;
if (source !== authzWindow)
return;
const dataParsed = qs.parse(data);
if (dataParsed.state !== state)
return;
window.removeEventListener("message", onAuth);
authzWindow.close();
resolve(dataParsed.code as string);
});
} | Muflhi01/health-cards-tests | src/FhirConnector.ts | TypeScript |
InterfaceDeclaration |
export interface FhirConnection {
newSmartState: SmartState,
} | Muflhi01/health-cards-tests | src/FhirConnector.ts | TypeScript |
MethodDeclaration |
async telegramBotTest(this: ICredentialTestFunctions, credential: ICredentialsDecrypted): Promise<NodeCredentialTestResult> {
const credentials = credential.data;
const options = {
uri: `https://api.telegram.org/bot${credentials!.accessToken}/getMe`,
json: true,
};
try {
const response = await this.helpers.request(options);
if (!response.ok) {
return {
status: 'Error',
message: 'Token is not valid.',
};
}
} catch (err) {
return {
status: 'Error',
message: `Token is not valid; ${err.message}`,
};
}
return {
status: 'OK',
message: 'Authentication successful!',
};
} | Aarnab2/n8n | packages/nodes-base/nodes/Telegram/Telegram.node.ts | TypeScript |
ArrowFunction |
() => ({
getPathArray: jest.fn(() => mockPath.split("/")),
}) | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ArrowFunction |
() => mockPath.split("/") | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ArrowFunction |
() => {
const fakeProps = (): WeedLayerProps => ({
visible: true,
radiusVisible: true,
weeds: [fakeWeed()],
mapTransformProps: fakeMapTransformProps(),
hoveredPoint: undefined,
dispatch: jest.fn(),
currentPoint: undefined,
boxSelected: undefined,
groupSelected: [],
animate: false,
interactions: true,
});
it("shows weeds", () => {
const p = fakeProps();
p.interactions = false;
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.find(GardenWeed).html()).toContain("r=\"100\"");
expect(layer.props().style).toEqual({ pointerEvents: "none" });
});
it("toggles visibility off", () => {
const p = fakeProps();
p.visible = false;
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.find(GardenWeed).length).toEqual(0);
});
it("allows weed mode interaction", () => {
mockPath = Path.mock(Path.weeds());
const p = fakeProps();
p.interactions = true;
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.props().style).toEqual({ cursor: "pointer" });
});
it("is selected", () => {
mockPath = Path.mock(Path.weeds());
const p = fakeProps();
const weed = fakeWeed();
p.weeds = [weed];
p.boxSelected = [weed.uuid];
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.find(GardenWeed).props().selected).toBeTruthy();
});
} | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ArrowFunction |
(): WeedLayerProps => ({
visible: true,
radiusVisible: true,
weeds: [fakeWeed()],
mapTransformProps: fakeMapTransformProps(),
hoveredPoint: undefined,
dispatch: jest.fn(),
currentPoint: undefined,
boxSelected: undefined,
groupSelected: [],
animate: false,
interactions: true,
}) | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ArrowFunction |
() => {
const p = fakeProps();
p.interactions = false;
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.find(GardenWeed).html()).toContain("r=\"100\"");
expect(layer.props().style).toEqual({ pointerEvents: "none" });
} | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ArrowFunction |
() => {
const p = fakeProps();
p.visible = false;
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.find(GardenWeed).length).toEqual(0);
} | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ArrowFunction |
() => {
mockPath = Path.mock(Path.weeds());
const p = fakeProps();
p.interactions = true;
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.props().style).toEqual({ cursor: "pointer" });
} | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ArrowFunction |
() => {
mockPath = Path.mock(Path.weeds());
const p = fakeProps();
const weed = fakeWeed();
p.weeds = [weed];
p.boxSelected = [weed.uuid];
const wrapper = svgMount(<WeedLayer {...p} />);
const layer = wrapper.find("#weeds-layer");
expect(layer.find(GardenWeed).props().selected).toBeTruthy();
} | alanwangvt/Farmbot-Web-App | frontend/farm_designer/map/layers/weeds/__tests__/weed_layer_test.tsx | TypeScript |
ClassDeclaration |
@Injectable()
export class AppService {
getHello(): string {
console.log('HOLA');
return 'Hello World with NestJS LC!';
}
} | luiscasdel64/api-task | src/app.service.ts | TypeScript |
MethodDeclaration |
getHello(): string {
console.log('HOLA');
return 'Hello World with NestJS LC!';
} | luiscasdel64/api-task | src/app.service.ts | TypeScript |
FunctionDeclaration |
export function SessionFromJSON(json: any): Session {
return SessionFromJSONTyped(json, false)
} | apideck-libraries/node-sdk | src/gen/models/Session.ts | TypeScript |
FunctionDeclaration |
export function SessionFromJSONTyped(json: any, ignoreDiscriminator: boolean): Session {
if (json === undefined || json === null) {
return json
}
return {
consumer_metadata: !exists(json, 'consumer_metadata')
? undefined
: ConsumerMetadataFromJSON(json['consumer_metadata']),
custom_consumer_settings: !exists(json, 'custom_consumer_settings')
? undefined
: json['custom_consumer_settings'],
redirect_uri: !exists(json, 'redirect_uri') ? undefined : json['redirect_uri'],
settings: !exists(json, 'settings') ? undefined : SessionSettingsFromJSON(json['settings']),
theme: !exists(json, 'theme') ? undefined : SessionThemeFromJSON(json['theme'])
}
} | apideck-libraries/node-sdk | src/gen/models/Session.ts | TypeScript |
FunctionDeclaration |
export function SessionToJSON(value?: Session | null): any {
if (value === undefined) {
return undefined
}
if (value === null) {
return null
}
return {
consumer_metadata: ConsumerMetadataToJSON(value.consumer_metadata),
custom_consumer_settings: value.custom_consumer_settings,
redirect_uri: value.redirect_uri,
settings: SessionSettingsToJSON(value.settings),
theme: SessionThemeToJSON(value.theme)
}
} | apideck-libraries/node-sdk | src/gen/models/Session.ts | TypeScript |
InterfaceDeclaration | /**
*
* @export
* @interface Session
*/
export interface Session {
/**
*
* @type {ConsumerMetadata}
* @memberof Session
*/
consumer_metadata?: ConsumerMetadata
/**
* Custom consumer settings that are passed as part of the session.
* @type {{ [key: string]: object; }}
* @memberof Session
*/
custom_consumer_settings?: { [key: string]: unknown }
/**
*
* @type {string}
* @memberof Session
*/
redirect_uri?: string
/**
*
* @type {SessionSettings}
* @memberof Session
*/
settings?: SessionSettings
/**
*
* @type {SessionTheme}
* @memberof Session
*/
theme?: SessionTheme
} | apideck-libraries/node-sdk | src/gen/models/Session.ts | TypeScript |
FunctionDeclaration | /**
* The `humanTime` utility converts a date to a localized, human-readable time-
* ago string.
*/
export default function humanTime(time: Date): string {
let d = dayjs(time);
const now = dayjs();
// To prevent showing things like "in a few seconds" due to small offsets
// between client and server time, we always reset future dates to the
// current time. This will result in "just now" being shown instead.
if (d.isAfter(now)) {
d = now;
}
const day = 864e5;
const diff = d.diff(dayjs());
let ago: string;
// If this date was more than a month ago, we'll show the name of the month
// in the string. If it wasn't this year, we'll show the year as well.
if (diff < -30 * day) {
if (d.year() === dayjs().year()) {
ago = d.format('D MMM');
} else {
ago = d.format('ll');
}
} else {
ago = d.fromNow();
}
return ago;
} | Heniisbaba/core | js/src/common/utils/humanTime.ts | TypeScript |
ArrowFunction |
(selector: string) => {
const el = this.shadowRoot!.querySelector(selector) as PolymerElement;
if (el) {
el.set('invalid', false);
}
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
ArrowFunction |
(selector: string) => {
const el = this.shadowRoot!.querySelector(selector) as PolymerElement & {
validate(): boolean;
};
if (el && !el.validate()) {
isValid = false;
}
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
ClassDeclaration | /**
* @polymer
* @customElement
* @appliesMixin EnvironmentFlagsMixin
*/
class PdTermination extends EnvironmentFlagsMixin(PolymerElement) {
static get template() {
return html`
${SharedStyles} ${gridLayoutStyles} ${requiredFieldStarredStyles}
<style>
:host {
/* host CSS */
}
#pdTermination {
--etools-dialog-default-btn-bg: var(--error-color);
}
#pdTerminationConfirmation {
--etools-dialog-confirm-btn-bg: var(--primary-color);
}
</style>
<etools-dialog
no-padding
keep-dialog-open
id="pdTermination"
opened="{{opened}}"
size="md"
hidden$="[[warningOpened]]"
ok-btn-text="Terminate"
dialog-title="Terminate PD/SSFA"
on-close="_handleDialogClosed"
on-confirm-btn-clicked="_triggerPdTermination"
disable-confirm-btn="[[uploadInProgress]]"
disable-dismiss-btn="[[uploadInProgress]]"
>
<div class="row-h flex-c">
<datepicker-lite
id="terminationDate"
label="Termination Date"
value="{{termination.date}}"
error-message="Please select termination date"
auto-validate
required
selected-date-display-format="D MMM YYYY"
>
</datepicker-lite>
</div>
<div class="row-h flex-c">
<etools-upload
id="terminationNotice"
label="Termination Notice"
accept=".doc,.docx,.pdf,.jpg,.png"
file-url="[[termination.attachment_notice]]"
upload-endpoint="[[uploadEndpoint]]"
on-upload-finished="_uploadFinished"
required
auto-validate
upload-in-progress="{{uploadInProgress}}"
error-message="Termination Notice file is required"
>
</etools-upload>
</div>
<div class="row-h">
<etools-warn-message
messages="Once you hit save, the PD/SSFA will be Terminated and this action can not be reversed"
>
</etools-warn-message>
</div>
</etools-dialog>
<etools-dialog
no-padding
id="pdTerminationConfirmation"
theme="confirmation"
opened="{{warningOpened}}"
size="md"
ok-btn-text="Continue"
on-close="_terminationConfirmed"
>
<div class="row-h">
Please make sure that the reporting requirements for the PD are updated with the correct dates
</div>
</etools-dialog>
`;
}
@property({type: String})
uploadEndpoint: string = pmpEndpoints.attachmentsUpload.url;
@property({type: Number})
interventionId!: number;
@property({type: Boolean})
opened!: boolean;
@property({type: Boolean})
warningOpened!: boolean;
@property({type: Object})
termination!: {date: string; attachment_notice: number};
@property({type: Object})
terminationElSource!: PolymerElement;
@property({type: Boolean})
uploadInProgress = false;
private _validationSelectors: string[] = ['#terminationDate', '#terminationNotice'];
connectedCallback() {
super.connectedCallback();
(this.$.terminationDate as any).maxDate = this._getMaxDate();
}
_getMaxDate() {
return moment(Date.now()).add(30, 'd').toDate();
}
_handleDialogClosed() {
this.resetValidations();
}
_triggerPdTermination() {
if (!this.validate()) {
return;
}
if (this.environmentFlags && !this.environmentFlags.prp_mode_off && this.environmentFlags.prp_server_on) {
this.set('warningOpened', true);
} else {
this._terminatePD();
}
}
_terminationConfirmed(e: CustomEvent) {
if (e.detail.confirmed) {
this._terminatePD();
}
}
_terminatePD() {
if (this.validate()) {
fireEvent(this.terminationElSource, 'terminate-pd', {
interventionId: this.interventionId,
terminationData: {
date: this.termination.date,
fileId: this.termination.attachment_notice
}
});
this.set('opened', false);
}
}
// TODO: refactor validation at some point (common with ag add amendment dialog and more)
resetValidations() {
this._validationSelectors.forEach((selector: string) => {
const el = this.shadowRoot!.querySelector(selector) as PolymerElement;
if (el) {
el.set('invalid', false);
}
});
}
// TODO: refactor validation at some point (common with ag add amendment dialog and more)
validate() {
let isValid = true;
this._validationSelectors.forEach((selector: string) => {
const el = this.shadowRoot!.querySelector(selector) as PolymerElement & {
validate(): boolean;
};
if (el && !el.validate()) {
isValid = false;
}
});
return isValid;
}
_uploadFinished(e: CustomEvent) {
if (e.detail.success) {
const uploadResponse = e.detail.success;
this.set('termination.attachment_notice', uploadResponse.id);
}
}
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration |
connectedCallback() {
super.connectedCallback();
(this.$.terminationDate as any).maxDate = this._getMaxDate();
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration |
_getMaxDate() {
return moment(Date.now()).add(30, 'd').toDate();
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration |
_handleDialogClosed() {
this.resetValidations();
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration |
_triggerPdTermination() {
if (!this.validate()) {
return;
}
if (this.environmentFlags && !this.environmentFlags.prp_mode_off && this.environmentFlags.prp_server_on) {
this.set('warningOpened', true);
} else {
this._terminatePD();
}
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration |
_terminationConfirmed(e: CustomEvent) {
if (e.detail.confirmed) {
this._terminatePD();
}
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration |
_terminatePD() {
if (this.validate()) {
fireEvent(this.terminationElSource, 'terminate-pd', {
interventionId: this.interventionId,
terminationData: {
date: this.termination.date,
fileId: this.termination.attachment_notice
}
});
this.set('opened', false);
}
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration | // TODO: refactor validation at some point (common with ag add amendment dialog and more)
resetValidations() {
this._validationSelectors.forEach((selector: string) => {
const el = this.shadowRoot!.querySelector(selector) as PolymerElement;
if (el) {
el.set('invalid', false);
}
});
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration | // TODO: refactor validation at some point (common with ag add amendment dialog and more)
validate() {
let isValid = true;
this._validationSelectors.forEach((selector: string) => {
const el = this.shadowRoot!.querySelector(selector) as PolymerElement & {
validate(): boolean;
};
if (el && !el.validate()) {
isValid = false;
}
});
return isValid;
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
MethodDeclaration |
_uploadFinished(e: CustomEvent) {
if (e.detail.success) {
const uploadResponse = e.detail.success;
this.set('termination.attachment_notice', uploadResponse.id);
}
} | unicef/etools-partnership-management | src_ts/components/app-modules/interventions/components/pd-termination.ts | TypeScript |
ArrowFunction |
(props) => {
const actionRef = useRef<ActionType>();
const [editShow, seteditShow] = useState<boolean>(false)
const [pagesize, setpagesize] = useState<number>(10)
const [select, setselect] = useState<string>()
const confirm = (id: string) => {
let form = new FormData()
form.append('id', id)
deleteCurrent(form).then(res => {
if (res.code === 1) {
message.success(res.msg)
actionRef.current?.reload()
}
})
}
enum status {
'待系统审核' = 'processing',
'待媒体审核' = 'processing',
'系统审核通过' = 'default',
'媒体审核通过' = 'default',
'系统审核失败' = 'error',
'媒体审核失败' = 'error',
'开启中' = 'success',
'已关闭' = 'default',
'已删除' = 'default'
}
const columns: ProColumns<GithubIssueItem>[] = [
{
dataIndex: 'id',
title: 'id',
width: 48,
hideInSearch: true
},
{
title: '关键词',
dataIndex: 'keywords',
ellipsis: true,
hideInTable: true,
},
{
title: '计划名称',
dataIndex: 'name',
ellipsis: true,
hideInSearch: true
},
{
title: '开关',
dataIndex: 'status',
hideInSearch: true,
ellipsis: true,
render: (r, re) => {
return (
<Switch checked={re.is_active === 1 ? true : false} onChange={() | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
(id: string) => {
let form = new FormData()
form.append('id', id)
deleteCurrent(form).then(res => {
if (res.code === 1) {
message.success(res.msg)
actionRef.current?.reload()
}
})
} | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
res => {
if (res.code === 1) {
message.success(res.msg)
actionRef.current?.reload()
}
} | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
(r, re) => {
return (
<Switch checked={re.is_active === 1 ? true : false} onChange={() | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
res => {
if (res.code === 1) {
message.success(res.msg)
actionRef.current?.reload()
}
} | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
(_, item) => {
return <Badge status={status[item.status]} text={item.status} />;
} | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
(text, record, _, action) => [
<Button type="primary" disabled={record?.status === 1 ? true : false | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
() => actionRef.current?.reload() | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
EnumDeclaration |
enum status {
'待系统审核' = 'processing',
'待媒体审核' = 'processing',
'系统审核通过' = 'default',
'媒体审核通过' = 'default',
'系统审核失败' = 'error',
'媒体审核失败' = 'error',
'开启中' = 'success',
'已关闭' = 'default',
'已删除' = 'default'
} | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
TypeAliasDeclaration |
type GithubIssueItem = {
url: string;
id: number;
number: number;
title: string;
labels: {
name: string;
color: string;
}[];
state: string;
comments: number;
created_at: string;
updated_at: string;
closed_at?: string;
is_active?: number;
}; | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
MethodDeclaration |
async (
params: T & {
pageSize: number;
current: number;
},
sort,
filter,
) | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
MethodDeclaration |
seteditShow(true) | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
MethodDeclaration |
setselect('') | MrChowjl/ddd | src/pages/Account/Adplan/components/plan/index.tsx | TypeScript |
ArrowFunction |
() => {
page = new FrontEndPage();
} | RustyShackleforth/atomspace-explorer | e2e/app.e2e-spec.ts | TypeScript |
ArrowFunction |
async (generator: any) => {
consola.info(`Copying specified static contents`)
// generate 出力ディレクトリに options.api ディレクトリを作成
const distCopyPath = join(generator.distPath, options.api)
await fsExtra.mkdirp(distCopyPath).catch((err) => consola.error(err))
await fsExtra
.copy(options.dirpath, distCopyPath, {
overwrite: false,
errorOnExist: true,
})
.then(() =>
consola.success(`Copied from "${options.dirpath}" to "${distCopyPath}"`)
)
.catch((err) => consola.error(err))
} | akiakishitai/vlife-blog | src/modules/copyToDist/index.ts | TypeScript |
ArrowFunction |
(err) => consola.error(err) | akiakishitai/vlife-blog | src/modules/copyToDist/index.ts | TypeScript |
ArrowFunction |
() =>
consola.success(`Copied from "${options.dirpath}" to "${distCopyPath}"`) | akiakishitai/vlife-blog | src/modules/copyToDist/index.ts | TypeScript |
InterfaceDeclaration |
export interface ModuleOptions {
/** API エンドポイント */
api: string
/** 提供するローカルディレクトリパス */
dirpath: string
} | akiakishitai/vlife-blog | src/modules/copyToDist/index.ts | TypeScript |
InterfaceDeclaration |
export interface UserPayload {
username: string,
email: string,
role: Role
} | thesamhurwitz/hoenn-auth | src/auth/session-payload.ts | TypeScript |
InterfaceDeclaration |
export interface SessionPayload {
ip?: string,
device?: IResult,
location?: string,
createdAt: Date,
lastAccess: Date,
expires: Date,
user: UserPayload
} | thesamhurwitz/hoenn-auth | src/auth/session-payload.ts | TypeScript |
ArrowFunction |
comment => ({
id: comment._id,
imageUrl: comment.imageUrl,
commentBy: comment.commentBy,
commentBody: comment.commentBody,
dateCreated: comment.dateCreated,
postId: comment.postId
}) | ani-abel/Blog-api | src/Comments/comments.service.ts | TypeScript |
ClassDeclaration |
export class CommentsService {
constructor(@InjectModel("Comment") private readonly commentsModel: Model<Comment>){ }
async addComment(postId: string, commentBy: string, commentBody: string, imageUrl?: string): Promise<any> {
const newComment = new this.commentsModel({ imageUrl, commentBy, commentBody, postId });
//Check to see if a similar image already exists
if(await this.commentsModel.exists({ commentBy, commentBody, postId })){
throw new ForbiddenException("Comment already exists by you");
}
//save the entry to the db
const result = await newComment.save();
console.log(result);
return { id: result._id,
imageUrl: result.imageUrl,
commentBy: result.commentBy,
commentBody: result.commentBody,
dateCreated: result.dateCreated,
postId: result.postId
};
}
async getComments(postId: string): Promise<any>{
const comments = await this.commentsModel
.find({ postId })
.sort({ dateCreated: "desc" })
.limit(15)
.exec();
console.log(comments);
return comments.map(comment => ({
id: comment._id,
imageUrl: comment.imageUrl,
commentBy: comment.commentBy,
commentBody: comment.commentBody,
dateCreated: comment.dateCreated,
postId: comment.postId
}));
}
async countComments(postId: string): Promise<{ total: number }>{
console.log(postId);
const total = await this.commentsModel
.countDocuments({ postId })
.exec();
return { total };
}
} | ani-abel/Blog-api | src/Comments/comments.service.ts | TypeScript |
MethodDeclaration |
async addComment(postId: string, commentBy: string, commentBody: string, imageUrl?: string): Promise<any> {
const newComment = new this.commentsModel({ imageUrl, commentBy, commentBody, postId });
//Check to see if a similar image already exists
if(await this.commentsModel.exists({ commentBy, commentBody, postId })){
throw new ForbiddenException("Comment already exists by you");
}
//save the entry to the db
const result = await newComment.save();
console.log(result);
return { id: result._id,
imageUrl: result.imageUrl,
commentBy: result.commentBy,
commentBody: result.commentBody,
dateCreated: result.dateCreated,
postId: result.postId
};
} | ani-abel/Blog-api | src/Comments/comments.service.ts | TypeScript |
MethodDeclaration |
async getComments(postId: string): Promise<any>{
const comments = await this.commentsModel
.find({ postId })
.sort({ dateCreated: "desc" })
.limit(15)
.exec();
console.log(comments);
return comments.map(comment => ({
id: comment._id,
imageUrl: comment.imageUrl,
commentBy: comment.commentBy,
commentBody: comment.commentBody,
dateCreated: comment.dateCreated,
postId: comment.postId
}));
} | ani-abel/Blog-api | src/Comments/comments.service.ts | TypeScript |
MethodDeclaration |
async countComments(postId: string): Promise<{ total: number }>{
console.log(postId);
const total = await this.commentsModel
.countDocuments({ postId })
.exec();
return { total };
} | ani-abel/Blog-api | src/Comments/comments.service.ts | TypeScript |
ClassDeclaration |
export class NotFoundRequestError extends JWAError {
constructor(message: string, origin?: Error) {
super(
404,
`URL Not found. Details: ${message}`,
"URL_NOT_FOUND",
origin
);
}
} | jwa-lab/airlock | src/lib/errors/notFoundRequestError.ts | TypeScript |
ArrowFunction |
() => IftaFuelTaxesFilterInput | LeonardoRiosvlz/Shunchine | src/modules/ifta-fuel-taxes/graphql/dto/inputs/get-one-ifta-fuel-taxes.input.ts | TypeScript |
ClassDeclaration |
@InputType()
export class GetOneIftaFuelTaxesInput {
@Field(() => IftaFuelTaxesFilterInput, {nullable: true} ) where?: Filter<IftaFuelTaxesFilter>;
} | LeonardoRiosvlz/Shunchine | src/modules/ifta-fuel-taxes/graphql/dto/inputs/get-one-ifta-fuel-taxes.input.ts | TypeScript |
TypeAliasDeclaration |
export type ProgressLog = supiLogs.ProgressLog | packageRequesterLogs.ProgressLog | davej/supi | src/index.ts | TypeScript |
TypeAliasDeclaration |
export type Log = supiLogs.Log | packageRequesterLogs.Log | LifecycleLog | davej/supi | src/index.ts | TypeScript |
ClassDeclaration | /*
Generated class for the GoogleMapsProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class GoogleMapsProvider {
constructor(public http: Http) {
console.log('Hello GoogleMapsProvider Provider');
}
} | wandieinnocents/CitiMastaPro | src/providers/google-maps/google-maps.ts | TypeScript |
ArrowFunction |
async () => {
connection = new Connection();
await connection.connect();
await createTestSchema(connection);
} | panates/postgresql-client | test/B-connection/04-query.spec.ts | TypeScript |
ArrowFunction |
async () => {
await connection.close();
} | panates/postgresql-client | test/B-connection/04-query.spec.ts | TypeScript |
ArrowFunction |
() =>
connection.query(`select * from customers`, {fetchCount: -1}) | panates/postgresql-client | test/B-connection/04-query.spec.ts | TypeScript |
ArrowFunction |
() =>
connection.query(`select * from customers`, {fetchCount: 4294967296}) | panates/postgresql-client | test/B-connection/04-query.spec.ts | TypeScript |
ArrowFunction |
() => connection.query(`invalid sql`) | panates/postgresql-client | test/B-connection/04-query.spec.ts | TypeScript |
InterfaceDeclaration |
export interface Options {
main?: 'index.js',
outputDir?: boolean,
exports?: 'default' | 'import' | 'named',
camelCase?: camelcase.Options | false
} | fengxinming/rollup-plugin-combine | packages/rollup-plugin-combine/index.d.ts | TypeScript |
TypeAliasDeclaration |
type createPlugin = (opts?: Options) => Plugin; | fengxinming/rollup-plugin-combine | packages/rollup-plugin-combine/index.d.ts | TypeScript |
ArrowFunction |
({ children }) => {
const { questions } = useStoreState(state => state.questionStore)
const { addQuestion } = useStoreActions(action => action.questionStore)
const [question, setQuestion] = useState('')
const addQuestionHandler = () => {
const newQuestion: Question = {
id: v4(),
question
}
/* addQuestion(newQuestion) */
setQuestion('')
}
return (
<>
<QuestionForm
question={question}
setQuestion={setQuestion}
placeholder={`${questions.length + 1}. Question?`} | F34th3R/quizzapp | frontend/src/components/pages/Quiz/create/CreateQuestion.tsx | TypeScript |
ArrowFunction |
state => state.questionStore | F34th3R/quizzapp | frontend/src/components/pages/Quiz/create/CreateQuestion.tsx | TypeScript |
ArrowFunction |
action => action.questionStore | F34th3R/quizzapp | frontend/src/components/pages/Quiz/create/CreateQuestion.tsx | TypeScript |
ArrowFunction |
() => {
const newQuestion: Question = {
id: v4(),
question
}
/* addQuestion(newQuestion) */
setQuestion('')
} | F34th3R/quizzapp | frontend/src/components/pages/Quiz/create/CreateQuestion.tsx | TypeScript |
ArrowFunction |
({ id, question }) => (
<QuestionForm
key={id} | F34th3R/quizzapp | frontend/src/components/pages/Quiz/create/CreateQuestion.tsx | TypeScript |
FunctionDeclaration |
export async function amendVersion(): Promise<void> {
const tags = await gitReleaseTags('HEAD')
if (tags.length === 0) {
throw new InputError(
'The current commit does not appear to be a release commit.'
)
}
const staged = await gitListStagedFiles()
if (staged.length === 0) {
throw new InputError(
'To amend a release, first stage the updated files with `git add`.'
)
}
await gitAmendCommit(tags)
} | eemeli/version | src/version/amend-version.ts | TypeScript |
ClassDeclaration |
export class MapFactory extends ContractFactory {
constructor(signer?: Signer) {
super(_abi, _bytecode, signer);
}
deploy(overrides?: Overrides): Promise<Map> {
return super.deploy(overrides || {}) as Promise<Map>;
}
getDeployTransaction(overrides?: Overrides): TransactionRequest {
return super.getDeployTransaction(overrides || {});
}
attach(address: string): Map {
return super.attach(address) as Map;
}
connect(signer: Signer): MapFactory {
return super.connect(signer) as MapFactory;
}
static connect(address: string, signerOrProvider: Signer | Provider): Map {
return new Contract(address, _abi, signerOrProvider) as Map;
}
} | ipatka/monster-encounter | src/types/MapFactory.ts | TypeScript |
MethodDeclaration |
deploy(overrides?: Overrides): Promise<Map> {
return super.deploy(overrides || {}) as Promise<Map>;
} | ipatka/monster-encounter | src/types/MapFactory.ts | TypeScript |
MethodDeclaration |
getDeployTransaction(overrides?: Overrides): TransactionRequest {
return super.getDeployTransaction(overrides || {});
} | ipatka/monster-encounter | src/types/MapFactory.ts | TypeScript |
MethodDeclaration |
attach(address: string): Map {
return super.attach(address) as Map;
} | ipatka/monster-encounter | src/types/MapFactory.ts | TypeScript |
MethodDeclaration |
connect(signer: Signer): MapFactory {
return super.connect(signer) as MapFactory;
} | ipatka/monster-encounter | src/types/MapFactory.ts | TypeScript |
MethodDeclaration |
static connect(address: string, signerOrProvider: Signer | Provider): Map {
return new Contract(address, _abi, signerOrProvider) as Map;
} | ipatka/monster-encounter | src/types/MapFactory.ts | TypeScript |
Subsets and Splits