type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
ArrowFunction
|
() => this._onDidConfigurationChange.fire(this.configurationName)
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
content => true
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
err =>
this.getInitialConfigFileContent().then(content => {
if (!content) {
return false;
}
configFileCreated = true;
return this.fileService.updateContent(resource, content).then(() => true);
}
)
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
content => {
if (!content) {
return false;
}
configFileCreated = true;
return this.fileService.updateContent(resource, content).then(() => true);
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
() => true
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
errorFree => {
if (!errorFree) {
return false;
}
this.telemetryService.publicLog('debugConfigure');
return this.editorService.openEditor({
resource: resource,
options: {
forceOpen: true,
pinned: configFileCreated // pin only if config file is created #8727
},
}, sideBySide).then(() => true);
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
(error) => {
throw new Error(nls.localize('DebugConfig.failed', "Unable to create 'launch.json' file inside the '.vscode' folder ({0}).", error));
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
adapter => {
if (!adapter) {
return null;
}
return this.massageInitialConfigurations(adapter).then(() => {
let editorConfig = this.configurationService.getConfiguration<any>();
return JSON.stringify(
{
version: '0.2.0',
configurations: adapter.initialConfigurations ? adapter.initialConfigurations : []
},
null,
editorConfig.editor.insertSpaces ? strings.repeat(' ', editorConfig.editor.tabSize) : '\t');
});
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
() => {
let editorConfig = this.configurationService.getConfiguration<any>();
return JSON.stringify(
{
version: '0.2.0',
configurations: adapter.initialConfigurations ? adapter.initialConfigurations : []
},
null,
editorConfig.editor.insertSpaces ? strings.repeat(' ', editorConfig.editor.tabSize) : '\t');
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
jsonContent => {
try {
const jsonObject = JSON.parse(jsonContent.value);
if (jsonObject.main) {
return jsonObject.main;
} else if (jsonObject.scripts && typeof jsonObject.scripts.start === 'string') {
return (<string>jsonObject.scripts.start).split(' ').pop();
}
} catch (error) { }
return null;
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
err => null
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
(program: string) => {
adapter.initialConfigurations.forEach(config => {
if (program && config.program) {
if (!path.isAbsolute(program)) {
program = paths.join('${workspaceRoot}', program);
}
config.program = program;
}
});
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
ArrowFunction
|
config => {
if (program && config.program) {
if (!path.isAbsolute(program)) {
program = paths.join('${workspaceRoot}', program);
}
config.program = program;
}
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
private registerListeners(): void {
debuggersExtPoint.setHandler((extensions) => {
extensions.forEach(extension => {
extension.value.forEach(rawAdapter => {
const adapter = new Adapter(rawAdapter, this.systemVariables, extension.description);
const duplicate = this.adapters.filter(a => a.type === adapter.type)[0];
if (!rawAdapter.type || (typeof rawAdapter.type !== 'string')) {
extension.collector.error(nls.localize('debugNoType', "Debug adapter 'type' can not be omitted and must be of type 'string'."));
}
if (duplicate) {
Object.keys(adapter).forEach(attribute => {
if (adapter[attribute]) {
if (attribute === 'enableBreakpointsFor') {
Object.keys(adapter.enableBreakpointsFor).forEach(languageId => duplicate.enableBreakpointsFor[languageId] = true);
} else if (duplicate[attribute] && attribute !== 'type' && attribute !== 'extensionDescription') {
// give priority to the later registered extension.
duplicate[attribute] = adapter[attribute];
extension.collector.error(nls.localize('duplicateDebuggerType', "Debug type '{0}' is already registered and has attribute '{1}', ignoring attribute '{1}'.", adapter.type, attribute));
} else {
duplicate[attribute] = adapter[attribute];
}
}
});
} else {
this.adapters.push(adapter);
}
if (adapter.enableBreakpointsFor) {
adapter.enableBreakpointsFor.languageIds.forEach(modeId => {
this.allModeIdsForBreakpoints[modeId] = true;
});
}
});
});
// update the schema to include all attributes and types from extensions.
// debug.schema.properties['configurations'].items.properties.type.enum = this.adapters.map(adapter => adapter.type);
this.adapters.forEach(adapter => {
const schemaAttributes = adapter.getSchemaAttributes();
if (schemaAttributes) {
(<IJSONSchema> schema.properties['configurations'].items).oneOf.push(...schemaAttributes);
}
});
});
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Resolve all interactive variables in configuration #6569
*/
public resolveInteractiveVariables(): TPromise<debug.IConfig> {
if (!this.configuration) {
return TPromise.as(null);
}
// We need a map from interactive variables to keys because we only want to trigger an command once per key -
// even though it might occure multiple times in configuration #7026.
const interactiveVariablesToKeys: { [key: string]: string[] } = {};
const findInteractiveVariables = (object: any) => {
Object.keys(object).forEach(key => {
if (object[key] && typeof object[key] === 'object') {
findInteractiveVariables(object[key]);
} else if (typeof object[key] === 'string') {
const matches = /\${command.(.+)}/.exec(object[key]);
if (matches && matches.length === 2) {
const interactiveVariable = matches[1];
if (!interactiveVariablesToKeys[interactiveVariable]) {
interactiveVariablesToKeys[interactiveVariable] = [];
}
interactiveVariablesToKeys[interactiveVariable].push(key);
}
}
});
};
findInteractiveVariables(this.configuration);
const factory: { (): TPromise<any> }[] = Object.keys(interactiveVariablesToKeys).map(interactiveVariable => {
return () => {
const commandId = this.adapter.variables ? this.adapter.variables[interactiveVariable] : null;
if (!commandId) {
return TPromise.wrapError(nls.localize('interactiveVariableNotFound', "Adapter {0} does not contribute variable {1} that is specified in launch configuration.", this.adapter.type, interactiveVariable));
} else {
return this.keybindingService.executeCommand<string>(commandId, this.configuration).then(result => {
if (!result) {
this.configuration.silentlyAbort = true;
}
interactiveVariablesToKeys[interactiveVariable].forEach(key => this.configuration[key] = this.configuration[key].replace(`\${command.${ interactiveVariable }}`, result));
});
}
};
});
return sequence(factory).then(() => this.configuration);
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
public setConfiguration(nameOrConfig: string|debug.IConfig): TPromise<void> {
return this.loadLaunchConfig().then(config => {
if (types.isObject(nameOrConfig)) {
this.configuration = objects.deepClone(nameOrConfig) as debug.IConfig;
} else {
if (!config || !config.configurations) {
this.configuration = null;
return;
}
// if the configuration name is not set yet, take the first launch config (can happen if debug viewlet has not been opened yet).
const filtered = nameOrConfig ? config.configurations.filter(cfg => cfg.name === nameOrConfig) : [config.configurations[0]];
this.configuration = filtered.length === 1 ? objects.deepClone(filtered[0]) : null;
if (config && this.configuration) {
this.configuration.debugServer = config.debugServer;
}
}
if (this.configuration) {
// Set operating system specific properties #1873
if (isWindows && this.configuration.windows) {
Object.keys(this.configuration.windows).forEach(key => {
this.configuration[key] = this.configuration.windows[key];
});
}
if (isMacintosh && this.configuration.osx) {
Object.keys(this.configuration.osx).forEach(key => {
this.configuration[key] = this.configuration.osx[key];
});
}
if (isLinux && this.configuration.linux) {
Object.keys(this.configuration.linux).forEach(key => {
this.configuration[key] = this.configuration.linux[key];
});
}
// massage configuration attributes - append workspace path to relatvie paths, substitute variables in paths.
if (this.systemVariables) {
Object.keys(this.configuration).forEach(key => {
this.configuration[key] = this.systemVariables.resolveAny(this.configuration[key]);
});
}
}
}).then(() => this._onDidConfigurationChange.fire(this.configurationName));
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
public openConfigFile(sideBySide: boolean): TPromise<boolean> {
const resource = uri.file(paths.join(this.contextService.getWorkspace().resource.fsPath, '/.vscode/launch.json'));
let configFileCreated = false;
return this.fileService.resolveContent(resource).then(content => true, err =>
this.getInitialConfigFileContent().then(content => {
if (!content) {
return false;
}
configFileCreated = true;
return this.fileService.updateContent(resource, content).then(() => true);
}
)).then(errorFree => {
if (!errorFree) {
return false;
}
this.telemetryService.publicLog('debugConfigure');
return this.editorService.openEditor({
resource: resource,
options: {
forceOpen: true,
pinned: configFileCreated // pin only if config file is created #8727
},
}, sideBySide).then(() => true);
}, (error) => {
throw new Error(nls.localize('DebugConfig.failed', "Unable to create 'launch.json' file inside the '.vscode' folder ({0}).", error));
});
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
private getInitialConfigFileContent(): TPromise<string> {
return this.quickOpenService.pick(this.adapters, { placeHolder: nls.localize('selectDebug', "Select Environment") })
.then(adapter => {
if (!adapter) {
return null;
}
return this.massageInitialConfigurations(adapter).then(() => {
let editorConfig = this.configurationService.getConfiguration<any>();
return JSON.stringify(
{
version: '0.2.0',
configurations: adapter.initialConfigurations ? adapter.initialConfigurations : []
},
null,
editorConfig.editor.insertSpaces ? strings.repeat(' ', editorConfig.editor.tabSize) : '\t');
});
});
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
private massageInitialConfigurations(adapter: Adapter): TPromise<void> {
if (!adapter || !adapter.initialConfigurations || adapter.type !== 'node') {
return TPromise.as(undefined);
}
// check package.json for 'main' or 'scripts' so we generate a more pecise 'program' attribute in launch.json.
const packageJsonUri = uri.file(paths.join(this.contextService.getWorkspace().resource.fsPath, '/package.json'));
return this.fileService.resolveContent(packageJsonUri).then(jsonContent => {
try {
const jsonObject = JSON.parse(jsonContent.value);
if (jsonObject.main) {
return jsonObject.main;
} else if (jsonObject.scripts && typeof jsonObject.scripts.start === 'string') {
return (<string>jsonObject.scripts.start).split(' ').pop();
}
} catch (error) { }
return null;
}, err => null).then((program: string) => {
adapter.initialConfigurations.forEach(config => {
if (program && config.program) {
if (!path.isAbsolute(program)) {
program = paths.join('${workspaceRoot}', program);
}
config.program = program;
}
});
});
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
public canSetBreakpointsIn(model: editor.IModel): boolean {
if (model.uri.scheme === Schemas.inMemory) {
return false;
}
const mode = model ? model.getMode() : null;
const modeId = mode ? mode.getId() : null;
return !!this.allModeIdsForBreakpoints[modeId];
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
MethodDeclaration
|
public loadLaunchConfig(): TPromise<debug.IGlobalConfig> {
return TPromise.as(this.configurationService.getConfiguration<debug.IGlobalConfig>('launch'));
}
|
blackViking007/redesigned-VSCode
|
src/vs/workbench/parts/debug/node/debugConfigurationManager.ts
|
TypeScript
|
FunctionDeclaration
|
async function bootstrap() {
const app = await NestFactory.create(AppModule,{cors: true });
app.use(express.static(join(process.cwd(), './public')))
await app.listen(process.env.PORT || 3000);
}
|
Himanshu72/Foodbit
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
event => event.reason !== 'resize'
|
GabrielInTheWorld/ngrid
|
libs/ngrid/src/lib/grid/cell/meta-cell.component.ts
|
TypeScript
|
ArrowFunction
|
event => this.columnDef.applySourceWidth(this.el)
|
GabrielInTheWorld/ngrid
|
libs/ngrid/src/lib/grid/cell/meta-cell.component.ts
|
TypeScript
|
ClassDeclaration
|
/**
* Header cell component.
* The header cell component will render the header cell template and add the proper classes and role.
*
* It is also responsible for creating and managing the any `dataHeaderExtensions` registered in the registry.
* These extensions add features to the cells either as a template instance or as a component instance.
* Examples: Sorting behavior, drag&drop/resize handlers, menus etc...
*/
@Component({
selector: 'pbl-ngrid-meta-cell',
// tslint:disable-next-line: no-host-metadata-property
host: {
role: 'cell',
},
exportAs: 'ngridMetaCell',
template: `<ng-container *ngTemplateOutlet="column?.template; context: cellCtx"></ng-container>`,
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class PblNgridMetaCellComponent<T extends PblMetaColumn | PblColumnGroup = PblMetaColumn | PblColumnGroup> extends PblNgridBaseCell {
@ViewChild('vcRef', { read: ViewContainerRef, static: true }) vcRef: ViewContainerRef;
column: T;
cellCtx: MetaCellContext<any, PblMetaColumn>;
get columnDef(): PblNgridColumnDef<PblMetaColumn> { return this.column.columnDef; }
get grid(): _PblNgridComponent { return this.extApi.grid; }
setColumn(column: T, isFooter: boolean) {
const prev = this.column;
if (prev !== column) {
if (prev) {
unrx.kill(this, prev);
}
this.column = column;
if (column) {
if (!column.columnDef) {
new PblNgridColumnDef(this.extApi).column = column;
column.columnDef.name = column.id;
}
this.cellCtx = MetaCellContext.create(column, this.grid);
if (isPblColumnGroup(column)) {
this.el.classList.add(HEADER_GROUP_CSS);
if (column.placeholder) {
this.el.classList.add(HEADER_GROUP_PLACE_HOLDER_CSS);
}
}
this.columnDef.widthChange
.pipe(
filter( event => event.reason !== 'resize'),
unrx(this, column),
)
.subscribe( event => this.columnDef.applySourceWidth(this.el));
applySourceWidth.call(this);
initCellElement(this.el, column);
initCellHeaderFooter(this.el, isFooter);
}
}
}
ngOnDestroy() {
if (this.column) {
unrx(this, this.column);
}
super.ngOnDestroy();
}
}
|
GabrielInTheWorld/ngrid
|
libs/ngrid/src/lib/grid/cell/meta-cell.component.ts
|
TypeScript
|
MethodDeclaration
|
setColumn(column: T, isFooter: boolean) {
const prev = this.column;
if (prev !== column) {
if (prev) {
unrx.kill(this, prev);
}
this.column = column;
if (column) {
if (!column.columnDef) {
new PblNgridColumnDef(this.extApi).column = column;
column.columnDef.name = column.id;
}
this.cellCtx = MetaCellContext.create(column, this.grid);
if (isPblColumnGroup(column)) {
this.el.classList.add(HEADER_GROUP_CSS);
if (column.placeholder) {
this.el.classList.add(HEADER_GROUP_PLACE_HOLDER_CSS);
}
}
this.columnDef.widthChange
.pipe(
filter( event => event.reason !== 'resize'),
unrx(this, column),
)
.subscribe( event => this.columnDef.applySourceWidth(this.el));
applySourceWidth.call(this);
initCellElement(this.el, column);
initCellHeaderFooter(this.el, isFooter);
}
}
}
|
GabrielInTheWorld/ngrid
|
libs/ngrid/src/lib/grid/cell/meta-cell.component.ts
|
TypeScript
|
MethodDeclaration
|
ngOnDestroy() {
if (this.column) {
unrx(this, this.column);
}
super.ngOnDestroy();
}
|
GabrielInTheWorld/ngrid
|
libs/ngrid/src/lib/grid/cell/meta-cell.component.ts
|
TypeScript
|
ClassDeclaration
|
@injectable()
class UpdateDeliveryService {
constructor(
@inject('DeliveriesRepository')
private deliveriesRepository: IDeliveriesRepository,
) {}
public async execute(id: number): Promise<void> {
await this.deliveriesRepository.cancelById(id);
}
}
|
FeruYasu/FastFeet
|
server/src/modules/deliveries/services/CancelDeliveryService.ts
|
TypeScript
|
MethodDeclaration
|
public async execute(id: number): Promise<void> {
await this.deliveriesRepository.cancelById(id);
}
|
FeruYasu/FastFeet
|
server/src/modules/deliveries/services/CancelDeliveryService.ts
|
TypeScript
|
ArrowFunction
|
e => {
e.preventDefault();
const { dispatch } = this.props;
const projName = (e.target.elements
.projectName as HTMLInputElement).value.trim();
const contribNames = (e.target.elements
.contributorName as HTMLInputElement).value.trim();
const appName = (e.target.elements
.appName as HTMLInputElement).value.trim();
const sigName = (e.target.elements
.sigName as HTMLInputElement).value.trim();
const contactName = (e.target.elements
.contactName as HTMLInputElement).value.trim();
const dateApproved = (e.target.elements
.dateApproved as HTMLInputElement).value.toLowerCase();
const dateSigned = (e.target.elements
.dateSigned as HTMLInputElement).value.toLowerCase();
const notes = (e.target.elements
.description as HTMLInputElement).value.toLowerCase();
const jsonObj = {
project_name: projName,
contributor_names: contribNames,
approver_name: appName,
signatory_name: sigName,
contact_name: contactName,
date_approved: dateApproved,
date_signed: dateSigned,
additional_notes: notes,
};
dispatch(claLogger.postNewCla(jsonObj));
const getAlert = () => (
<SweetAlert
success={true}
title="Success"
onConfirm={() => this.hideAlert()}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
() => (
<SweetAlert
success={true}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
() => {
this.setState({
alert: null,
});
this.props.toggleForm(false);
}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
() => {
return this.state.cla_project_names.map(object => (
<option key={object.project_name} value={object.project_name} />
));
}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
object => (
<option key={object.project_name}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
() => {
return this.state.cla_project_approvers_names.map(alist => (
<option key={alist.approver_alias} value={alist.approver_alias} />
));
}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
alist => (
<option key={alist.approver_alias}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
user => {
return <option key={user} value={user} />;
}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
state => ({})
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ClassDeclaration
|
class CCLAForm extends React.Component<Partial<Props>, State> {
constructor(props) {
super(props);
this.state = {
project_name: '',
signed_date: '',
approved_date: '',
contributor_names: '',
approver_name: '',
signatory_name: '',
contact_name: '',
addition_notes: '',
cla_project_names: new Array(),
cla_project_approvers_names: new Array(),
alert: null,
display: {
signatory: [],
poc: [],
},
};
}
handleSubmit = e => {
e.preventDefault();
const { dispatch } = this.props;
const projName = (e.target.elements
.projectName as HTMLInputElement).value.trim();
const contribNames = (e.target.elements
.contributorName as HTMLInputElement).value.trim();
const appName = (e.target.elements
.appName as HTMLInputElement).value.trim();
const sigName = (e.target.elements
.sigName as HTMLInputElement).value.trim();
const contactName = (e.target.elements
.contactName as HTMLInputElement).value.trim();
const dateApproved = (e.target.elements
.dateApproved as HTMLInputElement).value.toLowerCase();
const dateSigned = (e.target.elements
.dateSigned as HTMLInputElement).value.toLowerCase();
const notes = (e.target.elements
.description as HTMLInputElement).value.toLowerCase();
const jsonObj = {
project_name: projName,
contributor_names: contribNames,
approver_name: appName,
signatory_name: sigName,
contact_name: contactName,
date_approved: dateApproved,
date_signed: dateSigned,
additional_notes: notes,
};
dispatch(claLogger.postNewCla(jsonObj));
const getAlert = () => (
<SweetAlert
success={true}
title="Success"
onConfirm={() => this.hideAlert()}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface Props {
dispatch: any;
toggleForm: any;
}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface State {
project_name: string;
signed_date: string;
approved_date: string;
contributor_names: string;
approver_name: string;
signatory_name: string;
contact_name: string;
addition_notes: string;
cla_project_names: any[];
cla_project_approvers_names: any[];
alert: any;
display: {
signatory: string[];
poc: string[];
};
}
|
Ab-hay/oss-contribution-tracker
|
browser/components/CCLAForm.tsx
|
TypeScript
|
ArrowFunction
|
(t) => {
textObjArr.push(this.choiceStringParser(t));
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
ArrowFunction
|
() => {
switch (caseType) {
case this.caseTypes.UPPER_CASE:
return value.toUpperCase();
case this.caseTypes.LOWER_CASE:
return value.toLowerCase();
case this.caseTypes.SENTENCE_CASE:
return value[0].toUpperCase() + value.slice(1);
default:
return value;
}
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
ArrowFunction
|
(filename: string) => {
const fileData = fs.readFileSync(dirname + filename, {
encoding: 'utf-8',
});
onFileContent(filename, fileData);
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
ClassDeclaration
|
@Injectable()
export class Language {
private static data: Record<string, any>;
private static fallbackLang: string;
private static caseTypes = {
UPPER_CASE: 1,
LOWER_CASE: 2,
SENTENCE_CASE: 3,
UNKNOWN: 0,
};
constructor(@Inject(CONFIG_OPTIONS) private options: LocalizationOptions) {
const { path, fallbackLang } = options;
const data: Record<string, any> = {};
Language.readFiles(path, function (filename: string, content: any) {
data[filename.split('.')[0]] = JSON.parse(content);
});
Language.data = data;
Language.fallbackLang = fallbackLang;
}
static trans(
key: string,
language?: string | Record<string, any>,
options?: Record<string, any>
): string {
let langData = Language.data[this.fallbackLang];
if (typeof language === 'string' && language != '') {
langData = Language.data[language];
} else {
options = language as Record<string, any>;
}
let text = get(langData, key, null);
if (!text || typeof text !== 'string') return `ERR::INVALID KEY ==> ${key}`;
if (options) {
for (const k in options) {
text = this.handleOptions(text, k, options[k]);
}
}
return text;
}
static transChoice(
key: string,
language?: string | number,
count?: number | Record<string, any>,
options?: Record<string, any>
): string {
let langData = Language.data[this.fallbackLang];
if (typeof language === 'string' && language != '') {
langData = Language.data[language];
}
if (typeof count === 'object') {
options = count as Record<string, any>;
}
if (typeof language === 'number') {
count = language as number;
}
if (!count && count != 0) throw new Error('Count value not found');
let text = get(langData, key, null);
if (!text || typeof text !== 'string') return `ERR::INVALID KEY ==> ${key}`;
const textObjArr: Record<string, any>[] = [];
text.split('|').forEach((t) => {
textObjArr.push(this.choiceStringParser(t));
});
let finalText = '';
for (const t of textObjArr) {
if (t.limit.upper === count && t.limit.lower === count) {
finalText = t.text;
break;
}
if (t.limit.upper >= count && t.limit.lower <= count) {
finalText = t.text;
break;
}
}
if (finalText && finalText.match(/\bcount\b/)) {
options = { ...options, count };
}
if (options) {
for (const k in options) {
finalText = this.handleOptions(finalText, k, options[k]);
}
}
return finalText ? finalText : `ERR::INVALID COUNT ==> ${count}`;
}
private static choiceStringParser(t: string): Record<string, any> {
const limits: string[] = t.match(/\[(.*?)\]/)![1].split(',');
return {
text: replaceAll(t, /\[.*?\]/, '').trim(),
limit: {
lower: limits[0] === '*' ? Number.NEGATIVE_INFINITY : +limits[0],
upper: limits[1]
? limits[1] === '*'
? Number.POSITIVE_INFINITY
: +limits[1]
: +limits[0],
},
};
}
private static handleOptions(text: string, key: string, value: any): string {
// if value is a number
if (!isNaN(+value)) return replaceAll(text, `:${key}`, value);
// if value is a string
let lowerCaseText = text.toLowerCase();
const keyStartIdx = lowerCaseText.indexOf(key);
const identifier: string = text.substr(
keyStartIdx,
keyStartIdx + key.length
);
const caseType = isUpperCase(identifier)
? this.caseTypes.UPPER_CASE
: isLowerCase(identifier)
? this.caseTypes.LOWER_CASE
: isSentenceCase(identifier)
? this.caseTypes.SENTENCE_CASE
: this.caseTypes.UNKNOWN;
text = replaceAll(
text,
`:${
caseType === this.caseTypes.UPPER_CASE
? key.toUpperCase()
: caseType === this.caseTypes.LOWER_CASE
? key.toLowerCase()
: caseType === this.caseTypes.SENTENCE_CASE
? key[0].toUpperCase() + key.slice(1)
: key
}`,
() => {
switch (caseType) {
case this.caseTypes.UPPER_CASE:
return value.toUpperCase();
case this.caseTypes.LOWER_CASE:
return value.toLowerCase();
case this.caseTypes.SENTENCE_CASE:
return value[0].toUpperCase() + value.slice(1);
default:
return value;
}
}
);
return text;
}
private static readFiles(dirname: string, onFileContent: any) {
const fss = fs.readdirSync(dirname);
fss.forEach((filename: string) => {
const fileData = fs.readFileSync(dirname + filename, {
encoding: 'utf-8',
});
onFileContent(filename, fileData);
});
}
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
MethodDeclaration
|
static trans(
key: string,
language?: string | Record<string, any>,
options?: Record<string, any>
): string {
let langData = Language.data[this.fallbackLang];
if (typeof language === 'string' && language != '') {
langData = Language.data[language];
} else {
options = language as Record<string, any>;
}
let text = get(langData, key, null);
if (!text || typeof text !== 'string') return `ERR::INVALID KEY ==> ${key}`;
if (options) {
for (const k in options) {
text = this.handleOptions(text, k, options[k]);
}
}
return text;
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
MethodDeclaration
|
static transChoice(
key: string,
language?: string | number,
count?: number | Record<string, any>,
options?: Record<string, any>
): string {
let langData = Language.data[this.fallbackLang];
if (typeof language === 'string' && language != '') {
langData = Language.data[language];
}
if (typeof count === 'object') {
options = count as Record<string, any>;
}
if (typeof language === 'number') {
count = language as number;
}
if (!count && count != 0) throw new Error('Count value not found');
let text = get(langData, key, null);
if (!text || typeof text !== 'string') return `ERR::INVALID KEY ==> ${key}`;
const textObjArr: Record<string, any>[] = [];
text.split('|').forEach((t) => {
textObjArr.push(this.choiceStringParser(t));
});
let finalText = '';
for (const t of textObjArr) {
if (t.limit.upper === count && t.limit.lower === count) {
finalText = t.text;
break;
}
if (t.limit.upper >= count && t.limit.lower <= count) {
finalText = t.text;
break;
}
}
if (finalText && finalText.match(/\bcount\b/)) {
options = { ...options, count };
}
if (options) {
for (const k in options) {
finalText = this.handleOptions(finalText, k, options[k]);
}
}
return finalText ? finalText : `ERR::INVALID COUNT ==> ${count}`;
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
MethodDeclaration
|
private static choiceStringParser(t: string): Record<string, any> {
const limits: string[] = t.match(/\[(.*?)\]/)![1].split(',');
return {
text: replaceAll(t, /\[.*?\]/, '').trim(),
limit: {
lower: limits[0] === '*' ? Number.NEGATIVE_INFINITY : +limits[0],
upper: limits[1]
? limits[1] === '*'
? Number.POSITIVE_INFINITY
: +limits[1]
: +limits[0],
},
};
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
MethodDeclaration
|
private static handleOptions(text: string, key: string, value: any): string {
// if value is a number
if (!isNaN(+value)) return replaceAll(text, `:${key}`, value);
// if value is a string
let lowerCaseText = text.toLowerCase();
const keyStartIdx = lowerCaseText.indexOf(key);
const identifier: string = text.substr(
keyStartIdx,
keyStartIdx + key.length
);
const caseType = isUpperCase(identifier)
? this.caseTypes.UPPER_CASE
: isLowerCase(identifier)
? this.caseTypes.LOWER_CASE
: isSentenceCase(identifier)
? this.caseTypes.SENTENCE_CASE
: this.caseTypes.UNKNOWN;
text = replaceAll(
text,
`:${
caseType === this.caseTypes.UPPER_CASE
? key.toUpperCase()
: caseType === this.caseTypes.LOWER_CASE
? key.toLowerCase()
: caseType === this.caseTypes.SENTENCE_CASE
? key[0].toUpperCase() + key.slice(1)
: key
}`,
() => {
switch (caseType) {
case this.caseTypes.UPPER_CASE:
return value.toUpperCase();
case this.caseTypes.LOWER_CASE:
return value.toLowerCase();
case this.caseTypes.SENTENCE_CASE:
return value[0].toUpperCase() + value.slice(1);
default:
return value;
}
}
);
return text;
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
MethodDeclaration
|
private static readFiles(dirname: string, onFileContent: any) {
const fss = fs.readdirSync(dirname);
fss.forEach((filename: string) => {
const fileData = fs.readFileSync(dirname + filename, {
encoding: 'utf-8',
});
onFileContent(filename, fileData);
});
}
|
squareboat/nestjs-localization
|
lib/src/services/Language.ts
|
TypeScript
|
FunctionDeclaration
|
function tokenString(tokenString: any, jwtSecret: string): JwtDataDto {
throw new Error("Function not implemented.");
}
|
Goja62/RazvojWebAplikacija-back-end
|
src/middlewares/auth.middleware.ts
|
TypeScript
|
ClassDeclaration
|
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(
public administratorService: AdministratorService,
public userService: UserService,
) { }
async use(req: Request, res: Response, next: NextFunction) {
if (!req.headers.authorization) {
throw new HttpException('Token not found', HttpStatus.UNAUTHORIZED);
}
const token = req.headers.authorization;
const tokenParts = token.split(' ');
if (tokenParts.length !== 2) {
throw new HttpException('Bad token found', HttpStatus.UNAUTHORIZED);
}
const tokenString = tokenParts[1];
let jwtData: JwtDataDto;
try {
jwtData = jwt.verify(tokenString, jwtSecret);
} catch (e) {
throw new HttpException('Bad token found', HttpStatus.UNAUTHORIZED);
}
if (!jwtData) {
throw new HttpException('Bad token found', HttpStatus.UNAUTHORIZED);
}
if (jwtData.ip !== req.ip.toString()) {
throw new HttpException('Token not found', HttpStatus.UNAUTHORIZED);
}
if (jwtData.ua !== req.headers['user-agent']) {
throw new HttpException('Token not found', HttpStatus.UNAUTHORIZED);
}
if (jwtData.role === 'administrator') {
const administrator = await this.administratorService.getById(jwtData.id)
if (!administrator) {
throw new HttpException('Account not found', HttpStatus.UNAUTHORIZED);
}
} else if (jwtData.role === 'user') {
const user = await this.userService.getById(jwtData.id)
if (!user) {
throw new HttpException('Account not found', HttpStatus.UNAUTHORIZED);
}
}
const trenutniTimestamp = new Date().getTime() / 1000;
if (trenutniTimestamp >= jwtData.exp) {
throw new HttpException('Token hes expired', HttpStatus.UNAUTHORIZED);
}
req.token = jwtData;
next()
}
}
|
Goja62/RazvojWebAplikacija-back-end
|
src/middlewares/auth.middleware.ts
|
TypeScript
|
MethodDeclaration
|
async use(req: Request, res: Response, next: NextFunction) {
if (!req.headers.authorization) {
throw new HttpException('Token not found', HttpStatus.UNAUTHORIZED);
}
const token = req.headers.authorization;
const tokenParts = token.split(' ');
if (tokenParts.length !== 2) {
throw new HttpException('Bad token found', HttpStatus.UNAUTHORIZED);
}
const tokenString = tokenParts[1];
let jwtData: JwtDataDto;
try {
jwtData = jwt.verify(tokenString, jwtSecret);
} catch (e) {
throw new HttpException('Bad token found', HttpStatus.UNAUTHORIZED);
}
if (!jwtData) {
throw new HttpException('Bad token found', HttpStatus.UNAUTHORIZED);
}
if (jwtData.ip !== req.ip.toString()) {
throw new HttpException('Token not found', HttpStatus.UNAUTHORIZED);
}
if (jwtData.ua !== req.headers['user-agent']) {
throw new HttpException('Token not found', HttpStatus.UNAUTHORIZED);
}
if (jwtData.role === 'administrator') {
const administrator = await this.administratorService.getById(jwtData.id)
if (!administrator) {
throw new HttpException('Account not found', HttpStatus.UNAUTHORIZED);
}
} else if (jwtData.role === 'user') {
const user = await this.userService.getById(jwtData.id)
if (!user) {
throw new HttpException('Account not found', HttpStatus.UNAUTHORIZED);
}
}
const trenutniTimestamp = new Date().getTime() / 1000;
if (trenutniTimestamp >= jwtData.exp) {
throw new HttpException('Token hes expired', HttpStatus.UNAUTHORIZED);
}
req.token = jwtData;
next()
}
|
Goja62/RazvojWebAplikacija-back-end
|
src/middlewares/auth.middleware.ts
|
TypeScript
|
ClassDeclaration
|
@Injectable()
export class UserService {
constructor(@InjectModel(UserModel) private readonly userModel: ReturnModelType<typeof UserModel>) {}
async create( user: UserModel) {
const createdUser = new this.userModel(user);
return createdUser.save();
}
async findAll(): Promise<UserModel[] | null> {
return this.userModel.find().exec();
}
async findOne(id: string): Promise<UserModel | null> {
return this.userModel.findOne({ _id: id });
}
// async update(id: string, user: UserModel): Promise<UserModel> {
// return await this.userModel.findByIdAndUpdate(id, user, { new: true });
// }
//
// async delete(id: string): Promise<UserModel> {
// return await this.userModel.findByIdAndRemove(id);
// }
}
|
oliviermattei/nestjs-graphql-typegoose
|
src/user/user.service.ts
|
TypeScript
|
MethodDeclaration
|
async create( user: UserModel) {
const createdUser = new this.userModel(user);
return createdUser.save();
}
|
oliviermattei/nestjs-graphql-typegoose
|
src/user/user.service.ts
|
TypeScript
|
MethodDeclaration
|
async findAll(): Promise<UserModel[] | null> {
return this.userModel.find().exec();
}
|
oliviermattei/nestjs-graphql-typegoose
|
src/user/user.service.ts
|
TypeScript
|
MethodDeclaration
|
async findOne(id: string): Promise<UserModel | null> {
return this.userModel.findOne({ _id: id });
}
|
oliviermattei/nestjs-graphql-typegoose
|
src/user/user.service.ts
|
TypeScript
|
ArrowFunction
|
(props) => (
<div>
<ul>
<li>
<label htmlFor="zoomMode">
<FontAwesomeIcon icon
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
ArrowFunction
|
(state: RootState) => ({
isZoomEnabled: getZoomMode(state),
isEditingEventRange: getIsEditingEventRange(state),
})
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
ArrowFunction
|
(dispatch: Function) => ({
zoom: (direction) => dispatch(zoomOnClick(direction)),
zoomToggle: (mode) => dispatch(zoomToggleAction(mode)),
})
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
ArrowFunction
|
(direction) => dispatch(zoomOnClick(direction))
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
ArrowFunction
|
(mode) => dispatch(zoomToggleAction(mode))
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
TypeAliasDeclaration
|
type StateProps = ReturnType<typeof mapState>;
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
TypeAliasDeclaration
|
type DispatchProps = ReturnType<typeof mapDispatch>;
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
TypeAliasDeclaration
|
type ZoomControlsProps = StateProps & DispatchProps;
|
sintel-dev/MTV
|
src/components/Timeseries/FocusChart/ZoomControls.tsx
|
TypeScript
|
ArrowFunction
|
(item) => {
if (id != null && item.id != id)
return false;
if (siteId != null && item.site_id != siteId)
return false;
if (label != null && item.label != label)
return false;
if (udi != null && item.udi != udi)
return false;
if (udis != null && _.indexOf(udis, item.udi) < 0)
return false;
return true;
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ArrowFunction
|
(d) => d.id == beaconId
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ArrowFunction
|
(item) => item.udi == udi
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ArrowFunction
|
(callback) => {
this.getBeacons(
correlationId,
FilterParams.fromTuples(
'site_id', siteId,
'udis', udis
),
null,
(err, page) => {
beacons = page ? page.data : [];
callback(err);
}
);
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ArrowFunction
|
(err, page) => {
beacons = page ? page.data : [];
callback(err);
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ArrowFunction
|
(callback) => {
let lat = 0;
let lng = 0;
let count = 0;
for (let beacon of beacons) {
if (beacon.center != null
&& beacon.center.type == 'Point'
&& _.isArray(beacon.center.coordinates)) {
lng += beacon.center.coordinates[0];
lat += beacon.center.coordinates[1];
count += 1;
}
}
if (count > 0) {
position = {
type: 'Point',
coordinates: [lng / count, lat / count]
}
}
callback();
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ArrowFunction
|
(err) => { callback(err, err == null ? position : null); }
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ArrowFunction
|
(d) => d.id != beacon.id
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ClassDeclaration
|
export class BeaconsMemoryClientV1 implements IBeaconsClientV1 {
private _beacons: BeaconV1[] = [];
private composeFilter(filter: FilterParams): any {
filter = filter || new FilterParams();
let id = filter.getAsNullableString('id');
let siteId = filter.getAsNullableString('site_id');
let label = filter.getAsNullableString('label');
let udi = filter.getAsNullableString('udi');
let udis = filter.getAsObject('udis');
if (_.isString(udis))
udis = udis.split(',');
if (!_.isArray(udis))
udis = null;
return (item) => {
if (id != null && item.id != id)
return false;
if (siteId != null && item.site_id != siteId)
return false;
if (label != null && item.label != label)
return false;
if (udi != null && item.udi != udi)
return false;
if (udis != null && _.indexOf(udis, item.udi) < 0)
return false;
return true;
};
}
public getBeacons(correlationId: string, filter: FilterParams, paging: PagingParams,
callback: (err: any, page: DataPage<BeaconV1>) => void): void {
let beacons = _.filter(this._beacons, this.composeFilter(filter));
callback(null, new DataPage<BeaconV1>(beacons, beacons.length));
}
public getBeaconById(correlationId: string, beaconId: string,
callback: (err: any, beacon: BeaconV1) => void): void {
let beacon = _.find(this._beacons, (d) => d.id == beaconId);
callback(null, beacon);
}
public getBeaconByUdi(correlationId: string, udi: string,
callback: (err: any, beacon: BeaconV1) => void): void {
let beacon = _.find(this._beacons, (item) => item.udi == udi);
callback(null, beacon);
}
public calculatePosition(correlationId: string, siteId: string, udis: string[],
callback: (err: any, position: any) => void): void {
let beacons: BeaconV1[];
let position: any = null;
if (udis == null || udis.length == 0) {
callback(null, null);
return;
}
async.series([
(callback) => {
this.getBeacons(
correlationId,
FilterParams.fromTuples(
'site_id', siteId,
'udis', udis
),
null,
(err, page) => {
beacons = page ? page.data : [];
callback(err);
}
);
},
(callback) => {
let lat = 0;
let lng = 0;
let count = 0;
for (let beacon of beacons) {
if (beacon.center != null
&& beacon.center.type == 'Point'
&& _.isArray(beacon.center.coordinates)) {
lng += beacon.center.coordinates[0];
lat += beacon.center.coordinates[1];
count += 1;
}
}
if (count > 0) {
position = {
type: 'Point',
coordinates: [lng / count, lat / count]
}
}
callback();
}
], (err) => { callback(err, err == null ? position : null); });
}
public createBeacon(correlationId: string, beacon: BeaconV1,
callback: (err: any, beacon: BeaconV1) => void): void {
beacon.id = beacon.id || IdGenerator.nextLong();
beacon.type = beacon.type || "unknown";
this._beacons.push(beacon);
callback(null, beacon);
}
public updateBeacon(correlationId: string, beacon: BeaconV1,
callback: (err: any, beacon: BeaconV1) => void): void {
beacon.type = beacon.type || "unknown";
this._beacons = _.filter(this._beacons, (d) => d.id != beacon.id);
this._beacons.push(beacon);
callback(null, beacon);
}
public deleteBeaconById(correlationId: string, beaconId: string,
callback: (err: any, beacon: BeaconV1) => void): void {
let beacon = _.find(this._beacons, (d) => d.id == beaconId);
if (beacon)
this._beacons = _.filter(this._beacons, (d) => d.id != beacon.id);
callback(null, beacon);
}
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
private composeFilter(filter: FilterParams): any {
filter = filter || new FilterParams();
let id = filter.getAsNullableString('id');
let siteId = filter.getAsNullableString('site_id');
let label = filter.getAsNullableString('label');
let udi = filter.getAsNullableString('udi');
let udis = filter.getAsObject('udis');
if (_.isString(udis))
udis = udis.split(',');
if (!_.isArray(udis))
udis = null;
return (item) => {
if (id != null && item.id != id)
return false;
if (siteId != null && item.site_id != siteId)
return false;
if (label != null && item.label != label)
return false;
if (udi != null && item.udi != udi)
return false;
if (udis != null && _.indexOf(udis, item.udi) < 0)
return false;
return true;
};
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
public getBeacons(correlationId: string, filter: FilterParams, paging: PagingParams,
callback: (err: any, page: DataPage<BeaconV1>) => void): void {
let beacons = _.filter(this._beacons, this.composeFilter(filter));
callback(null, new DataPage<BeaconV1>(beacons, beacons.length));
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
public getBeaconById(correlationId: string, beaconId: string,
callback: (err: any, beacon: BeaconV1) => void): void {
let beacon = _.find(this._beacons, (d) => d.id == beaconId);
callback(null, beacon);
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
public getBeaconByUdi(correlationId: string, udi: string,
callback: (err: any, beacon: BeaconV1) => void): void {
let beacon = _.find(this._beacons, (item) => item.udi == udi);
callback(null, beacon);
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
public calculatePosition(correlationId: string, siteId: string, udis: string[],
callback: (err: any, position: any) => void): void {
let beacons: BeaconV1[];
let position: any = null;
if (udis == null || udis.length == 0) {
callback(null, null);
return;
}
async.series([
(callback) => {
this.getBeacons(
correlationId,
FilterParams.fromTuples(
'site_id', siteId,
'udis', udis
),
null,
(err, page) => {
beacons = page ? page.data : [];
callback(err);
}
);
},
(callback) => {
let lat = 0;
let lng = 0;
let count = 0;
for (let beacon of beacons) {
if (beacon.center != null
&& beacon.center.type == 'Point'
&& _.isArray(beacon.center.coordinates)) {
lng += beacon.center.coordinates[0];
lat += beacon.center.coordinates[1];
count += 1;
}
}
if (count > 0) {
position = {
type: 'Point',
coordinates: [lng / count, lat / count]
}
}
callback();
}
], (err) => { callback(err, err == null ? position : null); });
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
public createBeacon(correlationId: string, beacon: BeaconV1,
callback: (err: any, beacon: BeaconV1) => void): void {
beacon.id = beacon.id || IdGenerator.nextLong();
beacon.type = beacon.type || "unknown";
this._beacons.push(beacon);
callback(null, beacon);
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
public updateBeacon(correlationId: string, beacon: BeaconV1,
callback: (err: any, beacon: BeaconV1) => void): void {
beacon.type = beacon.type || "unknown";
this._beacons = _.filter(this._beacons, (d) => d.id != beacon.id);
this._beacons.push(beacon);
callback(null, beacon);
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
MethodDeclaration
|
public deleteBeaconById(correlationId: string, beaconId: string,
callback: (err: any, beacon: BeaconV1) => void): void {
let beacon = _.find(this._beacons, (d) => d.id == beaconId);
if (beacon)
this._beacons = _.filter(this._beacons, (d) => d.id != beacon.id);
callback(null, beacon);
}
|
pip-templates/pip-templates-facade-node
|
src/clients/version1/BeaconsMemoryClientV1.ts
|
TypeScript
|
ClassDeclaration
|
export class Countdown {
async save() {
console.log('real implementation');
}
}
|
mrdulin/expressjs-research
|
src/stackoverflow/65399764/database/orm.ts
|
TypeScript
|
MethodDeclaration
|
async save() {
console.log('real implementation');
}
|
mrdulin/expressjs-research
|
src/stackoverflow/65399764/database/orm.ts
|
TypeScript
|
ClassDeclaration
|
@Component({
selector: 'app-selected-book',
templateUrl: './selected-book.component.html',
styleUrls: ['./selected-book.component.css']
})
export class SelectedBookComponent implements OnInit {
book$: Observable<IBook>;
isSelectedBookInCollection$: Observable<boolean>;
constructor(private store: Store<fromBooks.IAppState>) {
this.book$ = store.pipe(select(fromBooks.getSelectedBook)) as Observable<
IBook
>;
this.isSelectedBookInCollection$ = store.pipe(
select(fromBooks.isSelectedBookInCollection)
);
}
addToCollection(book: IBook) {
this.store.dispatch(new BookCollectionActions.AddBook(book));
}
removeFromCollection(book: IBook) {
this.store.dispatch(new BookCollectionActions.RemoveBook(book));
}
ngOnInit() {
}
}
|
plotop/google-books
|
src/app/books/containers/selected-book/selected-book.component.ts
|
TypeScript
|
MethodDeclaration
|
addToCollection(book: IBook) {
this.store.dispatch(new BookCollectionActions.AddBook(book));
}
|
plotop/google-books
|
src/app/books/containers/selected-book/selected-book.component.ts
|
TypeScript
|
MethodDeclaration
|
removeFromCollection(book: IBook) {
this.store.dispatch(new BookCollectionActions.RemoveBook(book));
}
|
plotop/google-books
|
src/app/books/containers/selected-book/selected-book.component.ts
|
TypeScript
|
ArrowFunction
|
({state, setState}, e) => setState((s) => ({
...s,
layers: [...s.layers, [3, 60, 4]],
active: s.layers.length,
}))
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(s) => ({
...s,
layers: [...s.layers, [3, 60, 4]],
active: s.layers.length,
})
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
({state, setState}, idx) => setState((s) => {
if(idx === 0) return s
const newLayers = [...s.layers]
newLayers.splice(idx, 1)
return {
...s,
layers: newLayers,
active: newLayers.length - 1,
}
})
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(s) => {
if(idx === 0) return s
const newLayers = [...s.layers]
newLayers.splice(idx, 1)
return {
...s,
layers: newLayers,
active: newLayers.length - 1,
}
}
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
({setState}, e, idx) => setState((s) => ({
...s,
layers: s.layers.map((l, i) => {
if(i === s.active) l[idx] = parseInt(e.target.value)
return l
}),
}))
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(s) => ({
...s,
layers: s.layers.map((l, i) => {
if(i === s.active) l[idx] = parseInt(e.target.value)
return l
}),
})
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(l, i) => {
if(i === s.active) l[idx] = parseInt(e.target.value)
return l
}
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(arr, acc?) => arr.length ? arrChain(arr, acc ? [...arr.pop(), acc] : arr.pop()) : acc
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(host, e) => {
const layer = parseInt(e.target.dataset.layer)
host.setState((s) => ({...s, active: layer}))
}
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(s) => ({...s, active: layer})
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(host, e) => {
console.log(e.detail)
host.mandalaStyles = e.detail
host.mandala.forEach((m) => m.styles = host.mandalaStyles)
}
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(m) => m.styles = host.mandalaStyles
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
ArrowFunction
|
(host, value) => value || {layers: [[3, 60, 5]], active: 0}
|
auzmartist/mandala
|
src/components/mandala-companion.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.