type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
ArrowFunction |
({ term, relayEnvironment, updateFollowCount }) => {
return (
<QueryRenderer<GeneSearchResultsQuery>
environment={relayEnvironment}
query={graphql`
query GeneSearchResultsQuery($term: String!) {
viewer {
...GeneSearchResults_viewer
}
}
`} | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
ClassDeclaration |
@track({}, { dispatch: data => Events.postEvent(data) })
class GeneSearchResultsContent extends React.Component<Props, null> {
private excludedGeneIds: Set<string>
followCount: number = 0
constructor(props: Props, context: any) {
super(props, context)
this.excludedGeneIds = new Set(
this.props.viewer.match_gene.map(item => item._id)
)
}
onGeneFollowed(
gene: Gene,
store: RecordSourceSelectorProxy,
data: GeneSearchResultsFollowGeneMutationResponse
): void {
const suggestedGene = store.get(
data.followGene.gene.similar.edges[0].node.__id
)
this.excludedGeneIds.add(suggestedGene.getValue("_id"))
const suggestedGenesRootField = store.get("client:root:viewer")
const suggestedGenes = suggestedGenesRootField.getLinkedRecords(
"match_gene",
{ term: this.props.term }
)
const updatedSuggestedGenes = suggestedGenes.map(geneItem =>
geneItem.getValue("id") === gene.id ? suggestedGene : geneItem
)
suggestedGenesRootField.setLinkedRecords(
updatedSuggestedGenes,
"match_gene",
{ term: this.props.term }
)
this.followCount += 1
this.props.updateFollowCount(this.followCount)
this.props.tracking.trackEvent({
action: "Followed Gene",
entity_id: gene._id,
entity_slug: gene.id,
context_module: "onboarding search",
})
}
followedGene(gene: Gene) {
this.excludedGeneIds.add(gene._id)
commitMutation<GeneSearchResultsFollowGeneMutation>(
this.props.relay.environment,
{
mutation: graphql`
mutation GeneSearchResultsFollowGeneMutation(
$input: FollowGeneInput!
$excludedGeneIds: [String]!
) {
followGene(input: $input) {
gene {
similar(first: 1, exclude_gene_ids: $excludedGeneIds) {
edges {
node {
id
_id
__id
name
image {
cropped(width: 100, height: 100) {
url
}
}
}
}
}
}
}
}
`,
variables: {
input: {
gene_id: gene.id,
},
excludedGeneIds: Array.from(this.excludedGeneIds),
},
updater: (store, data) => this.onGeneFollowed(gene, store, data),
}
)
}
render() {
const items = this.props.viewer.match_gene.map((item, index) => {
const imageUrl = get(item, i => i.image.cropped.url)
return (
<LinkContainer key={`gene-search-results-${index}`}>
<ReplaceTransition
transitionEnterTimeout={1000}
transitionLeaveTimeout={400}
>
<ItemLink
href="#"
item={item}
key={item.id}
id={item.id}
name={item.name}
image_url={imageUrl}
onClick={() => this.followedGene(item)} | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
InterfaceDeclaration |
interface ContainerProps extends FollowProps {
term: string
} | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
InterfaceDeclaration |
interface Props extends React.HTMLProps<HTMLAnchorElement>, ContainerProps {
tracking?: TrackingProp
relay?: RelayProp
viewer: GeneSearchResults_viewer
} | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
TypeAliasDeclaration |
type Gene = GeneSearchResults_viewer["match_gene"][0] | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
MethodDeclaration |
onGeneFollowed(
gene: Gene,
store: RecordSourceSelectorProxy,
data: GeneSearchResultsFollowGeneMutationResponse
): void {
const suggestedGene = store.get(
data.followGene.gene.similar.edges[0].node.__id
)
this.excludedGeneIds.add(suggestedGene.getValue("_id"))
const suggestedGenesRootField = store.get("client:root:viewer")
const suggestedGenes = suggestedGenesRootField.getLinkedRecords(
"match_gene",
{ term: this.props.term }
)
const updatedSuggestedGenes = suggestedGenes.map(geneItem =>
geneItem.getValue("id") === gene.id ? suggestedGene : geneItem
)
suggestedGenesRootField.setLinkedRecords(
updatedSuggestedGenes,
"match_gene",
{ term: this.props.term }
)
this.followCount += 1
this.props.updateFollowCount(this.followCount)
this.props.tracking.trackEvent({
action: "Followed Gene",
entity_id: gene._id,
entity_slug: gene.id,
context_module: "onboarding search",
})
} | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
MethodDeclaration |
followedGene(gene: Gene) {
this.excludedGeneIds.add(gene._id)
commitMutation<GeneSearchResultsFollowGeneMutation>(
this.props.relay.environment,
{
mutation: graphql`
mutation GeneSearchResultsFollowGeneMutation(
$input: FollowGeneInput!
$excludedGeneIds: [String]!
) {
followGene(input: $input) {
gene {
similar(first: 1, exclude_gene_ids: $excludedGeneIds) {
edges {
node {
id
_id
__id
name
image {
cropped(width: 100, height: 100) {
url
}
}
}
}
}
}
}
}
`,
variables: {
input: {
gene_id: gene.id,
},
excludedGeneIds: Array.from(this.excludedGeneIds),
},
updater: (store, data) => this.onGeneFollowed(gene, store, data),
}
)
} | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
MethodDeclaration |
render() {
const items = this.props.viewer.match_gene.map((item, index) => {
const imageUrl = get(item, i => i.image.cropped.url)
return (
<LinkContainer key={`gene-search-results-${index}`}>
<ReplaceTransition
transitionEnterTimeout={1000}
transitionLeaveTimeout={400}
>
<ItemLink
href="#"
item={item}
key={item.id}
id={item.id}
name={item.name}
image_url={imageUrl}
onClick={() => this.followedGene(item)} | fossabot/reaction-1 | src/Components/Onboarding/Steps/Genes/GeneSearchResults.tsx | TypeScript |
ArrowFunction |
config => {
const solarTheme: any = config.variables.solar;
this.option = Object.assign({}, {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)',
},
series: [
{
name: ' ',
clockWise: true,
hoverAnimation: false,
type: 'pie',
center: ['45%', '50%'],
radius: solarTheme.radius,
data: [
{
value: this.value,
name: ' ',
label: {
normal: {
position: 'center',
formatter: '{d}%',
textStyle: {
fontSize: '22',
fontFamily: config.variables.fontSecondary,
fontWeight: '600',
color: config.variables.fgHeading,
},
},
},
tooltip: {
show: false,
},
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: solarTheme.gradientLeft,
},
{
offset: 1,
color: solarTheme.gradientRight,
},
]),
shadowColor: solarTheme.shadowColor,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 3,
},
},
hoverAnimation: false,
},
{
value: 100 - this.value,
name: ' ',
tooltip: {
show: false,
},
label: {
normal: {
position: 'inner',
},
},
itemStyle: {
normal: {
color: config.variables.layoutBg,
},
},
},
],
},
{
name: ' ',
clockWise: true,
hoverAnimation: false,
type: 'pie',
center: ['45%', '50%'],
radius: solarTheme.radius,
data: [
{
value: this.value,
name: ' ',
label: {
normal: {
position: 'inner',
show: false,
},
},
tooltip: {
show: false,
},
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: solarTheme.gradientLeft,
},
{
offset: 1,
color: solarTheme.gradientRight,
},
]),
shadowColor: solarTheme.shadowColor,
shadowBlur: 7,
},
},
hoverAnimation: false,
},
{
value: 28,
name: ' ',
tooltip: {
show: false,
},
label: {
normal: {
position: 'inner',
},
},
itemStyle: {
normal: {
color: 'none',
},
},
},
],
},
],
});
} | misupopo/band-admin | src/app/pages/dashboard/solar/solar.component.ts | TypeScript |
ClassDeclaration |
@Component({
selector: 'ngx-solar',
styleUrls: ['./solar.component.scss'],
template: `
<nb-card size="xsmall" class="solar-card">
<nb-card-header>Solar Energy Consumption</nb-card-header>
<nb-card-body>
<div echarts [options]="option" class="echart">
</div>
<div class="info">
<div class="value">6. 421 kWh</div>
<div class="details"><span>out of</span> 8.421 kWh</div>
</div>
</nb-card-body>
</nb-card>
`,
})
export class SolarComponent implements AfterViewInit, OnDestroy {
private value = 0;
@Input('chartValue')
set chartValue(value: number) {
this.value = value;
if (this.option.series) {
this.option.series[0].data[0].value = value;
this.option.series[0].data[1].value = 100 - value;
this.option.series[1].data[0].value = value;
}
}
option: any = {};
themeSubscription: any;
constructor(private theme: NbThemeService) {
}
ngAfterViewInit() {
this.themeSubscription = this.theme.getJsTheme().delay(1).subscribe(config => {
const solarTheme: any = config.variables.solar;
this.option = Object.assign({}, {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)',
},
series: [
{
name: ' ',
clockWise: true,
hoverAnimation: false,
type: 'pie',
center: ['45%', '50%'],
radius: solarTheme.radius,
data: [
{
value: this.value,
name: ' ',
label: {
normal: {
position: 'center',
formatter: '{d}%',
textStyle: {
fontSize: '22',
fontFamily: config.variables.fontSecondary,
fontWeight: '600',
color: config.variables.fgHeading,
},
},
},
tooltip: {
show: false,
},
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: solarTheme.gradientLeft,
},
{
offset: 1,
color: solarTheme.gradientRight,
},
]),
shadowColor: solarTheme.shadowColor,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 3,
},
},
hoverAnimation: false,
},
{
value: 100 - this.value,
name: ' ',
tooltip: {
show: false,
},
label: {
normal: {
position: 'inner',
},
},
itemStyle: {
normal: {
color: config.variables.layoutBg,
},
},
},
],
},
{
name: ' ',
clockWise: true,
hoverAnimation: false,
type: 'pie',
center: ['45%', '50%'],
radius: solarTheme.radius,
data: [
{
value: this.value,
name: ' ',
label: {
normal: {
position: 'inner',
show: false,
},
},
tooltip: {
show: false,
},
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: solarTheme.gradientLeft,
},
{
offset: 1,
color: solarTheme.gradientRight,
},
]),
shadowColor: solarTheme.shadowColor,
shadowBlur: 7,
},
},
hoverAnimation: false,
},
{
value: 28,
name: ' ',
tooltip: {
show: false,
},
label: {
normal: {
position: 'inner',
},
},
itemStyle: {
normal: {
color: 'none',
},
},
},
],
},
],
});
});
}
ngOnDestroy() {
this.themeSubscription.unsubscribe();
}
} | misupopo/band-admin | src/app/pages/dashboard/solar/solar.component.ts | TypeScript |
MethodDeclaration |
ngAfterViewInit() {
this.themeSubscription = this.theme.getJsTheme().delay(1).subscribe(config => {
const solarTheme: any = config.variables.solar;
this.option = Object.assign({}, {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)',
},
series: [
{
name: ' ',
clockWise: true,
hoverAnimation: false,
type: 'pie',
center: ['45%', '50%'],
radius: solarTheme.radius,
data: [
{
value: this.value,
name: ' ',
label: {
normal: {
position: 'center',
formatter: '{d}%',
textStyle: {
fontSize: '22',
fontFamily: config.variables.fontSecondary,
fontWeight: '600',
color: config.variables.fgHeading,
},
},
},
tooltip: {
show: false,
},
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: solarTheme.gradientLeft,
},
{
offset: 1,
color: solarTheme.gradientRight,
},
]),
shadowColor: solarTheme.shadowColor,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 3,
},
},
hoverAnimation: false,
},
{
value: 100 - this.value,
name: ' ',
tooltip: {
show: false,
},
label: {
normal: {
position: 'inner',
},
},
itemStyle: {
normal: {
color: config.variables.layoutBg,
},
},
},
],
},
{
name: ' ',
clockWise: true,
hoverAnimation: false,
type: 'pie',
center: ['45%', '50%'],
radius: solarTheme.radius,
data: [
{
value: this.value,
name: ' ',
label: {
normal: {
position: 'inner',
show: false,
},
},
tooltip: {
show: false,
},
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: solarTheme.gradientLeft,
},
{
offset: 1,
color: solarTheme.gradientRight,
},
]),
shadowColor: solarTheme.shadowColor,
shadowBlur: 7,
},
},
hoverAnimation: false,
},
{
value: 28,
name: ' ',
tooltip: {
show: false,
},
label: {
normal: {
position: 'inner',
},
},
itemStyle: {
normal: {
color: 'none',
},
},
},
],
},
],
});
});
} | misupopo/band-admin | src/app/pages/dashboard/solar/solar.component.ts | TypeScript |
MethodDeclaration |
ngOnDestroy() {
this.themeSubscription.unsubscribe();
} | misupopo/band-admin | src/app/pages/dashboard/solar/solar.component.ts | TypeScript |
ArrowFunction |
(e: React.MouseEvent<HTMLElement>, href: string) => {
e.preventDefault();
this.props.history.replace(href);
} | timcowebapps/react.toolkit-guides | src/views/components/button/index.tsx | TypeScript |
ArrowFunction |
(e: React.MouseEvent<HTMLElement>, href: string) => {
e.preventDefault();
this.props.history.replace(href);
} | timcowebapps/react.toolkit-guides | src/views/components/button/index.tsx | TypeScript |
ClassDeclaration |
export class ButtonComp extends React.Component<ButtonCompProps.IProps, ButtonCompState.IState> {
//#region Статические переменные
public static displayName: string = "ButtonComp";
public static propTypes: PropTypes.ValidationMap<ButtonCompProps.IProps> = ButtonCompProps.types;
public static defaultProps: ButtonCompProps.IProps = ButtonCompProps.defaults;
//#endregion
//#region Приватные переменные
//#endregion
//#region Приватные методы
/**
* Начальное состояние свойств по умолчанию.
*
* @class ButtonComp
* @private
*/
private _getInitialState(): ButtonCompState.IState {
return {
// Empty
}
}
private _handleClick(event: any) {
// Empty
}
//#endregion
/**
* Конструктор класса.
*
* @class ButtonComp
* @public
* @constructor
* @param {ButtonCompProps.IProps} props Свойства компонента.
*/
public constructor(props?: ButtonCompProps.IProps) {
super(props);
this.state = this._getInitialState();
}
/**
* Отрисовывает компонент.
*
* @class ButtonComp
* @public
*/
public render(): JSX.Element {
return (
<Layout>
<div className={styles["container-fluid"]}>
<div className={CN.many(
styles["row"],
Methodology.Bem.Entities.block(styles, "spacing-above").element().modifiers(["sm"]),
Methodology.Bem.Entities.block(styles, "spacing-below").element().modifiers(["sm"])
)}>
<div className={Methodology.Bem.Entities.block(styles, "col").element().modifiers(["xs-12", "sm-12", "md-12", "lg-12"])}>
<Heading {...{
requirements: {
htmlTag: HtmlTagTypes.H1,
align: AlignTransform.toStr(AlignTypes.Left),
viewStyle: { stylesheet: headingStyles, bem: { block: "heading" } }
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Кнопка"
}
}]
}} />
<p>Используется для создания различных типов кнопок.</p>
<p>Смотри: <Hyperlink {...{
requirements: {
to: RouteConstants.Home,
onClick: (e: React.MouseEvent<HTMLElement>, href: string) => {
e.preventDefault();
this.props.history.replace(href);
},
viewStyle: { stylesheet: linkStyles, bem: { block: "link" } },
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Icon"
}
}]
}} /></p>
<div className={styles["component-preview"]}>
<Button {...{
requirements: {
htmlTag: HtmlTagTypes.Button,
onClick: this._handleClick,
viewStyle: { stylesheet: buttonStyles, bem: { block: "btn", modifiers: ["primary"] }, extracts: "block" }
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Block"
}
}]
}} />
</div>
<p><code>{"import { Button } from '@timcowebapps/react.toolkit'"}</code></p>
<Heading {...{
requirements: {
htmlTag: HtmlTagTypes.H2,
align: AlignTransform.toStr(AlignTypes.Left),
viewStyle: { stylesheet: headingStyles, bem: { block: "heading" } }
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Схема компонента"
}
}]
}} />
<table>
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>uid</code></td>
<td>String</td>
<td>Уникальный идентификатор компонента</td>
</tr>
<tr>
<td><code>requirements.htmlTag</code></td>
<td>Number</td>
<td>Html тег элемента. Допустимые значения <Hyperlink {...{
requirements: {
to: RouteConstants.Home,
onClick: (e: React.MouseEvent<HTMLElement>, href: string) => {
e.preventDefault();
this.props.history.replace(href);
},
viewStyle: { stylesheet: linkStyles, bem: { block: "link" } },
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "HtmlTagTypes"
}
}]
}} /> перечислителя: <code>HtmlTagTypes.Button</code> (по умолчанию), <code>HtmlTagTypes.A</code></td>
</tr>
<tr>
<td><code>requirements.onClick</code></td>
<td>Function</td>
<td>Обработчик клика по кнопке</td>
</tr>
<tr>
<td><code>requirements.value</code></td>
<td>String</td>
<td>Значение</td>
</tr>
<tr>
<td><code>requirements.viewStyle.stylesheet</code></td>
<td>Object</td>
<td>Карта каскадных стилей</td>
</tr>
<tr>
<td><code>requirements.viewStyle.bem.block</code></td>
<td>String</td>
<td>Имя блока</td>
</tr>
<tr>
<td><code>requirements.viewStyle.bem.modifiers</code></td>
<td>Array<String></td>
<td>Имена модификаторов</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</Layout>
);
}
} | timcowebapps/react.toolkit-guides | src/views/components/button/index.tsx | TypeScript |
MethodDeclaration | //#endregion
//#region Приватные переменные
//#endregion
//#region Приватные методы
/**
* Начальное состояние свойств по умолчанию.
*
* @class ButtonComp
* @private
*/
private _getInitialState(): ButtonCompState.IState {
return {
// Empty
}
} | timcowebapps/react.toolkit-guides | src/views/components/button/index.tsx | TypeScript |
MethodDeclaration |
private _handleClick(event: any) {
// Empty
} | timcowebapps/react.toolkit-guides | src/views/components/button/index.tsx | TypeScript |
MethodDeclaration | /**
* Отрисовывает компонент.
*
* @class ButtonComp
* @public
*/
public render(): JSX.Element {
return (
<Layout>
<div className={styles["container-fluid"]}>
<div className={CN.many(
styles["row"],
Methodology.Bem.Entities.block(styles, "spacing-above").element().modifiers(["sm"]),
Methodology.Bem.Entities.block(styles, "spacing-below").element().modifiers(["sm"])
)}>
<div className={Methodology.Bem.Entities.block(styles, "col").element().modifiers(["xs-12", "sm-12", "md-12", "lg-12"])}>
<Heading {...{
requirements: {
htmlTag: HtmlTagTypes.H1,
align: AlignTransform.toStr(AlignTypes.Left),
viewStyle: { stylesheet: headingStyles, bem: { block: "heading" } }
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Кнопка"
}
}]
}} />
<p>Используется для создания различных типов кнопок.</p>
<p>Смотри: <Hyperlink {...{
requirements: {
to: RouteConstants.Home,
onClick: (e: React.MouseEvent<HTMLElement>, href: string) => {
e.preventDefault();
this.props.history.replace(href);
},
viewStyle: { stylesheet: linkStyles, bem: { block: "link" } },
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Icon"
}
}]
}} /></p>
<div className={styles["component-preview"]}>
<Button {...{
requirements: {
htmlTag: HtmlTagTypes.Button,
onClick: this._handleClick,
viewStyle: { stylesheet: buttonStyles, bem: { block: "btn", modifiers: ["primary"] }, extracts: "block" }
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Block"
}
}]
}} />
</div>
<p><code>{"import { Button } from '@timcowebapps/react.toolkit'"}</code></p>
<Heading {...{
requirements: {
htmlTag: HtmlTagTypes.H2,
align: AlignTransform.toStr(AlignTypes.Left),
viewStyle: { stylesheet: headingStyles, bem: { block: "heading" } }
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "Схема компонента"
}
}]
}} />
<table>
<thead>
<tr>
<th>Свойство</th>
<th>Тип</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>uid</code></td>
<td>String</td>
<td>Уникальный идентификатор компонента</td>
</tr>
<tr>
<td><code>requirements.htmlTag</code></td>
<td>Number</td>
<td>Html тег элемента. Допустимые значения <Hyperlink {...{
requirements: {
to: RouteConstants.Home,
onClick: (e: React.MouseEvent<HTMLElement>, href: string) => {
e.preventDefault();
this.props.history.replace(href);
},
viewStyle: { stylesheet: linkStyles, bem: { block: "link" } },
},
items: [{
type: Data.Schema.ComponentTypes.Node,
requirements: {
content: "HtmlTagTypes"
}
}]
}} /> перечислителя: <code>HtmlTagTypes.Button</code> (по умолчанию), <code>HtmlTagTypes.A</code></td>
</tr>
<tr>
<td><code>requirements.onClick</code></td>
<td>Function</td>
<td>Обработчик клика по кнопке</td>
</tr>
<tr>
<td><code>requirements.value</code></td>
<td>String</td>
<td>Значение</td>
</tr>
<tr>
<td><code>requirements.viewStyle.stylesheet</code></td>
<td>Object</td>
<td>Карта каскадных стилей</td>
</tr>
<tr>
<td><code>requirements.viewStyle.bem.block</code></td>
<td>String</td>
<td>Имя блока</td>
</tr>
<tr>
<td><code>requirements.viewStyle.bem.modifiers</code></td>
<td>Array<String></td>
<td>Имена модификаторов</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</Layout>
);
} | timcowebapps/react.toolkit-guides | src/views/components/button/index.tsx | TypeScript |
ArrowFunction |
(plant: PlantsEdge) => {
/* eslint-disable no-case-declarations */
switch (plant.node.parentVegetable.contentfulid.substring(0, 1).toLowerCase()) {
case 'v':
let vegetablesInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[0].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (vegetablesInFamilies === undefined) {
vegetablesInFamilies = {}
vegetablesInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[0].subplants.push(vegetablesInFamilies)
}
vegetablesInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'f':
let fruitsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[1].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (fruitsInFamilies === undefined) {
fruitsInFamilies = {}
fruitsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[1].subplants.push(fruitsInFamilies)
}
fruitsInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'h':
let herbsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[2].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (herbsInFamilies === undefined) {
herbsInFamilies = {}
herbsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[2].subplants.push(herbsInFamilies)
}
herbsInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'g':
let grainsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[3].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (grainsInFamilies === undefined) {
grainsInFamilies = {}
grainsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[3].subplants.push(grainsInFamilies)
}
grainsInFamilies[plant.node.parentVegetable.name].push(plant)
break
default:
return
}
} | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
ArrowFunction |
parentVege => {
return parentVege[plant.node.parentVegetable.name]
} | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
ArrowFunction |
(vegetableParent, vegParentIndex) => {
return (
<div key={vegParentIndex}>
{vegetableParent.type.toLowerCase() === 'vegetables' && (
<ArticleImageParent key={vegParentIndex}>
<ArticleInside
style={{
backgroundImage: `url("//images.ctfassets.net/ce6fbxhy1t51/1ivQJbUcXJJUiHGiL9d4tN/9566fedf02d1c8c22c9dd3b840807c6f/asparagus-raw.jpg")`,
}}
/>
<OverlayContainer>
<ArticleOverlay key={vegParentIndex}>
<h3>sdfdsds</h3>
<ArticleDescription>sdfdsfd</ArticleDescription>
</ArticleOverlay>
</OverlayContainer>
</ArticleImageParent> | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
ArrowFunction |
(vegPlant, index) => {
return (
<div className="container" key={index}>
{Object.keys(vegPlant).map((key, index) => {
return (
<div key={index}>
<VegetableGroup>
<VegetableGroupTitle>{key}</VegetableGroupTitle>
<div className="row">
{vegPlant[key].map((plant: PlantsEdge, index: number) => {
return (
<div className="col4" key={index}>
<LazyLoad
style={{ width: '100%', backgroundColor: '#fefefe' }}
once
offset={100}
>
<picture>
<source
type="image/webp"
srcSet={`${plant.node.bannerImage.file.url}?fm=webp&q=70&w=${Math.round(
windowWidth,
)}&h=${Math.round(windowWidth)}&fit=fill`}
/>
<source
type="image/jpg"
srcSet={`${plant.node.bannerImage.file.url}?fm=jpg&q=70&w=${Math.round(
windowWidth,
)}&h=${Math.round(windowWidth)}&fit=fill`}
/>
<img
src={`${plant.node.bannerImage.file.url}?fm=jpg&q=70&w=${Math.round(
windowWidth,
)}&h=${Math.round(windowWidth)}&fit=fill`}
alt={plant.node.bannerImage.title}
/>
</picture>
</LazyLoad>
<VegetableTitle className="center">{plant.node.title}</VegetableTitle>
<PrimaryButton>Learn More</PrimaryButton>
</div>
)
} | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
ArrowFunction |
(key, index) => {
return (
<div key={index}>
<VegetableGroup>
<VegetableGroupTitle>{key}</VegetableGroupTitle>
<div className="row">
{vegPlant[key].map((plant: PlantsEdge, index: number) => {
return (
<div className="col4" key={index}>
<LazyLoad
style={{ width: '100%', backgroundColor: '#fefefe' }}
once
offset={100}
>
<picture>
<source
type="image/webp"
srcSet={`${plant.node.bannerImage.file.url}?fm=webp&q=70&w=${Math.round(
windowWidth,
)}&h=${Math.round(windowWidth)}&fit=fill`}
/>
<source
type="image/jpg"
srcSet={`${plant.node.bannerImage.file.url}?fm=jpg&q=70&w=${Math.round(
windowWidth,
)}&h=${Math.round(windowWidth)}&fit=fill`}
/>
<img
src={`${plant.node.bannerImage.file.url}?fm=jpg&q=70&w=${Math.round(
windowWidth,
)}&h=${Math.round(windowWidth)}&fit=fill`}
alt={plant.node.bannerImage.title}
/>
</picture>
</LazyLoad>
<VegetableTitle className="center">{plant.node.title}</VegetableTitle>
<PrimaryButton>Learn More</PrimaryButton>
</div> | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
ArrowFunction |
(plant: PlantsEdge, index: number) => {
return (
<div className="col4" key={index}>
<LazyLoad
style={{ width: '100%', backgroundColor: '#fefefe' }}
once
offset={100}
>
<picture>
<source
type="image/webp"
srcSet={`${plant.node.bannerImage.file.url}?fm=webp&q=70&w=${Math.round(
windowWidth,
)}&h=${Math.round(windowWidth)}&fit=fill`} | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
ClassDeclaration |
class PlantsIndex extends React.Component<PlantsProps> {
render() {
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-undef */
const contentful = require('contentful')
const contentfulConfig = require('../../.contentful.json')
/* eslint-enable @typescript-eslint/no-var-requires */
/* eslint-enable no-undef */
const posts: PlantsEdge[] = get(this, 'props.data.allContentfulVegetable.edges')
const vegetablesByParent = [
{
type: 'Vegetables',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
{
type: 'Fruits',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
{
type: 'Herbs',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
{
type: 'Grains',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
]
posts.map((plant: PlantsEdge) => {
/* eslint-disable no-case-declarations */
switch (plant.node.parentVegetable.contentfulid.substring(0, 1).toLowerCase()) {
case 'v':
let vegetablesInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[0].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (vegetablesInFamilies === undefined) {
vegetablesInFamilies = {}
vegetablesInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[0].subplants.push(vegetablesInFamilies)
}
vegetablesInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'f':
let fruitsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[1].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (fruitsInFamilies === undefined) {
fruitsInFamilies = {}
fruitsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[1].subplants.push(fruitsInFamilies)
}
fruitsInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'h':
let herbsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[2].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (herbsInFamilies === undefined) {
herbsInFamilies = {}
herbsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[2].subplants.push(herbsInFamilies)
}
herbsInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'g':
let grainsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[3].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (grainsInFamilies === undefined) {
grainsInFamilies = {}
grainsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[3].subplants.push(grainsInFamilies)
}
grainsInFamilies[plant.node.parentVegetable.name].push(plant)
break
default:
return
}
})
const BodyCopy = styled.div`
column-count: 2;
column-gap: 40px;
color: #464646;
font-size: 1em;
font-family: 'Roboto', sans-serif;
line-height: 2em;
padding-top: 1.875em;
padding-bottom: 1.875em;
text-align: justify;
`
const VideoBackgroundContainer = styled.div`
position: relative;
overflow: hidden;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
`
const HeroVideo = styled.video`
position: absolute;
z-index: 99;
max-width: 100%;
`
const ArticleInside = styled.div`
display: block;
background-size: cover;
background-repeat: no-repeat;
padding-top: 56%;
-ms-transform: scale(1);
-moz-transform: scale(1);
-webkit-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
transition: all 1s;
&::before {
position: absolute;
content: ' ';
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
z-index: 0;
background-color: rgba(51, 51, 51, 0.25);
}
`
const ArticleImageParent = styled.div`
width: 100%;
overflow: hidden;
position: relative;
`
const ArticleOverlay = styled.div`
position: absolute;
z-index: 999;
bottom: 20px;
left: 20px;
width: calc(100% - 40px);
color: #fff;
`
const OverlayContainer = styled.div`
position: absolute;
width: 100%;
height: 100%;
top: 0;
bottom: 20px;
overflow: hidden;
`
const ArticleDescription = styled.div`
font-family: 'Roboto', sans-serif;
font-size: 12px;
font-weight: 300;
color: #fff;
height: 100px;
max-height: 100px;
display: block;
padding-top: 20px;
`
const VegetableGroup = styled.div`
padding-top: 20px;
padding-bottom: 40px;
`
const VegetableGroupTitle = styled.h2`
font-family: 'Roboto', sans-serif;
font-size: 1.5em;
font-weight: 600;
color: #333;
display: block;
`
const VegetableTitle = styled.h2`
font-family: 'Roboto', sans-serif;
font-size: 1em;
font-weight: 300;
color: #333;
display: block;
`
const PrimaryButton = styled.button`
background-color: #0f9114;
border: none;
font-family: 'Roboto', sans-serif;
font-size: 0.75rem;
color: #fff;
text-align: center;
margin: 20px auto;
display: block;
font-weight: 600;
text-transform: uppercase;
padding: 15px 25px;
letter-spacing: 2px;
`
const windowWidth = typeof window !== 'undefined' ? window.innerWidth : 900
return (
<Layout>
<div style={{ background: '#fff', paddingTop: '250px', position: 'absolute', top: '0', width: '100%' }} | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
MethodDeclaration |
render() {
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-undef */
const contentful = require('contentful')
const contentfulConfig = require('../../.contentful.json')
/* eslint-enable @typescript-eslint/no-var-requires */
/* eslint-enable no-undef */
const posts: PlantsEdge[] = get(this, 'props.data.allContentfulVegetable.edges')
const vegetablesByParent = [
{
type: 'Vegetables',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
{
type: 'Fruits',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
{
type: 'Herbs',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
{
type: 'Grains',
subplants: new Array<{ [id: string]: PlantsEdge[] }>(),
},
]
posts.map((plant: PlantsEdge) => {
/* eslint-disable no-case-declarations */
switch (plant.node.parentVegetable.contentfulid.substring(0, 1).toLowerCase()) {
case 'v':
let vegetablesInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[0].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (vegetablesInFamilies === undefined) {
vegetablesInFamilies = {}
vegetablesInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[0].subplants.push(vegetablesInFamilies)
}
vegetablesInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'f':
let fruitsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[1].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (fruitsInFamilies === undefined) {
fruitsInFamilies = {}
fruitsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[1].subplants.push(fruitsInFamilies)
}
fruitsInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'h':
let herbsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[2].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (herbsInFamilies === undefined) {
herbsInFamilies = {}
herbsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[2].subplants.push(herbsInFamilies)
}
herbsInFamilies[plant.node.parentVegetable.name].push(plant)
break
case 'g':
let grainsInFamilies: { [id: string]: PlantsEdge[] } | undefined = vegetablesByParent[3].subplants.find(
parentVege => {
return parentVege[plant.node.parentVegetable.name]
},
)
if (grainsInFamilies === undefined) {
grainsInFamilies = {}
grainsInFamilies[plant.node.parentVegetable.name] = []
vegetablesByParent[3].subplants.push(grainsInFamilies)
}
grainsInFamilies[plant.node.parentVegetable.name].push(plant)
break
default:
return
}
})
const BodyCopy = styled.div`
column-count: 2;
column-gap: 40px;
color: #464646;
font-size: 1em;
font-family: 'Roboto', sans-serif;
line-height: 2em;
padding-top: 1.875em;
padding-bottom: 1.875em;
text-align: justify;
`
const VideoBackgroundContainer = styled.div`
position: relative;
overflow: hidden;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
`
const HeroVideo = styled.video`
position: absolute;
z-index: 99;
max-width: 100%;
`
const ArticleInside = styled.div`
display: block;
background-size: cover;
background-repeat: no-repeat;
padding-top: 56%;
-ms-transform: scale(1);
-moz-transform: scale(1);
-webkit-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
transition: all 1s;
&::before {
position: absolute;
content: ' ';
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
z-index: 0;
background-color: rgba(51, 51, 51, 0.25);
}
`
const ArticleImageParent = styled.div`
width: 100%;
overflow: hidden;
position: relative;
`
const ArticleOverlay = styled.div`
position: absolute;
z-index: 999;
bottom: 20px;
left: 20px;
width: calc(100% - 40px);
color: #fff;
`
const OverlayContainer = styled.div`
position: absolute;
width: 100%;
height: 100%;
top: 0;
bottom: 20px;
overflow: hidden;
`
const ArticleDescription = styled.div`
font-family: 'Roboto', sans-serif;
font-size: 12px;
font-weight: 300;
color: #fff;
height: 100px;
max-height: 100px;
display: block;
padding-top: 20px;
`
const VegetableGroup = styled.div`
padding-top: 20px;
padding-bottom: 40px;
`
const VegetableGroupTitle = styled.h2`
font-family: 'Roboto', sans-serif;
font-size: 1.5em;
font-weight: 600;
color: #333;
display: block;
`
const VegetableTitle = styled.h2`
font-family: 'Roboto', sans-serif;
font-size: 1em;
font-weight: 300;
color: #333;
display: block;
`
const PrimaryButton = styled.button`
background-color: #0f9114;
border: none;
font-family: 'Roboto', sans-serif;
font-size: 0.75rem;
color: #fff;
text-align: center;
margin: 20px auto;
display: block;
font-weight: 600;
text-transform: uppercase;
padding: 15px 25px;
letter-spacing: 2px;
`
const windowWidth = typeof window !== 'undefined' ? window.innerWidth : 900
return (
<Layout>
<div style={{ background: '#fff', paddingTop: '250px', position: 'absolute', top: '0', width: '100%' }} | buffaloproject1/prepper | src/pages/plants.tsx | TypeScript |
ArrowFunction |
async (req: Request, res: Response) =>{
try {
const getVideosDetaisUC = new VideoDetailsUC(new VideosDetailsDB())
const result = await getVideosDetaisUC.execute({videoId: req.params.videoId})
res.status(200).send(result)
} catch (error) {
res.status(400).send(error.message)
}
} | edu-mendes/FutureTube | functions/src/endpoints/getVideosDetailsEP.ts | TypeScript |
ArrowFunction |
(props: Props) => {
return (
<>
<Point>
<div data-guide='1'>1번</div>
<div data-guide='2'>2번</div>
<div data-guide='3'>3번</div>
<div data-guide='4'>4번</div>
<div data-guide='5'>5번</div>
<div data-guide='6'>6번</div>
<div data-guide='7'>7번</div>
<div data-guide='8'>8번</div>
<div data-guide='9'>8번</div>
<div data-guide='10'>8번</div>
<div data-guide='11'>8번</div>
<div data-guide='12'>8번</div>
</Point>
<Instruction
show={true}
items={[
{
groupNumber: 0,
type: 'topLeft',
selector: '[data-guide="1"]',
message: '1번 입니다.',
},
{
groupNumber: 0,
type: 'topRight',
selector: '[data-guide="2"]',
message: '2번 입니다.',
},
{
groupNumber: 0,
type: 'bottomLeft',
selector: '[data-guide="3"]',
message: '3번 입니다.',
},
{
groupNumber: 0,
type: 'bottomRight',
selector: '[data-guide="4"]',
message: '4번 입니다.',
},
{
groupNumber: 0,
type: 'left-to-topLeft',
selector: '[data-guide="5"]',
message: '5번 입니다.',
},
{
groupNumber: 0,
type: 'left-to-topRight',
selector: '[data-guide="6"]',
message: '6번 입니다.',
},
{
groupNumber: 0,
type: 'left-to-bottomLeft',
selector: '[data-guide="7"]',
message: '7번 입니다.',
},
{
groupNumber: 0,
type: 'left-to-bottomRight',
selector: '[data-guide="8"]',
message: '8번 입니다.',
},
{
groupNumber: 0,
type: 'right-to-topLeft',
selector: '[data-guide="9"]',
message: '5번 입니다.',
},
{
groupNumber: 0,
type: 'right-to-topRight',
selector: '[data-guide="10"]',
message: '6번 입니다.',
},
{
groupNumber: 0,
type: 'right-to-bottomLeft',
selector: '[data-guide="11"]',
message: '7번 입니다.',
},
{
groupNumber: 0,
type: 'right-to-bottomRight',
selector: '[data-guide="12"]',
message: '8번 입니다.',
},
]}
/>
</> | HorongD/Component | src/components/pages/InstructionTest.tsx | TypeScript |
ClassDeclaration |
@Component({
selector: 'example-call-control-active',
template: `
<md-call-control
type="microphone-muted"
ariaLabel="For the Win"
[active]="true"
(click)="onClick()"
></md-call-control>
`,
})
export class ExampleCallControlActiveComponent {
constructor() {}
onClick() {
alert('click');
}
} | AMANDUA/collab-ui | angular/src/lib/call-control/examples/active.component.ts | TypeScript |
MethodDeclaration |
onClick() {
alert('click');
} | AMANDUA/collab-ui | angular/src/lib/call-control/examples/active.component.ts | TypeScript |
ArrowFunction |
event => event instanceof NavigationEnd | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ArrowFunction |
() => this.activatedRoute | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ArrowFunction |
route => {
while (route.firstChild) route = route.firstChild;
return route;
} | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ArrowFunction |
route => route.outlet === 'primary' | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ArrowFunction |
route => route.params | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ArrowFunction |
params => this.getNamespace(params) | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ArrowFunction |
n => n | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ClassDeclaration |
@Injectable()
export class NamespaceScope implements INamespaceScope {
public namespace: Observable<string>;
constructor(protected activatedRoute: ActivatedRoute, protected router: Router) {
this.namespace = this.router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map(
route => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter(route => route.outlet === 'primary')
.mergeMap(route => route.params).map(params => this.getNamespace(params)).filter(n => n).distinctUntilChanged();
}
protected getNamespace(params) {
return params['namespace'] || this.getRouteParams('namespace');
}
protected getRouteParams(key): any {
if (
this.router &&
this.router.routerState &&
this.router.routerState.snapshot &&
this.router.routerState.snapshot.root
) {
return this.findParamsFor(this.router.routerState.snapshot.root, key);
}
return null;
}
protected findParamsFor(route, key): any {
let children = route.children;
for (let child of children) {
let params = child.params;
if (params) {
let answer = params[key];
if (!answer) {
answer = this.findParamsFor(child, key);
}
if (answer) {
return answer;
}
}
}
return null;
}
currentNamespace() {
return this.findParamsFor(this.router.routerState.snapshot.root, "namespace");
}
} | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
InterfaceDeclaration |
export interface INamespaceScope {
namespace: Observable<string>;
currentNamespace(): string;
} | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
MethodDeclaration |
protected getNamespace(params) {
return params['namespace'] || this.getRouteParams('namespace');
} | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
MethodDeclaration |
protected getRouteParams(key): any {
if (
this.router &&
this.router.routerState &&
this.router.routerState.snapshot &&
this.router.routerState.snapshot.root
) {
return this.findParamsFor(this.router.routerState.snapshot.root, key);
}
return null;
} | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
MethodDeclaration |
protected findParamsFor(route, key): any {
let children = route.children;
for (let child of children) {
let params = child.params;
if (params) {
let answer = params[key];
if (!answer) {
answer = this.findParamsFor(child, key);
}
if (answer) {
return answer;
}
}
}
return null;
} | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
MethodDeclaration |
currentNamespace() {
return this.findParamsFor(this.router.routerState.snapshot.root, "namespace");
} | sanketpathak/fabric8-ui | src/a-runtime-console/kubernetes/service/namespace.scope.ts | TypeScript |
ArrowFunction |
() => {
window.blocklet = undefined;
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
ArrowFunction |
() => {
window.blocklet = {
prefix: 'https://baidu.com',
};
const app = new Request(axios);
const axiosConfig = {
baseURL: '',
timeout: 3000,
};
const config = app.handleRequest(axiosConfig);
expect(config.baseURL).toBe('https://baidu.com');
expect(config.timeout).toBe(200000);
expect(app.handleResponse({ data: 100 } as any)).toBe(100);
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
ArrowFunction |
() => {
window.blocklet = {
prefix: '',
};
const app = new Request(axios);
const axiosConfig = {
baseURL: '',
timeout: 3000,
};
const config = app.handleRequest(axiosConfig);
expect(config.baseURL).toBe('');
expect(config.timeout).toBe(200000);
expect(app.handleResponse({ data: 100 } as any)).toBe(100);
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
ArrowFunction |
() => {
const app = new Request(axios);
expect(app.handleResponse({ data: 100 } as any)).toBe(100);
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
ArrowFunction |
async () => {
const app = new Request(axios);
expect(app.handleRequestError(null)).rejects.toBe(null);
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
ArrowFunction |
async () => {
const app = new Request(axios);
const CancelToken = app.getCloseSoure();
expect(CancelToken.token).not.toBeNull();
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
ArrowFunction |
async () => {
const app = new Request(axios);
app.get('http://127.0.0.1', {});
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
ArrowFunction |
async () => {
const app = new Request(axios);
app.post('http://127.0.0.1', {});
} | ds147000/yzl-backlet | src/libs/__tests__/api.test.ts | TypeScript |
FunctionDeclaration |
async function submitFile(): Promise<void> {
const data = new FormData();
if (!uploadedFiles.length) return;
data.append('file', uploadedFiles[0].file, uploadedFiles[0].name);
try {
await api.post('/transactions/import', data);
history.push('/');
} catch (err) {
console.log(err.response.error);
}
} | robertoricci/Desafio-Fundamentos-ReactJS | src/pages/Import/index.tsx | TypeScript |
FunctionDeclaration |
function handleUpload(files: File[]): void {
const uploadFiles = files.map((file: File) => ({
file,
name: file.name,
readableSize: filesize(file.size),
}));
setUploadedFiles(uploadFiles);
} | robertoricci/Desafio-Fundamentos-ReactJS | src/pages/Import/index.tsx | TypeScript |
ArrowFunction |
() => {
const [uploadedFiles, setUploadedFiles] = useState<FileProps[]>([]);
const history = useHistory();
async function submitFile(): Promise<void> {
const data = new FormData();
if (!uploadedFiles.length) return;
data.append('file', uploadedFiles[0].file, uploadedFiles[0].name);
try {
await api.post('/transactions/import', data);
history.push('/');
} catch (err) {
console.log(err.response.error);
}
}
function handleUpload(files: File[]): void {
const uploadFiles = files.map((file: File) => ({
file,
name: file.name,
readableSize: filesize(file.size),
}));
setUploadedFiles(uploadFiles);
}
return (
<>
<Header size="small" />
<Container>
<Title>Importar uma transação</Title>
<ImportFileContainer>
<Upload onUpload={handleUpload} />
{!!uploadedFiles.length && <FileList files={uploadedFiles} />}
<Footer>
<p>
<img src={alert} alt="Alert" />
Permitido apenas arquivos CSV
</p>
<button onClick={submitFile} type="button">
Enviar
</button>
</Footer>
</ImportFileContainer>
</Container>
</> | robertoricci/Desafio-Fundamentos-ReactJS | src/pages/Import/index.tsx | TypeScript |
ArrowFunction |
(file: File) => ({
file,
name: file.name,
readableSize: filesize(file.size),
}) | robertoricci/Desafio-Fundamentos-ReactJS | src/pages/Import/index.tsx | TypeScript |
InterfaceDeclaration |
interface FileProps {
file: File;
name: string;
readableSize: string;
} | robertoricci/Desafio-Fundamentos-ReactJS | src/pages/Import/index.tsx | TypeScript |
ArrowFunction |
async (request, _, config) => {
const validator = new Validator(request, inputParameters)
validateRequest(request)
const jobRunID = validator.validated.id
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { raceType, date, resultsType, endpoint, ...rest } = validator.validated.data
const url = `/elections/${date}`
const params = {
...rest,
level: 'state',
raceTypeID: raceType,
format: 'json',
winner: 'X',
resultsType: resultsType,
apikey: config.apiKey,
}
const options = { ...config.api, params, url }
const response = await Requester.request<ResponseSchema>(options)
validateResponse(response.data)
const race = response.data.races[0]
const reportingUnit = getReportingUnit(race.reportingUnits, rest.statePostal)
const raceWinner = getReportingUnitWinner(reportingUnit)
response.data.precinctsReporting = reportingUnit.precinctsReporting
response.data.precinctsReportingPct = reportingUnit.precinctsReportingPct
response.data.winnerFirstName = raceWinner.first
response.data.winnerLastName = raceWinner.last
response.data.winnerVoteCount = raceWinner.voteCount
response.data.winnerCandidateId = raceWinner.candidateID
response.data.winnerParty = raceWinner.party
response.data.candidates = encodeCandidates(reportingUnit.candidates)
return Requester.success(
jobRunID,
Requester.withResult(response, concatenateName(raceWinner)),
config.verbose,
)
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
ArrowFunction |
(request: AdapterRequest) => {
const { statePostal, officeID, raceID } = request.data
const statePostals = statePostal.split(',')
if (statePostals.length > 1) {
throw new AdapterError({
jobRunID: request.id,
statusCode: 400,
message: 'Adapter only supports finding results from a single state',
})
}
if (!officeID && !raceID) {
throw new AdapterError({
jobRunID: request.id,
statusCode: 400,
message: 'Either officeID or raceID must be present',
})
}
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
ArrowFunction |
(response: ResponseSchema) => {
const races = response.races
if (races.length === 0) {
throw Error('We could not find any races')
}
if (races.length > 1) {
throw Error("We don't support finding the winner from multiple races")
}
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
ArrowFunction |
(reportingUnits: ReportingUnit[], statePostal: string): ReportingUnit => {
// Response should only contain a national RU if the statePostal is US but will contain both national and state for any other statePostal codes.
const level = statePostal === 'US' ? 'national' : 'state'
const reportingUnit = reportingUnits.find((ru) => ru.level === level)
if (!reportingUnit) {
throw Error('Cannot find reporting unit')
}
return reportingUnit
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
ArrowFunction |
(ru) => ru.level === level | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
ArrowFunction |
(reportingUnit: ReportingUnit): Candidate => {
for (const candidate of reportingUnit.candidates) {
if (candidate.winner === 'X') {
return candidate
}
}
throw Error('Candidate not found')
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
ArrowFunction |
(candidate: Candidate): string => `${candidate.voteCount},${candidate.last}` | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
ArrowFunction |
(candidates: Candidate[]): string[] => {
const encodedCandidates: string[] = []
const encodedValTypes = ['uint32', 'string', 'string', 'string', 'uint32', 'bool']
const abiCoder = utils.defaultAbiCoder
for (const { candidateID, party, first, last, voteCount, winner } of candidates) {
const encodedCandidate = abiCoder.encode(encodedValTypes, [
candidateID,
party,
first,
last,
voteCount,
!!winner,
])
encodedCandidates.push(encodedCandidate)
}
return encodedCandidates
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
InterfaceDeclaration |
interface Candidate {
first: string
last: string
abbrv: string
party: string
candidateID: string
pollID: string
ballotOrder: number
polNum: string
voteCount: number
winner?: string
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
InterfaceDeclaration |
interface ReportingUnit {
statePostal: string
stateName: string
level: string
lastUpdated: string
precinctsReporting: number
precinctsTotal: number
precinctsReportingPct: number
candidates: Candidate[]
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
InterfaceDeclaration |
export interface ResponseSchema {
precinctsReporting: number
precinctsReportingPct: number
winnerFirstName: string
winnerLastName: string
winnerVoteCount: number
winnerCandidateId: string
winnerParty: string
candidates: string[]
electionDate: string
timestamp: string
races: {
test: boolean
resultsType: string
raceID: string
raceType: string
raceTypeID: string
offceID: string
officeName: string
party: string
eevp: number
national: boolean
reportingUnits: ReportingUnit[]
}[]
} | KuphJr/external-adapters-js | packages/sources/ap-election/src/endpoint/election.ts | TypeScript |
FunctionDeclaration | /**
* Creates a check function that transforms a number into its integer part.
*
* ```js
* const check = truncate();
*
* check(3.14);
* // => {
* // isOk: true,
* // value: 3,
* // }
*
* check(-3.14);
* // => {
* // isOk: true,
* // value: -3,
* // }
* ```
*
* @returns A check function.
*/
export default function truncate(): Check<number> {
return transform((value) =>
value < 0 ? Math.ceil(value) : Math.floor(value),
);
} | jguyon/check | src/truncate.ts | TypeScript |
ArrowFunction |
(value) =>
value < 0 ? Math.ceil(value) : Math.floor(value) | jguyon/check | src/truncate.ts | TypeScript |
FunctionDeclaration |
export async function findLicense(owner: string, repo: string): Promise<any> {
const ignored = checkIsIgnored("github", `${owner}/${repo}`);
const cached = getCachedKeyForGithubRepo(owner, repo);
if (await ignored) {
return FOUND_IGNORED_REPO
}
const cachedKey = await cached;
if (cachedKey) {
console.log("[licenseplate] found key in cache");
return cachedKey
} else {
// Note: We don't run this at the same time as checkIsIgnored
// (even though both are async and take a bit),
// to avoid needless requests to the github API
let key: string = await findKey(owner, repo);
// Create task to cache this in 2'
// (to avoid congestion due to this low prio task
// on early page load)
setTimeout(() => cacheGithubRepos({
owner: owner,
repo: repo,
lKey: key
}).then(() => console.log(`[licenseplate]: cached ${key} for ${owner}/${repo} `)), 2);
return key
// return await getLicenseProperties(key)
}
} | MachineDoingStuffByItself/licenseplate | src/github/licenseFinder.ts | TypeScript |
FunctionDeclaration |
async function findKey(owner: string, repo: string): Promise<string> {
const url = `https://api.github.com/repos/${owner}/${repo}`;
let repoResponse: Response = await fetch(url);
if (repoResponse.status === 404) {
return FOUND_NO_REPO // Most likely a private repo
}
if (!repoResponse.ok) {
throw Error(`Get request to "${url}" failed with status code ${repoResponse.status}`)
}
let repoInfo = await repoResponse.json();
if (!repoInfo.license) {
return FOUND_NO_LICENSE
}
// Key is `other` if a license file was found, but license not recognized
return repoInfo.license.key
} | MachineDoingStuffByItself/licenseplate | src/github/licenseFinder.ts | TypeScript |
ArrowFunction |
() => cacheGithubRepos({
owner: owner,
repo: repo,
lKey: key
}).then(() => console.log(`[licenseplate]: cached ${key} for ${owner}/${repo} `)) | MachineDoingStuffByItself/licenseplate | src/github/licenseFinder.ts | TypeScript |
ArrowFunction |
() => console.log(`[licenseplate]: cached ${key} for ${owner}/${repo} `) | MachineDoingStuffByItself/licenseplate | src/github/licenseFinder.ts | TypeScript |
InterfaceDeclaration | /**
* The set of arguments for constructing a VpnConnection resource.
*/
export interface VpnConnectionArgs {
/**
* Expected bandwidth in MBPS.
*/
connectionBandwidth?: pulumi.Input<number>;
/**
* The name of the connection.
*/
connectionName?: pulumi.Input<string>;
/**
* DPD timeout in seconds for vpn connection.
*/
dpdTimeoutSeconds?: pulumi.Input<number>;
/**
* EnableBgp flag.
*/
enableBgp?: pulumi.Input<boolean>;
/**
* Enable internet security.
*/
enableInternetSecurity?: pulumi.Input<boolean>;
/**
* EnableBgp flag.
*/
enableRateLimiting?: pulumi.Input<boolean>;
/**
* The name of the gateway.
*/
gatewayName: pulumi.Input<string>;
/**
* Resource ID.
*/
id?: pulumi.Input<string>;
/**
* The IPSec Policies to be considered by this connection.
*/
ipsecPolicies?: pulumi.Input<pulumi.Input<inputs.network.v20200701.IpsecPolicyArgs>[]>;
/**
* The name of the resource that is unique within a resource group. This name can be used to access the resource.
*/
name?: pulumi.Input<string>;
/**
* Id of the connected vpn site.
*/
remoteVpnSite?: pulumi.Input<inputs.network.v20200701.SubResourceArgs>;
/**
* The resource group name of the VpnGateway.
*/
resourceGroupName: pulumi.Input<string>;
/**
* The Routing Configuration indicating the associated and propagated route tables on this connection.
*/
routingConfiguration?: pulumi.Input<inputs.network.v20200701.RoutingConfigurationArgs>;
/**
* Routing weight for vpn connection.
*/
routingWeight?: pulumi.Input<number>;
/**
* SharedKey for the vpn connection.
*/
sharedKey?: pulumi.Input<string>;
/**
* Use local azure ip to initiate connection.
*/
useLocalAzureIpAddress?: pulumi.Input<boolean>;
/**
* Enable policy-based traffic selectors.
*/
usePolicyBasedTrafficSelectors?: pulumi.Input<boolean>;
/**
* Connection protocol used for this connection.
*/
vpnConnectionProtocolType?: pulumi.Input<string | enums.network.v20200701.VirtualNetworkGatewayConnectionProtocol>;
/**
* List of all vpn site link connections to the gateway.
*/
vpnLinkConnections?: pulumi.Input<pulumi.Input<inputs.network.v20200701.VpnSiteLinkConnectionArgs>[]>;
} | polivbr/pulumi-azure-native | sdk/nodejs/network/v20200701/vpnConnection.ts | TypeScript |
MethodDeclaration | /**
* Get an existing VpnConnection resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): VpnConnection {
return new VpnConnection(name, undefined as any, { ...opts, id: id });
} | polivbr/pulumi-azure-native | sdk/nodejs/network/v20200701/vpnConnection.ts | TypeScript |
MethodDeclaration | /**
* Returns true if the given object is an instance of VpnConnection. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is VpnConnection {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === VpnConnection.__pulumiType;
} | polivbr/pulumi-azure-native | sdk/nodejs/network/v20200701/vpnConnection.ts | TypeScript |
InterfaceDeclaration |
export default interface IGuestVoterRepository {
getByCode(accessCode: string): Promise<IGuestVoterEntity | null>;
list(createdBy: string): Promise<IGuestVoterEntity[]>
save(guestVoter: IGuestVoterEntity): Promise<IGuestVoterEntity>;
exists(email: string): Promise<boolean>;
validate(accessCode: string): Promise<boolean>;
invalidateCode(accessCode: string): Promise<void>;
update(guestVoter: IGuestVoterEntity): Promise<IGuestVoterEntity>;
delete(guestVoterId: string): Promise<boolean>;
} | lucasluizss/yourvote | backend/src/domain/guest-voter/IGuestVoterRepository.ts | TypeScript |
ArrowFunction |
choice => {
if (choice === 0) {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, true, StorageScope.WORKSPACE);
} else {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, false, StorageScope.WORKSPACE);
}
return TPromise.as(null);
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
ClassDeclaration | /**
* Encapsulates terminal configuration logic, the primary purpose of this file is so that platform
* specific test cases can be written.
*/
export class TerminalConfigHelper implements ITerminalConfigHelper {
public panelContainer: HTMLElement;
private _charMeasureElement: HTMLElement;
private _lastFontMeasurement: ITerminalFont;
public constructor(
@IConfigurationService private _configurationService: IConfigurationService,
@IWorkspaceConfigurationService private _workspaceConfigurationService: IWorkspaceConfigurationService,
@IChoiceService private _choiceService: IChoiceService,
@IStorageService private _storageService: IStorageService) {
}
public get config(): ITerminalConfiguration {
return this._configurationService.getValue<IFullTerminalConfiguration>().terminal.integrated;
}
private _measureFont(fontFamily: string, fontSize: number, lineHeight: number): ITerminalFont {
// Create charMeasureElement if it hasn't been created or if it was orphaned by its parent
if (!this._charMeasureElement || !this._charMeasureElement.parentElement) {
this._charMeasureElement = document.createElement('div');
this.panelContainer.appendChild(this._charMeasureElement);
}
// TODO: This should leverage CharMeasure
const style = this._charMeasureElement.style;
style.display = 'block';
style.fontFamily = fontFamily;
style.fontSize = fontSize + 'px';
style.lineHeight = 'normal';
this._charMeasureElement.innerText = 'X';
const rect = this._charMeasureElement.getBoundingClientRect();
style.display = 'none';
// Bounding client rect was invalid, use last font measurement if available.
if (this._lastFontMeasurement && !rect.width && !rect.height) {
return this._lastFontMeasurement;
}
this._lastFontMeasurement = {
fontFamily,
fontSize,
lineHeight,
charWidth: rect.width,
charHeight: Math.ceil(rect.height)
};
return this._lastFontMeasurement;
}
/**
* Gets the font information based on the terminal.integrated.fontFamily
* terminal.integrated.fontSize, terminal.integrated.lineHeight configuration properties
*/
public getFont(excludeDimensions?: boolean): ITerminalFont {
const config = this._configurationService.getValue();
const editorConfig = (<IEditorConfiguration>config).editor;
const terminalConfig = this.config;
let fontFamily = terminalConfig.fontFamily || editorConfig.fontFamily;
// Work around bad font on Fedora
if (!terminalConfig.fontFamily) {
if (isFedora) {
fontFamily = '\'DejaVu Sans Mono\'';
}
}
let fontSize = this._toInteger(terminalConfig.fontSize, MINIMUM_FONT_SIZE, MAXIMUM_FONT_SIZE, EDITOR_FONT_DEFAULTS.fontSize);
const lineHeight = terminalConfig.lineHeight ? Math.max(terminalConfig.lineHeight, 1) : DEFAULT_LINE_HEIGHT;
if (excludeDimensions) {
return {
fontFamily,
fontSize,
lineHeight
};
}
return this._measureFont(fontFamily, fontSize, lineHeight);
}
public setWorkspaceShellAllowed(isAllowed: boolean): void {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, isAllowed, StorageScope.WORKSPACE);
}
public mergeDefaultShellPathAndArgs(shell: IShellLaunchConfig): void {
// Check whether there is a workspace setting
const platformKey = platform.isWindows ? 'windows' : platform.isMacintosh ? 'osx' : 'linux';
const shellConfigValue = this._workspaceConfigurationService.inspect<string>(`terminal.integrated.shell.${platformKey}`);
const shellArgsConfigValue = this._workspaceConfigurationService.inspect<string[]>(`terminal.integrated.shellArgs.${platformKey}`);
// Check if workspace setting exists and whether it's whitelisted
let isWorkspaceShellAllowed = false;
if (shellConfigValue.workspace !== undefined || shellArgsConfigValue.workspace !== undefined) {
isWorkspaceShellAllowed = this._storageService.getBoolean(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, StorageScope.WORKSPACE, undefined);
}
// Check if the value is neither blacklisted (false) or whitelisted (true) and ask for
// permission
if (isWorkspaceShellAllowed === undefined) {
let shellString: string;
if (shellConfigValue.workspace) {
shellString = `"${shellConfigValue.workspace}"`;
}
let argsString: string;
if (shellArgsConfigValue.workspace) {
argsString = `[${shellArgsConfigValue.workspace.map(v => '"' + v + '"').join(', ')}]`;
}
// Should not be localized as it's json-like syntax referencing settings keys
let changeString: string;
if (shellConfigValue.workspace !== undefined) {
if (shellArgsConfigValue.workspace !== undefined) {
changeString = `shell: ${shellString}, shellArgs: ${argsString}`;
} else {
changeString = `shell: ${shellString}`;
}
} else { // if (shellArgsConfigValue.workspace !== undefined)
changeString = `shellArgs: ${argsString}`;
}
const message = nls.localize('terminal.integrated.allowWorkspaceShell', "Do you allow {0} (defined as a workspace setting) to be launched in the terminal?", changeString);
const options = [nls.localize('allow', "Allow"), nls.localize('disallow', "Disallow")];
this._choiceService.choose(Severity.Info, message, options, 1).then(choice => {
if (choice === 0) {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, true, StorageScope.WORKSPACE);
} else {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, false, StorageScope.WORKSPACE);
}
return TPromise.as(null);
});
}
shell.executable = (isWorkspaceShellAllowed ? shellConfigValue.value : shellConfigValue.user) || shellConfigValue.default;
shell.args = (isWorkspaceShellAllowed ? shellArgsConfigValue.value : shellArgsConfigValue.user) || shellArgsConfigValue.default;
// Change Sysnative to System32 if the OS is Windows but NOT WoW64. It's
// safe to assume that this was used by accident as Sysnative does not
// exist and will break the terminal in non-WoW64 environments.
if (platform.isWindows && !process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432')) {
const sysnativePath = path.join(process.env.windir, 'Sysnative').toLowerCase();
if (shell.executable.toLowerCase().indexOf(sysnativePath) === 0) {
shell.executable = path.join(process.env.windir, 'System32', shell.executable.substr(sysnativePath.length));
}
}
}
private _toInteger(source: any, minimum: number, maximum: number, fallback: number): number {
let r = parseInt(source, 10);
if (isNaN(r)) {
return fallback;
}
if (typeof minimum === 'number') {
r = Math.max(minimum, r);
}
if (typeof maximum === 'number') {
r = Math.min(maximum, r);
}
return r;
}
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
InterfaceDeclaration |
interface IEditorConfiguration {
editor: IEditorOptions;
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
InterfaceDeclaration |
interface IFullTerminalConfiguration {
terminal: {
integrated: ITerminalConfiguration;
};
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
MethodDeclaration |
private _measureFont(fontFamily: string, fontSize: number, lineHeight: number): ITerminalFont {
// Create charMeasureElement if it hasn't been created or if it was orphaned by its parent
if (!this._charMeasureElement || !this._charMeasureElement.parentElement) {
this._charMeasureElement = document.createElement('div');
this.panelContainer.appendChild(this._charMeasureElement);
}
// TODO: This should leverage CharMeasure
const style = this._charMeasureElement.style;
style.display = 'block';
style.fontFamily = fontFamily;
style.fontSize = fontSize + 'px';
style.lineHeight = 'normal';
this._charMeasureElement.innerText = 'X';
const rect = this._charMeasureElement.getBoundingClientRect();
style.display = 'none';
// Bounding client rect was invalid, use last font measurement if available.
if (this._lastFontMeasurement && !rect.width && !rect.height) {
return this._lastFontMeasurement;
}
this._lastFontMeasurement = {
fontFamily,
fontSize,
lineHeight,
charWidth: rect.width,
charHeight: Math.ceil(rect.height)
};
return this._lastFontMeasurement;
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
MethodDeclaration | /**
* Gets the font information based on the terminal.integrated.fontFamily
* terminal.integrated.fontSize, terminal.integrated.lineHeight configuration properties
*/
public getFont(excludeDimensions?: boolean): ITerminalFont {
const config = this._configurationService.getValue();
const editorConfig = (<IEditorConfiguration>config).editor;
const terminalConfig = this.config;
let fontFamily = terminalConfig.fontFamily || editorConfig.fontFamily;
// Work around bad font on Fedora
if (!terminalConfig.fontFamily) {
if (isFedora) {
fontFamily = '\'DejaVu Sans Mono\'';
}
}
let fontSize = this._toInteger(terminalConfig.fontSize, MINIMUM_FONT_SIZE, MAXIMUM_FONT_SIZE, EDITOR_FONT_DEFAULTS.fontSize);
const lineHeight = terminalConfig.lineHeight ? Math.max(terminalConfig.lineHeight, 1) : DEFAULT_LINE_HEIGHT;
if (excludeDimensions) {
return {
fontFamily,
fontSize,
lineHeight
};
}
return this._measureFont(fontFamily, fontSize, lineHeight);
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
MethodDeclaration |
public setWorkspaceShellAllowed(isAllowed: boolean): void {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, isAllowed, StorageScope.WORKSPACE);
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
MethodDeclaration |
public mergeDefaultShellPathAndArgs(shell: IShellLaunchConfig): void {
// Check whether there is a workspace setting
const platformKey = platform.isWindows ? 'windows' : platform.isMacintosh ? 'osx' : 'linux';
const shellConfigValue = this._workspaceConfigurationService.inspect<string>(`terminal.integrated.shell.${platformKey}`);
const shellArgsConfigValue = this._workspaceConfigurationService.inspect<string[]>(`terminal.integrated.shellArgs.${platformKey}`);
// Check if workspace setting exists and whether it's whitelisted
let isWorkspaceShellAllowed = false;
if (shellConfigValue.workspace !== undefined || shellArgsConfigValue.workspace !== undefined) {
isWorkspaceShellAllowed = this._storageService.getBoolean(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, StorageScope.WORKSPACE, undefined);
}
// Check if the value is neither blacklisted (false) or whitelisted (true) and ask for
// permission
if (isWorkspaceShellAllowed === undefined) {
let shellString: string;
if (shellConfigValue.workspace) {
shellString = `"${shellConfigValue.workspace}"`;
}
let argsString: string;
if (shellArgsConfigValue.workspace) {
argsString = `[${shellArgsConfigValue.workspace.map(v => '"' + v + '"').join(', ')}]`;
}
// Should not be localized as it's json-like syntax referencing settings keys
let changeString: string;
if (shellConfigValue.workspace !== undefined) {
if (shellArgsConfigValue.workspace !== undefined) {
changeString = `shell: ${shellString}, shellArgs: ${argsString}`;
} else {
changeString = `shell: ${shellString}`;
}
} else { // if (shellArgsConfigValue.workspace !== undefined)
changeString = `shellArgs: ${argsString}`;
}
const message = nls.localize('terminal.integrated.allowWorkspaceShell', "Do you allow {0} (defined as a workspace setting) to be launched in the terminal?", changeString);
const options = [nls.localize('allow', "Allow"), nls.localize('disallow', "Disallow")];
this._choiceService.choose(Severity.Info, message, options, 1).then(choice => {
if (choice === 0) {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, true, StorageScope.WORKSPACE);
} else {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, false, StorageScope.WORKSPACE);
}
return TPromise.as(null);
});
}
shell.executable = (isWorkspaceShellAllowed ? shellConfigValue.value : shellConfigValue.user) || shellConfigValue.default;
shell.args = (isWorkspaceShellAllowed ? shellArgsConfigValue.value : shellArgsConfigValue.user) || shellArgsConfigValue.default;
// Change Sysnative to System32 if the OS is Windows but NOT WoW64. It's
// safe to assume that this was used by accident as Sysnative does not
// exist and will break the terminal in non-WoW64 environments.
if (platform.isWindows && !process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432')) {
const sysnativePath = path.join(process.env.windir, 'Sysnative').toLowerCase();
if (shell.executable.toLowerCase().indexOf(sysnativePath) === 0) {
shell.executable = path.join(process.env.windir, 'System32', shell.executable.substr(sysnativePath.length));
}
}
} | GarfieldZHU/vscode | src/vs/workbench/parts/terminal/electron-browser/terminalConfigHelper.ts | TypeScript |
InterfaceDeclaration | // Type definitions for @react-native-community/push-notification-ios 1.0.2
// Project: https://github.com/react-native-community/push-notification-ios
// Definitions by: Jules Sam. Randolph <https://github.com/jsamr>
export interface FetchResult {
NewData: 'UIBackgroundFetchResultNewData';
NoData: 'UIBackgroundFetchResultNoData';
ResultFailed: 'UIBackgroundFetchResultFailed';
} | sparkello/push-notification-ios | index.d.ts | TypeScript |
InterfaceDeclaration |
export interface AuthorizationStatus {
UNAuthorizationStatusNotDetermined: 0;
UNAuthorizationStatusDenied: 1;
UNAuthorizationStatusAuthorized: 2;
UNAuthorizationStatusProvisional: 3;
} | sparkello/push-notification-ios | index.d.ts | TypeScript |
InterfaceDeclaration |
export interface PushNotification {
/**
* An alias for `getAlert` to get the notification's main message string
*/
getMessage(): string | NotificationAlert;
/**
* Gets the sound string from the `aps` object
*/
getSound(): string;
/**
* Gets the category string from the `aps` object
*/
getCategory(): string;
/**
* Gets the notification's main message from the `aps` object
*/
getAlert(): string | NotificationAlert;
/**
* Gets the notification's title from the `aps` object
*/
getTitle(): string;
/**
* Gets the content-available number from the `aps` object
*/
getContentAvailable(): number;
/**
* Gets the badge count number from the `aps` object
*/
getBadgeCount(): number;
/**
* Gets the data object on the notif
*/
getData(): Record<string, any>;
/**
* Get's the action id of the notification action user has taken.
*/
getActionIdentifier(): string | undefined;
/**
* Gets the text user has inputed if user has taken the text action response.
*/
getUserText(): string | undefined;
/**
* iOS Only
* Signifies remote notification handling is complete
*/
finish(result: string): void;
} | sparkello/push-notification-ios | index.d.ts | TypeScript |
InterfaceDeclaration | /**
* @deprecated see `NotificationRequest`
* - This type will be removed in the next major version
*/
export interface PresentLocalNotificationDetails {
/**
* The "action" displayed beneath an actionable notification. Defaults to "view";
*/
alertAction?: string;
/**
* The message displayed in the notification alert.
*/
alertBody: string;
/**
* The text displayed as the title of the notification alert.
*/
alertTitle?: string;
/**
* The number to display as the app's icon badge. Setting the number to 0 removes the icon badge. (optional)
*/
applicationIconBadgeNumber?: number;
/**
* The category of this notification, required for actionable notifications. (optional)
*/
category?: string;
/**
* The sound played when the notification is fired (optional).
* The file should be added in the ios project from Xcode, on your target, so that it is bundled in the final app
* For more details see the example app.
*/
soundName?: string;
/**
* If true, the notification will appear without sound (optional).
*/
isSilent?: boolean;
/**
* An object containing additional notification data (optional).
*/
userInfo?: Record<string, any>;
} | sparkello/push-notification-ios | index.d.ts | TypeScript |
InterfaceDeclaration | /**
* @deprecated see `NotificationRequest`
* - This type will be removed in the next major version
*/
export interface ScheduleLocalNotificationDetails {
/**
* The "action" displayed beneath an actionable notification. Defaults to "view";
*/
alertAction?: string;
/**
* The message displayed in the notification alert.
*/
alertBody: string;
/**
* The text displayed as the title of the notification alert.
*/
alertTitle?: string;
/**
* The number to display as the app's icon badge. Setting the number to 0 removes the icon badge. (optional)
*/
applicationIconBadgeNumber?: number;
/**
* The category of this notification, required for actionable notifications. (optional)
*/
category?: string;
/**
* The date and time when the system should deliver the notification.
* Use Date.toISOString() to convert to the expected format
*/
fireDate: string;
/**
* The sound played when the notification is fired (optional).
* The file should be added in the ios project from Xcode, on your target, so that it is bundled in the final app
* For more details see the example app.
*/
soundName?: string;
/**
* If true, the notification will appear without sound (optional).
*/
isSilent?: boolean;
/**
* An object containing additional notification data (optional).
*/
userInfo?: Record<string, any>;
/**
* The interval to repeat as a string. Possible values: minute, hour, day, week, month, year.
*/
repeatInterval?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
} | sparkello/push-notification-ios | index.d.ts | TypeScript |
InterfaceDeclaration |
export interface PushNotificationPermissions {
alert?: boolean;
badge?: boolean;
sound?: boolean;
lockScreen?: boolean;
notificationCenter?: boolean;
authorizationStatus?: AuthorizationStatus[keyof AuthorizationStatus];
} | sparkello/push-notification-ios | index.d.ts | TypeScript |
InterfaceDeclaration | /**
* Handle push notifications for your app, including permission handling and icon badge number.
*/
export interface PushNotificationIOSStatic {
/**
* iOS fetch results that best describe the result of a finished remote notification handler.
* For a list of possible values, see `PushNotificationIOS.FetchResult`.
*/
FetchResult: FetchResult;
/**
* Authorization status of notification settings
* For a list of possible values, see `PushNotificationIOS.AuthorizationStatus`.
*/
AuthorizationStatus: AuthorizationStatus;
/**
* @deprecated use `addNotificationRequest`
* Schedules the localNotification for immediate presentation.
* details is an object containing:
* alertBody : The message displayed in the notification alert.
* alertAction : The "action" displayed beneath an actionable notification. Defaults to "view";
* soundName : The sound played when the notification is fired (optional). The file should be added in the ios project from Xcode, on your target, so that it is bundled in the final app. For more details see the example app.
* category : The category of this notification, required for actionable notifications (optional).
* userInfo : An optional object containing additional notification data.
* applicationIconBadgeNumber (optional) : The number to display as the app's icon badge. The default value of this property is 0, which means that no badge is displayed.
*/
presentLocalNotification(details: PresentLocalNotificationDetails): void;
/**
* @deprecated use `addNotificationRequest`
* Schedules the localNotification for future presentation.
* details is an object containing:
* fireDate : The date and time when the system should deliver the notification.
* alertBody : The message displayed in the notification alert.
* alertAction : The "action" displayed beneath an actionable notification. Defaults to "view";
* soundName : The sound played when the notification is fired (optional). The file should be added in the ios project from Xcode, on your target, so that it is bundled in the final app. For more details see the example app.
* category : The category of this notification, required for actionable notifications (optional).
* userInfo : An optional object containing additional notification data.
* applicationIconBadgeNumber (optional) : The number to display as the app's icon badge. Setting the number to 0 removes the icon badge.
*/
scheduleLocalNotification(details: ScheduleLocalNotificationDetails): void;
/**
* Sends notificationRequest to notification center at specified firedate.
* Fires immediately if firedate is not set.
*/
addNotificationRequest(request: NotificationRequest): void;
/**
* Cancels all scheduled localNotifications
* @deprecated use `removeAllPendingNotificationRequests` instead
* - This method is deprecated in iOS 10 and will be removed from future release
*/
cancelAllLocalNotifications(): void;
/**
* Removes all pending notifications
*/
removeAllPendingNotificationRequests(): void;
/**
* Removes specified pending notifications from Notification Center.
*/
removePendingNotificationRequests(identifiers: string[]): void;
/**
* Remove all delivered notifications from Notification Center.
*
* See https://reactnative.dev/docs/pushnotificationios.html#removealldeliverednotifications
*/
removeAllDeliveredNotifications(): void;
/**
* Provides you with a list of the app’s notifications that are still displayed in Notification Center.
*
* See https://reactnative.dev/docs/pushnotificationios.html#getdeliverednotifications
*/
getDeliveredNotifications(
callback: (notifications: Record<string, any>[]) => void,
): DeliveredNotification;
/**
* Removes the specified notifications from Notification Center
*
* See https://reactnative.dev/docs/pushnotificationios.html#removedeliverednotifications
*/
removeDeliveredNotifications(identifiers: string[]): void;
/**
* Sets the badge number for the app icon on the home screen
*/
setApplicationIconBadgeNumber(number: number): void;
/**
* Gets the current badge number for the app icon on the home screen
*/
getApplicationIconBadgeNumber(callback: (badge: number) => void): void;
/**
* @deprecated use `removeAllPendingNotificationRequests`
* - This method will be removed in the next major version
* - Cancel local notifications.
* - Optionally restricts the set of canceled notifications to those notifications whose userInfo fields match the corresponding fields in the userInfo argument.
*/
cancelLocalNotifications(userInfo: Record<string, any>): void;
/**
* @deprecated use `getPendingNotificationRequests`
* - This method will be removed in the next major version
* - Gets the local notifications that are currently scheduled.
*/
getScheduledLocalNotifications(
callback: (notifications: ScheduleLocalNotificationDetails[]) => void,
): void;
/**
* - Gets all pending notification requests that are currently scheduled.
*/
getPendingNotificationRequests(
callback: (notifications: NotificationRequest[]) => void,
): void;
/**
* Attaches a listener to remote notifications while the app is running in the
* foreground or the background.
*
* The handler will get be invoked with an instance of `PushNotificationIOS`
*
* The type MUST be 'notification'
*/
addEventListener(
type: 'notification' | 'localNotification',
handler: (notification: PushNotification) => void,
): void;
/**
* Fired when the user registers for remote notifications.
*
* The handler will be invoked with a hex string representing the deviceToken.
*
* The type MUST be 'register'
*/
addEventListener(
type: 'register',
handler: (deviceToken: string) => void,
): void;
/**
* Fired when the user fails to register for remote notifications.
* Typically occurs when APNS is having issues, or the device is a simulator.
*
* The handler will be invoked with {message: string, code: number, details: any}.
*
* The type MUST be 'registrationError'
*/
addEventListener(
type: 'registrationError',
handler: (error: {message: string; code: number; details: any}) => void,
): void;
/**
* Removes the event listener. Do this in `componentWillUnmount` to prevent
* memory leaks
*/
removeEventListener(type: PushNotificationEventName): void;
/**
* Requests all notification permissions from iOS, prompting the user's
* dialog box.
*/
requestPermissions(
permissions?: PushNotificationPermissions[] | PushNotificationPermissions,
): Promise<PushNotificationPermissions>;
/**
* Unregister for all remote notifications received via Apple Push
* Notification service.
* You should call this method in rare circumstances only, such as when
* a new version of the app removes support for all types of remote
* notifications. Users can temporarily prevent apps from receiving
* remote notifications through the Notifications section of the
* Settings app. Apps unregistered through this method can always
* re-register.
*/
abandonPermissions(): void;
/**
* See what push permissions are currently enabled. `callback` will be
* invoked with a `permissions` object:
*
* - `alert` :boolean
* - `badge` :boolean
* - `sound` :boolean
*/
checkPermissions(
callback: (permissions: PushNotificationPermissions) => void,
): void;
/**
* This method returns a promise that resolves to either the notification
* object if the app was launched by a push notification, or `null` otherwise.
*/
getInitialNotification(): Promise<PushNotification | null>;
/**
* Sets notification category to notification center.
* Used to set specific actions for notifications that contains specified category
*/
setNotificationCategories(categories: NotificationCategory[]): void;
} | sparkello/push-notification-ios | index.d.ts | TypeScript |
TypeAliasDeclaration | /**
* Alert Object that can be included in the aps `alert` object
*/
export type NotificationAlert = {
title?: string;
subtitle?: string;
body?: string;
}; | sparkello/push-notification-ios | index.d.ts | TypeScript |
TypeAliasDeclaration | /**
* Notification Category that can include specific actions
*/
export type NotificationCategory = {
id: string;
actions: NotificationAction[];
}; | sparkello/push-notification-ios | index.d.ts | TypeScript |
TypeAliasDeclaration | /**
* Notification Action that can be added to specific categories
*/
export type NotificationAction = {
/**
* Id of Action.
* This value will be returned as actionIdentifier when notification is received.
*/
id: string;
/**
* Text to be shown on notification action button.
*/
title: string;
/**
* Option for notification action.
*/
options?: {
foreground?: boolean;
destructive?: boolean;
authenticationRequired?: boolean;
};
/**
* Option for textInput action.
* If textInput prop exists, then user action will automatically become a text input action.
* The text user inputs will be in the userText field of the received notification.
*/
textInput?: {
/**
* Text to be shown on button when user finishes text input.
* Default is "Send" or its equivalent word in user's language setting.
*/
buttonTitle?: string;
/**
* Placeholder for text input for text input action.
*/
placeholder?: string;
};
}; | sparkello/push-notification-ios | index.d.ts | TypeScript |
TypeAliasDeclaration |
export type NotificationRequest = {
/**
* identifier of the notification.
* Required in order to retrieve specific notification.
*/
id: string;
/**
* A short description of the reason for the alert.
*/
title?: string;
/**
* A secondary description of the reason for the alert.
*/
subtitle?: string;
/**
* The message displayed in the notification alert.
*/
body?: string;
/**
* The number to display as the app's icon badge.
*/
badge?: number;
/**
* The sound to play when the notification is delivered.
* The file should be added in the ios project from Xcode, on your target, so that it is bundled in the final app.
* For more details see the example app.
*/
sound?: string;
/**
* The category of this notification. Required for actionable notifications.
*/
category?: string;
/**
* The thread identifier of this notification.
*/
threadId?: string;
/**
* The date which notification triggers.
*/
fireDate?: Date;
/**
* Sets notification to repeat daily.
* Must be used with fireDate.
*/
repeats?: boolean;
/**
* The interval to repeat as a string. Possible values: minute, hour, day, week, month, year.
*/
repeatInterval?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
/**
* Sets notification to be silent
*/
isSilent?: boolean;
/**
* Optional data to be added to the notification
*/
userInfo?: Record<string, any>;
}; | sparkello/push-notification-ios | index.d.ts | TypeScript |
TypeAliasDeclaration |
export type DeliveredNotification = {
identifier: string;
title: string;
subtitle: string;
body: string;
category?: string;
actionIdentifier?: string;
userText?: string;
userInfo?: Record<string, any>;
'thread-id'?: string;
}; | sparkello/push-notification-ios | index.d.ts | TypeScript |
TypeAliasDeclaration |
export type PushNotificationEventName =
| 'notification'
| 'localNotification'
| 'register'
| 'registrationError'; | sparkello/push-notification-ios | index.d.ts | TypeScript |
ArrowFunction |
(nodes): RuleNode => {
if (nodes.length == 0) {
throw new parseError('cannot parse', fragment.length);
}
if (nodes.length == 1) {
return nodes[0];
}
return {
type: 'group',
nodes,
};
} | 74th/ls-ebnf-parser | src/ruleparser.ts | TypeScript |
ArrowFunction |
rule => {
ruleNames[rule.name] = true;
} | 74th/ls-ebnf-parser | src/ruleparser.ts | TypeScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.