text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```xml
import { z } from '@botpress/sdk'
const TrelloIDSchema = z.string().nullable()
const LimitsObjectSchema = z.object({
status: z.string().optional().nullable(),
disableAt: z.number().optional().nullable(),
warnAt: z.number().optional().nullable(),
})
const MemberPrefsSchema = z.object({
timezoneInfo: z
.object({
offsetCurrent: z.number().optional().nullable(),
timezoneCurrent: z.string().optional().nullable(),
offsetNext: z.number().optional().nullable(),
dateNext: z.string().optional().nullable(),
timezoneNext: z.string().optional().nullable(),
})
.optional()
.nullable(),
privacy: z
.object({
fullName: z.string().optional().nullable(),
avatar: z.string().optional().nullable(),
})
.optional()
.nullable(),
sendSummaries: z.boolean().optional().nullable(),
minutesBetweenSummaries: z.number().optional().nullable(),
minutesBeforeDeadlineToNotify: z.number().optional().nullable(),
colorBlind: z.boolean().optional().nullable(),
locale: z.string().optional().nullable(),
timezone: z.string().optional().nullable(),
twoFactor: z
.object({
enabled: z.boolean().optional().nullable(),
needsNewBackups: z.boolean().optional().nullable(),
})
.optional()
.nullable(),
})
export { TrelloIDSchema, LimitsObjectSchema, MemberPrefsSchema }
``` | /content/code_sandbox/integrations/trello/src/misc/sub-schemas/index.ts | xml | 2016-11-16T21:57:59 | 2024-08-16T18:45:35 | botpress | botpress/botpress | 12,401 | 315 |
```xml
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createHeatmapLayerConstructorSpy,
createHeatmapLayerSpy,
createLatLngConstructorSpy,
createLatLngSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {HeatmapData, MapHeatmapLayer} from './map-heatmap-layer';
describe('MapHeatmapLayer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let latLngSpy: jasmine.SpyObj<google.maps.LatLng>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
latLngSpy = createLatLngSpy();
createMapConstructorSpy(mapSpy);
createLatLngConstructorSpy(latLngSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map heatmap layer', fakeAsync(() => {
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith({
data: [],
map: mapSpy,
});
}));
it('should throw if the `visualization` library has not been loaded', fakeAsync(() => {
createHeatmapLayerConstructorSpy(createHeatmapLayerSpy());
delete (window.google.maps as any).visualization;
expect(() => {
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
}).toThrowError(/Namespace `google.maps.visualization` not found, cannot construct heatmap/);
}));
it('sets heatmap inputs', fakeAsync(() => {
const options: google.maps.visualization.HeatmapLayerOptions = {
map: mapSpy,
data: [
new google.maps.LatLng(37.782, -122.447),
new google.maps.LatLng(37.782, -122.445),
new google.maps.LatLng(37.782, -122.443),
],
};
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = options.data;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith(options);
}));
it('sets heatmap options, ignoring map', fakeAsync(() => {
const options: Partial<google.maps.visualization.HeatmapLayerOptions> = {
radius: 5,
dissipating: true,
};
const data = [
new google.maps.LatLng(37.782, -122.447),
new google.maps.LatLng(37.782, -122.445),
new google.maps.LatLng(37.782, -122.443),
];
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = data;
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith({...options, map: mapSpy, data});
}));
it('exposes methods that provide information about the heatmap', fakeAsync(() => {
const heatmapSpy = createHeatmapLayerSpy();
createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
const heatmap = fixture.componentInstance.heatmap;
heatmapSpy.getData.and.returnValue([] as any);
expect(heatmap.getData()).toEqual([]);
}));
it('should update the heatmap data when the input changes', fakeAsync(() => {
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
let data = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(3, 4),
new google.maps.LatLng(5, 6),
];
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = data;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith(jasmine.objectContaining({data}));
data = [
new google.maps.LatLng(7, 8),
new google.maps.LatLng(9, 10),
new google.maps.LatLng(11, 12),
];
fixture.componentInstance.data = data;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(heatmapSpy.setData).toHaveBeenCalledWith(data);
}));
it('should create a LatLng object if a LatLngLiteral is passed in', fakeAsync(() => {
const latLngConstructor = createLatLngConstructorSpy(latLngSpy);
createHeatmapLayerConstructorSpy(createHeatmapLayerSpy());
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = [
{lat: 1, lng: 2},
{lat: 3, lng: 4},
];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(latLngConstructor).toHaveBeenCalledWith(1, 2);
expect(latLngConstructor).toHaveBeenCalledWith(3, 4);
expect(latLngConstructor).toHaveBeenCalledTimes(2);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-heatmap-layer [data]="data" [options]="options" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapHeatmapLayer],
})
class TestApp {
@ViewChild(MapHeatmapLayer) heatmap: MapHeatmapLayer;
options?: Partial<google.maps.visualization.HeatmapLayerOptions>;
data?: HeatmapData | null;
}
``` | /content/code_sandbox/src/google-maps/map-heatmap-layer/map-heatmap-layer.spec.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 1,254 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import {
format,
parseISO,
differenceInHours,
differenceInSeconds,
formatDistanceToNowStrict,
} from 'date-fns';
import {useEffect, useState} from 'react';
import {logger} from 'modules/logger';
const formatDateTime = (dateString: string) => {
try {
return format(parseISO(dateString), 'dd MMM yyyy - hh:mm a');
} catch (error) {
logger.error(error);
return '';
}
};
function getRelativeDate(date: number): string {
if (differenceInSeconds(Date.now(), date) <= 10) {
return 'Just now';
}
if (differenceInHours(date, Date.now()) > 0) {
return formatDateTime(new Date(date).toISOString());
}
return formatDistanceToNowStrict(date);
}
function useRelativeDate(targetDate: number): string {
const [relativeDate, setRelativeDate] = useState(getRelativeDate(targetDate));
useEffect(() => {
const intervalID = setInterval(() => {
setRelativeDate(getRelativeDate(targetDate));
}, 1000);
return () => {
clearInterval(intervalID);
};
}, [targetDate]);
return relativeDate;
}
export {useRelativeDate};
``` | /content/code_sandbox/operate/client/src/modules/notifications/Notification/useRelativeDate.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 290 |
```xml
import { name } from './name';
import { type } from './type';
import { namespace } from './namespace';
import { ports } from './ports';
import { clusterIP } from './clusterIP';
import { externalIP } from './externalIP';
import { targetPorts } from './targetPorts';
import { application } from './application';
import { created } from './created';
export const columns = [
name,
application,
namespace,
type,
ports,
targetPorts,
clusterIP,
externalIP,
created,
];
``` | /content/code_sandbox/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/index.tsx | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 115 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<!-- Don't create a NuGet package -->
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.SignalR.Protocols.MessagePack\Microsoft.AspNetCore.SignalR.Protocols.MessagePack.csproj" />
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.SignalR\Microsoft.AspNetCore.SignalR.csproj" />
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.Http.Connections\Microsoft.AspNetCore.Http.Connections.csproj" />
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.SignalR.StackExchangeRedis\Microsoft.AspNetCore.SignalR.StackExchangeRedis.csproj" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonPackageVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="$(MicrosoftAspNetCoreDiagnosticsPackageVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="$(MicrosoftAspNetCoreHostingPackageVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="$(MicrosoftAspNetCoreServerIISIntegrationPackageVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="$(MicrosoftAspNetCoreServerKestrelPackageVersion)" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="$(MicrosoftAspNetCoreStaticFilesPackageVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="$(MicrosoftAspNetCoreCorsPackageVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="$(MicrosoftExtensionsConfigurationCommandLinePackageVersion)" />
<PackageReference Include="System.Reactive.Linq" Version="$(SystemReactiveLinqPackageVersion)" />
<PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpPackageVersion)" />
</ItemGroup>
<Target Name="CopyTSClient" BeforeTargets="AfterBuild">
<ItemGroup>
<SignalRJSClientFiles Include="$(MSBuildThisFileDirectory)..\..\clients\ts\signalr\dist\browser\*" />
<SignalRJSClientFiles Include="$(MSBuildThisFileDirectory)..\..\clients\ts\signalr-protocol-msgpack\dist\browser\*" />
</ItemGroup>
<Copy SourceFiles="@(SignalRJSClientFiles)" DestinationFolder="$(MSBuildThisFileDirectory)wwwroot\lib\signalr" />
<ItemGroup>
<MsgPackClientFiles Include="$(MSBuildThisFileDirectory)..\..\clients\ts\signalr-protocol-msgpack\node_modules\msgpack5\dist\*" />
</ItemGroup>
<Copy SourceFiles="@(MsgPackClientFiles)" DestinationFolder="$(MSBuildThisFileDirectory)wwwroot\lib\msgpack5" />
</Target>
</Project>
``` | /content/code_sandbox/samples/SignalRSamples/SignalRSamples.csproj | xml | 2016-10-17T16:39:15 | 2024-08-15T16:33:14 | SignalR | aspnet/SignalR | 2,383 | 619 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="150dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/today"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/date"
android:layout_centerInParent="true"
android:layout_margin="8dp"
android:textAllCaps="true"
android:textAppearance="@android:style/TextAppearance.Material.Large"
android:textColor="@android:color/white"
tools:text="DayOfWeek" />
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_margin="8dp"
android:textAppearance="@android:style/TextAppearance.Material.Medium"
android:textColor="#88FFFFFF"
tools:text="Date" />
<ImageView
android:id="@+id/weather_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_below="@id/today"
android:layout_centerInParent="true"
android:layout_margin="8dp"
android:contentDescription="@string/empty_description"
android:textColor="@android:color/black"
android:tint="@android:color/white"
tools:src="@drawable/wi_day_rain" />
<TextView
android:id="@+id/max_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/weather_icon"
android:layout_margin="8dp"
android:textAppearance="@android:style/TextAppearance.Material.Medium"
android:textColor="@color/colorPrimary"
tools:text="MaxTemp" />
<TextView
android:id="@+id/min_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="@id/weather_icon"
android:layout_margin="8dp"
android:textAppearance="@android:style/TextAppearance.Material.Medium"
android:textColor="#81D4FA"
tools:text="MinTemp" />
</RelativeLayout>
``` | /content/code_sandbox/Android/app/src/main/res/layout/weather_item.xml | xml | 2016-01-30T13:42:30 | 2024-08-12T19:21:10 | Travel-Mate | project-travel-mate/Travel-Mate | 1,292 | 514 |
```xml
import { BlogPostPage } from './blog-post';
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
@NgModule({
declarations: [
BlogPostPage,
],
imports: [
IonicPageModule.forChild(BlogPostPage),
],
exports: [
BlogPostPage
]
})
export class BlogPostPageModule { }
``` | /content/code_sandbox/src/pages/miscellaneous/blog-post/blog-post.module.ts | xml | 2016-11-04T05:48:23 | 2024-08-03T05:22:54 | ionic3-components | yannbf/ionic3-components | 1,679 | 79 |
```xml
import { type HookLog } from '@pnpm/core-loggers'
import * as Rx from 'rxjs'
import { map } from 'rxjs/operators'
import chalk from 'chalk'
import { autozoom } from './utils/zooming'
export function reportHooks (
hook$: Rx.Observable<HookLog>,
opts: {
cwd: string
isRecursive: boolean
}
): Rx.Observable<Rx.Observable<{ msg: string }>> {
return hook$.pipe(
map((log) => Rx.of({
msg: autozoom(
opts.cwd,
log.prefix,
`${chalk.magentaBright(log.hook)}: ${log.message}`,
{
zoomOutCurrent: opts.isRecursive,
}
),
}))
)
}
``` | /content/code_sandbox/cli/default-reporter/src/reporterForClient/reportHooks.ts | xml | 2016-01-28T07:40:43 | 2024-08-16T12:38:47 | pnpm | pnpm/pnpm | 28,869 | 158 |
```xml
import { mergeClasses, Themes } from '@expo/styleguide';
import { forwardRef, PropsWithChildren } from 'react';
import { useCodeBlockSettingsContext } from '~/providers/CodeBlockSettingsProvider';
export type SnippetContentProps = PropsWithChildren<{
alwaysDark?: boolean;
hideOverflow?: boolean;
className?: string;
}>;
export const SnippetContent = forwardRef<HTMLDivElement, SnippetContentProps>(
({ children, className, alwaysDark = false, hideOverflow = false }: SnippetContentProps, ref) => {
const { preferredTheme, wordWrap } = useCodeBlockSettingsContext();
return (
<div
ref={ref}
className={mergeClasses(
preferredTheme === Themes.DARK && 'dark-theme',
wordWrap && '!whitespace-pre-wrap !break-words',
'relative text-default bg-subtle border border-default rounded-b-md overflow-x-auto p-4 !leading-[19px]',
'prose-code:!px-0',
alwaysDark && 'dark-theme bg-palette-black border-transparent whitespace-nowrap',
hideOverflow && 'overflow-hidden prose-code:!whitespace-nowrap',
className
)}>
{children}
</div>
);
}
);
``` | /content/code_sandbox/docs/ui/components/Snippet/SnippetContent.tsx | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 262 |
```xml
export {
exportSchema,
exportSchemaAsString,
exportValueAsString,
} from "./exportSchema.js";
export { EXPORTABLE } from "./helpers.js";
export type { ExportOptions } from "./interfaces.js";
``` | /content/code_sandbox/utils/graphile-export/src/index.ts | xml | 2016-04-14T21:29:19 | 2024-08-16T17:12:51 | crystal | graphile/crystal | 12,539 | 45 |
```xml
// *** WARNING: this file was generated by test. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "./utilities";
// Export members:
export { ProviderArgs } from "./provider";
export type Provider = import("./provider").Provider;
export const Provider: typeof import("./provider").Provider = null as any;
utilities.lazyLoad(exports, ["Provider"], () => require("./provider"));
// Export sub-modules:
import * as core from "./core";
import * as helm from "./helm";
import * as types from "./types";
import * as yaml from "./yaml";
export {
core,
helm,
types,
yaml,
};
pulumi.runtime.registerResourcePackage("kubernetes", {
version: utilities.getVersion(),
constructProvider: (name: string, type: string, urn: string): pulumi.ProviderResource => {
if (type !== "pulumi:providers:kubernetes") {
throw new Error(`unknown provider type ${type}`);
}
return new Provider(name, <any>undefined, { urn });
},
});
``` | /content/code_sandbox/tests/testdata/codegen/kubernetes20/nodejs/index.ts | xml | 2016-10-31T21:02:47 | 2024-08-16T19:47:04 | pulumi | pulumi/pulumi | 20,743 | 240 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>16B2657</string>
<key>CFBundleExecutable</key>
<string>VoodooPS2Keyboard</string>
<key>CFBundleGetInfoString</key>
<key>CFBundleIdentifier</key>
<string>org.rehabman.voodoo.driver.PS2Keyboard</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Voodoo PS/2 Keyboard</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>1.8.25</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1.8.25</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>8B62</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>12D75</string>
<key>DTSDKName</key>
<string>macosx10.8</string>
<key>DTXcode</key>
<string>0810</string>
<key>DTXcodeBuild</key>
<string>8B62</string>
<key>IOKitPersonalities</key>
<dict>
<key>ApplePS2Keyboard</key>
<dict>
<key>CFBundleIdentifier</key>
<string>org.rehabman.voodoo.driver.PS2Keyboard</string>
<key>IOClass</key>
<string>ApplePS2Keyboard</string>
<key>IOProviderClass</key>
<string>ApplePS2KeyboardDevice</string>
<key>Platform Profile</key>
<dict>
<key>DELL</key>
<dict>
<key>Dell-Keys</key>
<dict>
<key>Breakless PS2</key>
<array>
<string>e005</string>
<string>e006</string>
</array>
<key>Function Keys Special</key>
<array>
<string>;The following 12 items map Fn+fkeys to fkeys</string>
<string>e020=3b</string>
<string>e02e=3c</string>
<string>e030=3d</string>
<string>e022=3e</string>
<string>;Fn+f5 macro</string>
<string>;Fn+f6 macro</string>
<string>;Fn+f7 macro</string>
<string>;Fn+f8 macro</string>
<string>;Fn+f9 macro</string>
<string>;Fn+f10 no code</string>
<string>e005=57</string>
<string>e006=58</string>
<string>;The following 12 items map fkeys to Fn+fkeys</string>
<string>3b=e020</string>
<string>3c=e02e</string>
<string>3d=e030</string>
<string>3e=e022</string>
<string>;Fn+f5 macro</string>
<string>;Fn+f6 macro</string>
<string>;Fn+f7 macro</string>
<string>;Fn+f8 macro</string>
<string>;Fn+f9 macro</string>
<string>;Fn+f10 no code</string>
<string>57=e005</string>
<string>58=e006</string>
</array>
<key>Function Keys Standard</key>
<array>
<string>;The following 12 items map Fn+fkeys to Fn+fkeys</string>
<string>e020=e020</string>
<string>e02e=e02e</string>
<string>e030=e030</string>
<string>e022=e022</string>
<string>;Fn+f5 macro</string>
<string>;Fn+f6 macro</string>
<string>;Fn+f7 macro</string>
<string>;Fn+f8 macro</string>
<string>;Fn+f9 macro</string>
<string>;Fn+f10 no code</string>
<string>e005=e005</string>
<string>e006=e006</string>
<string>;The following 12 items map fkeys to fkeys</string>
<string>3b=3b</string>
<string>3c=3c</string>
<string>3d=3d</string>
<string>3e=3e</string>
<string>3f=3f</string>
<string>40=40</string>
<string>41=41</string>
<string>42=42</string>
<string>43=43</string>
<string>44=44</string>
<string>57=57</string>
<string>58=58</string>
</array>
</dict>
<key>HSW-LPT</key>
<string>Dell-Keys</string>
<key>SNB-CPT</key>
<dict>
<key>ActionSwipeDown</key>
<string>63 d, 63 u</string>
<key>ActionSwipeUp</key>
<string>61 d, 61 u</string>
<key>Breakless PS2</key>
<array>
<string>e01e;Touchpad Fn+f3 is breakless</string>
<string>e06e;REVIEW: temporary for case that macro inversion does not work...</string>
</array>
<key>Custom ADB Map</key>
<array>
<string>e009=83;Dell Support to Launchpad</string>
<string>e0f1=71;Call brightens up w RKA1 for special mode (was =90)</string>
<string>e0f2=6b;Call brightens down w RKA2 for special mode (was =91)</string>
<string>e06e=70;Map vidmirror key for special mode default is adb90</string>
</array>
<key>Custom PS2 Map</key>
<array>
<string>e01e=e037;Map tp disable to Fn+f3</string>
<string>e037=e01e;Prevent PrntScr from triggering tp disable</string>
</array>
<key>Function Keys Special</key>
<array>
<string>;The following 12 items map Fn+fkeys to fkeys</string>
<string>e06e=3b</string>
<string>e008=3c</string>
<string>e01e=3d</string>
<string>e005=3e</string>
<string>e006=3f</string>
<string>e00c=40</string>
<string>;Fn+f7 no dedicated macro</string>
<string>e010=42</string>
<string>e022=43</string>
<string>e019=44</string>
<string>e02e=57</string>
<string>e030=58</string>
<string>;The following 12 items map fkeys to Fn+fkeys</string>
<string>3b=e06e;Map vidmirror key to f1</string>
<string>3c=e0f0;Map radio toggle action from EC query to f2</string>
<string>3d=e037;Map touchpad toggle button to f3</string>
<string>3e=e0f2;Map acpi RKA2 to f4 brightness down</string>
<string>3f=e0f1;Map acpi RKA1 to f5 brightness up</string>
<string>40=e0f3;Map acpi RKA3 to f6 keyboard backlight</string>
<string>;Fn+f7 no macro</string>
<string>42=e010</string>
<string>43=e022</string>
<string>44=e019</string>
<string>57=e02e</string>
<string>58=e030</string>
</array>
<key>Function Keys Standard</key>
<array>
<string>;The following 12 items map Fn+fkeys to Fn+fkeys</string>
<string>e06e=e06e;Fn+f1 macro translated</string>
<string>e008=e008;Fn+f2 regular scancode and EC query call q8c</string>
<string>e01e=e037;Fn+f3 regular scancode and EC controls LED</string>
<string>e005=e005;Fn+f4 no ps2scancode and EC query call q81</string>
<string>e006=e006;Fn+f5 no ps2scancode and EC query call q80</string>
<string>e00c=e00c;Fn+f6 no ps2scancode and EC query call q8a</string>
<string>;Fn+f7 no macro just regular f key</string>
<string>e010=e010; Fn+f8 regular scancode</string>
<string>e022=e022; Fn+f9 regular scancode</string>
<string>e019=e019;Fn+f10 regular scancode</string>
<string>e02e=e02e;Fn+f11 regular scancode</string>
<string>e030=e030;Fn+f12 regular scancode</string>
<string>;Fn+f13 is mute dedicated button that always produces e020 regardless of Fn</string>
<string>;The following 12 items map fkeys to fkeys</string>
<string>3b=3b</string>
<string>3c=3c</string>
<string>3d=3d</string>
<string>3e=3e</string>
<string>3f=3f</string>
<string>40=40</string>
<string>41=41</string>
<string>42=42</string>
<string>43=43</string>
<string>44=44</string>
<string>57=57</string>
<string>58=58</string>
</array>
<key>Macro Inversion</key>
<array>
<string>;This section maps ps2 codes (packet format) received quickly (macros) into fake ps2 codes (packet format)</string>
<string>;Fn+F1</string>
<data>
//8CbgAAAAACWwEZ
</data>
<data>
//8C7gAAAAAC2wGZ
</data>
<data>
//8C7gAAAAABmQLb
</data>
</array>
<key>MaximumMacroTime</key>
<integer>35000000</integer>
<key>Note-Author</key>
<string>TimeWalker aka TimeWalker75a</string>
<key>Note-Comment</key>
<string>Keyboard Profile for DELL SandyBridge SecureCore Tiano based laptops (Vostro 3450 & 3750, Inspiron N4110, XPS L502x & L702x & L511z)</string>
</dict>
<key>WN09</key>
<dict>
<key>Breakless PS2</key>
<array>
<string>e01b</string>
<string>e008</string>
<string>e01e</string>
<string>e005</string>
<string>e06e</string>
<string>e006</string>
</array>
<key>Custom ADB Map</key>
<array>
<string>e01b=70</string>
<string>e06e=83</string>
</array>
<key>Custom PS2 Map</key>
<array>
<string>56=2b</string>
<string>29=56</string>
<string>2b=29</string>
<string>e01e=e037</string>
<string>e037=e01e</string>
</array>
</dict>
<key>WN09a</key>
<dict>
<key>Breakless PS2</key>
<array>
<string>e01b</string>
<string>e008</string>
<string>e01e</string>
<string>e005</string>
<string>e06e</string>
<string>e006</string>
</array>
<key>Custom ADB Map</key>
<array>
<string>e01b=70</string>
<string>e06e=83</string>
</array>
<key>Custom PS2 Map</key>
<array>
<string>e01e=e037</string>
<string>e037=e01e</string>
</array>
</dict>
</dict>
<key>Default</key>
<dict>
<key>ActionSwipeDown</key>
<string>65 d, 65 u</string>
<key>ActionSwipeLeft</key>
<string>3e d, 1e d, 1e u, 3e u</string>
<key>ActionSwipeRight</key>
<string>3e d, 21 d, 21 u, 3e u</string>
<key>ActionSwipeUp</key>
<string>64 d, 64 u</string>
<key>Breakless PS2</key>
<array>
<string>;Items must be strings in the form of breaklessscan (in hex)</string>
</array>
<key>Custom ADB Map</key>
<array>
<string>;Items must be strings in the form of scanfrom=adbto (in hex)</string>
</array>
<key>Custom PS2 Map</key>
<array>
<string>;Items must be strings in the form of scanfrom=scanto (in hex)</string>
<string>e027=0;disable discrete fnkeys toggle</string>
<string>e028=0;disable discrete trackpad toggle</string>
</array>
<key>HIDF12EjectDelay</key>
<integer>250</integer>
<key>LogScanCodes</key>
<integer>0</integer>
<key>Make Application key into Apple Fn key</key>
<false/>
<key>Make Application key into right windows</key>
<true/>
<key>Make right modifier keys into Hangul and Hanja</key>
<false/>
<key>SleepPressTime</key>
<integer>0</integer>
<key>Swap capslock and left control</key>
<false/>
<key>Swap command and option</key>
<true/>
<key>Use ISO layout keyboard</key>
<false/>
<key>alt_handler_id</key>
<integer>3</integer>
</dict>
<key>HPQOEM</key>
<dict>
<key>1411</key>
<string>ProBook-102;ProBook 4520s</string>
<key>1619</key>
<string>ProBook-87;ProBook 6560b</string>
<key>161C</key>
<string>ProBook-87;ProBook 8460p</string>
<key>164F</key>
<string>ProBook-87;ProBook 5330m</string>
<key>167C</key>
<string>ProBook-102;ProBook 4530s</string>
<key>167E</key>
<string>ProBook-102;ProBook 4330s</string>
<key>1680</key>
<string>ProBook-102;ProBook 4230s</string>
<key>179B</key>
<string>ProBook-87;ProBook 6470b</string>
<key>179C</key>
<string>ProBook-87;ProBook 6470b</string>
<key>17A9</key>
<string>ProBook-87;ProBook 8570b</string>
<key>17F0</key>
<string>ProBook-102;ProBook 4340s</string>
<key>17F3</key>
<string>ProBook-102;ProBook 4440s</string>
<key>17F6</key>
<string>ProBook-102;ProBook 4540s</string>
<key>1942</key>
<string>ProBook-87;ProBook 450s G1</string>
<key>1949</key>
<string>ProBook-87;ProBook 450s G1</string>
<key>1962</key>
<string>Haswell-Envy;HP Envy 15-j063cl</string>
<key>1963</key>
<string>Haswell-Envy;HP Envy 15-j063cl</string>
<key>1965</key>
<string>Haswell-Envy;HP Envy 17t-j100</string>
<key>1966</key>
<string>Haswell-Envy;HP Envy 17t-j000</string>
<key>198F</key>
<string>ProBook-87;ProBook 450s G0</string>
<key>Haswell-Envy</key>
<dict>
<key>Custom ADB Map</key>
<array>
<string>e019=42;next</string>
<string>e010=4d;previous</string>
</array>
<key>Custom PS2 Map</key>
<array>
<string>e045=e037</string>
<string>e0ab=0;bogus Fn+F2/F3</string>
</array>
</dict>
<key>ProBook-102</key>
<dict>
<key>Function Keys Special</key>
<array>
<string>;The following 12 items map Fn+fkeys to fkeys</string>
<string>e05f=3b</string>
<string>e012=3c</string>
<string>e017=3d</string>
<string>e06e=3e</string>
<string>e00a=3f</string>
<string>e009=40</string>
<string>e020=41</string>
<string>e02e=42</string>
<string>e030=43</string>
<string>e010=44</string>
<string>e022=57</string>
<string>e019=58</string>
<string>;The following 12 items map fkeys to Fn+fkeys</string>
<string>3b=e05f</string>
<string>3c=e012</string>
<string>3d=e017</string>
<string>3e=e06e</string>
<string>3f=e00a</string>
<string>40=e009</string>
<string>41=e020</string>
<string>42=e02e</string>
<string>43=e030</string>
<string>44=e010</string>
<string>57=e022</string>
<string>58=e019</string>
</array>
<key>Function Keys Standard</key>
<array>
<string>;The following 12 items map Fn+fkeys to Fn+fkeys</string>
<string>e05f=e05f</string>
<string>e012=e012</string>
<string>e017=e017</string>
<string>e06e=e06e</string>
<string>e00a=e00a</string>
<string>e009=e009</string>
<string>e020=e020</string>
<string>e02e=e02e</string>
<string>e030=e030</string>
<string>e010=e010</string>
<string>e022=e022</string>
<string>e019=e019</string>
<string>;The following 12 items map fkeys to fkeys</string>
<string>3b=3b</string>
<string>3c=3c</string>
<string>3d=3d</string>
<string>3e=3e</string>
<string>3f=3f</string>
<string>40=40</string>
<string>41=41</string>
<string>42=42</string>
<string>43=43</string>
<string>44=44</string>
<string>57=57</string>
<string>58=58</string>
</array>
<key>SleepPressTime</key>
<integer>3000</integer>
</dict>
<key>ProBook-87</key>
<dict>
<key>Custom ADB Map</key>
<array>
<string>46=4d;scroll => Previous-track</string>
<string>e045=34;pause => Play-Pause</string>
<string>e052=42;insert => Next-track</string>
<string>e046=92;break => Eject</string>
</array>
<key>Function Keys Special</key>
<array>
<string>;The following 8 items map Fn+fkeys to fkeys</string>
<string>e05f=3d</string>
<string>e06e=3e</string>
<string>e02e=40</string>
<string>e030=41</string>
<string>e009=42</string>
<string>e012=43</string>
<string>e017=44</string>
<string>e033=57</string>
<string>;The following 8 items map fkeys to Fn+fkeys</string>
<string>3d=e05f</string>
<string>3e=e06e</string>
<string>40=e02e</string>
<string>41=e030</string>
<string>42=e037</string>
<string>43=e012</string>
<string>44=e017</string>
</array>
<key>Function Keys Standard</key>
<array>
<string>;The following 8 items map Fn+fkeys to Fn+fkeys</string>
<string>e05f=e05f</string>
<string>e06e=e06e</string>
<string>e02e=e02e</string>
<string>e030=e030</string>
<string>e009=e009</string>
<string>e012=e012</string>
<string>e017=e017</string>
<string>e033=e033</string>
<string>;The following 8 items map fkeys to fkeys</string>
<string>3d=3d</string>
<string>3e=3e</string>
<string>40=40</string>
<string>41=41</string>
<string>42=42</string>
<string>43=43</string>
<string>44=44</string>
</array>
<key>SleepPressTime</key>
<integer>3000</integer>
</dict>
</dict>
<key>Intel</key>
<dict>
<key>CALPELLA</key>
<string>SamsungKeys</string>
<key>SamsungKeys</key>
<dict>
<key>Breakless PS2</key>
<array>
<string>e003</string>
<string>e002</string>
<string>e004</string>
<string>e020</string>
<string>;e031</string>
<string>e033</string>
<string>e006</string>
<string>e077</string>
<string>e079</string>
<string>e008</string>
<string>e009</string>
</array>
<key>Custom ADB Map</key>
<array>
<string>e002=70</string>
<string>e006=80</string>
<string>e008=71 (was =90)</string>
<string>e009=6b (was =91)</string>
</array>
<key>Function Keys Special</key>
<array>
<string>;The following 12 items map Fn+fkeys to fkeys</string>
<string>;fn+f1 no code</string>
<string>e003=3c</string>
<string>;fn+f3 weird code</string>
<string>e002=3e</string>
<string>e004=3f</string>
<string>e020=40</string>
<string>e031=41</string>
<string>e033=42</string>
<string>e006=43</string>
<string>;fn+f10 weird code</string>
<string>;fn+f11 no code</string>
<string>;fn+f12 scrolllock</string>
<string>;The following 12 items map fkeys to Fn+fkeys</string>
<string>;fn+f1 no code</string>
<string>3c=e003</string>
<string>;fn+f3 weird code</string>
<string>3e=e002</string>
<string>3f=e004</string>
<string>40=e020</string>
<string>41=e031</string>
<string>42=e033</string>
<string>43=e006</string>
<string>;fn+f10 weird code</string>
<string>;fn+f11 no code</string>
<string>;fn+f12 scrolllock</string>
</array>
<key>Function Keys Standard</key>
<array>
<string>;The following 12 items map Fn+fkeys to Fn+fkeys</string>
<string>;fn+f1 no code</string>
<string>e003=e003</string>
<string>;fn+f3 weird code</string>
<string>e002=e002</string>
<string>e004=e004</string>
<string>e020=e020</string>
<string>e031=e031</string>
<string>e033=e033</string>
<string>e006=e006</string>
<string>;fn+f10 weird code</string>
<string>;fn+f11 no code</string>
<string>;fn+f12 scrolllock</string>
<string>;The following 12 items map fkeys to fkeys</string>
<string>3b=3b</string>
<string>3c=3c</string>
<string>3d=3d</string>
<string>3e=3e</string>
<string>3f=3f</string>
<string>40=40</string>
<string>41=41</string>
<string>42=42</string>
<string>43=43</string>
<string>44=44</string>
<string>57=57</string>
<string>58=58</string>
</array>
</dict>
</dict>
<key>SECCSD</key>
<dict>
<key>LH43STAR</key>
<string>SamsungKeys</string>
<key>SamsungKeys</key>
<dict>
<key>Breakless PS2</key>
<array>
<string>e020</string>
<string>e02e</string>
<string>e030</string>
</array>
</dict>
</dict>
</dict>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.iokit.IOHIDSystem</key>
<string>1.1</string>
<key>com.apple.kpi.bsd</key>
<string>8.0.0</string>
<key>com.apple.kpi.iokit</key>
<string>8.0.0</string>
<key>com.apple.kpi.libkern</key>
<string>8.0.0</string>
<key>com.apple.kpi.mach</key>
<string>8.0.0</string>
<key>com.apple.kpi.unsupported</key>
<string>8.0.0</string>
<key>org.rehabman.voodoo.driver.PS2Controller</key>
<string>1.8.25</string>
</dict>
<key>OSBundleRequired</key>
<string>Console</string>
<key>Source Code</key>
<string>path_to_url
</dict>
</plist>
``` | /content/code_sandbox/Clover-Configs/Lenovo/Y410P/CLOVER/kexts/10.13/VoodooPS2Controller.kext/Contents/PlugIns/VoodooPS2Keyboard.kext/Contents/Info.plist | xml | 2016-11-05T04:22:54 | 2024-08-12T19:25:53 | Hackintosh-Installer-University | huangyz0918/Hackintosh-Installer-University | 3,937 | 6,796 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/**
* Interface describing `dsnanmeanpn`.
*/
interface Routine {
/**
* Computes the arithmetic mean of a single-precision floating-point strided array, ignoring `NaN` values, using a two-pass error correction algorithm with extended accumulation, and returning an extended precision result.
*
* @param N - number of indexed elements
* @param x - input array
* @param stride - stride length
* @returns arithmetic mean
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
*
* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
*
* var v = dsnanmeanpn( x.length, x, 1 );
* // returns ~0.3333
*/
( N: number, x: Float32Array, stride: number ): number;
/**
* Computes the arithmetic mean of a single-precision floating-point strided array, ignoring `NaN` values and using a two-pass error correction algorithm with extended accumulation and alternative indexing semantics.
*
* @param N - number of indexed elements
* @param x - input array
* @param stride - stride length
* @param offset - starting index
* @returns arithmetic mean
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
*
* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
*
* var v = dsnanmeanpn.ndarray( x.length, x, 1, 0 );
* // returns ~0.3333
*/
ndarray( N: number, x: Float32Array, stride: number, offset: number ): number;
}
/**
* Computes the arithmetic mean of a single-precision floating-point strided array, ignoring `NaN` values, using a two-pass error correction algorithm with extended accumulation, and returning an extended precision result.
*
* @param N - number of indexed elements
* @param x - input array
* @param stride - stride length
* @returns arithmetic mean
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
*
* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
*
* var v = dsnanmeanpn( x.length, x, 1 );
* // returns ~0.3333
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
*
* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
*
* var v = dsnanmeanpn.ndarray( x.length, x, 1, 0 );
* // returns ~0.3333
*/
declare var dsnanmeanpn: Routine;
// EXPORTS //
export = dsnanmeanpn;
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/dsnanmeanpn/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 721 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:id="@+id/activity_sencond"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:orientation="vertical"
tools:context="com.yinglan.alphatabsindicator.SencondActivity">
<com.yinglan.alphatabs.AlphaTabsIndicator
android:id="@+id/alphaIndicator"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginTop="20dp"
android:background="@android:color/white"
android:orientation="horizontal">
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@android:color/holo_blue_dark"
app:tabIconNormal="@mipmap/home_normal"
app:tabIconSelected="@mipmap/home_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@android:color/black"
app:tabIconNormal="@mipmap/category_normal"
app:tabIconSelected="@mipmap/category_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@android:color/holo_green_light"
app:tabIconNormal="@mipmap/service_normal"
app:tabIconSelected="@mipmap/service_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@color/colorPrimary"
app:tabIconNormal="@mipmap/mine_normal"
app:tabIconSelected="@mipmap/mine_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
</com.yinglan.alphatabs.AlphaTabsIndicator>
<com.yinglan.alphatabs.AlphaTabsIndicator
android:id="@+id/alphaIndicator1"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="20dp"
android:background="@android:color/white"
android:orientation="horizontal">
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:tabIconNormal="@mipmap/home_normal"
app:tabIconSelected="@mipmap/home_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:tabIconNormal="@mipmap/category_normal"
app:tabIconSelected="@mipmap/category_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:tabIconNormal="@mipmap/service_normal"
app:tabIconSelected="@mipmap/service_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@color/colorAccent"
app:tabIconNormal="@mipmap/mine_normal"
app:tabIconSelected="@mipmap/mine_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
</com.yinglan.alphatabs.AlphaTabsIndicator>
<com.yinglan.alphatabs.AlphaTabsIndicator
android:id="@+id/alphaIndicator2"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginTop="20dp"
android:background="@android:color/white"
android:orientation="horizontal">
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:tabIconNormal="@mipmap/home_normal"
app:tabIconSelected="@mipmap/home_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:tabIconNormal="@mipmap/category_normal"
app:tabIconSelected="@mipmap/category_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:tabIconNormal="@mipmap/service_normal"
app:tabIconSelected="@mipmap/service_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:tabIconNormal="@mipmap/mine_normal"
app:tabIconSelected="@mipmap/mine_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@color/colorPrimaryDark"
app:tabIconNormal="@mipmap/mine_normal"
app:tabIconSelected="@mipmap/mine_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@color/colorPrimary"
app:tabIconNormal="@mipmap/mine_normal"
app:tabIconSelected="@mipmap/mine_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@color/colorPrimary"
app:tabIconNormal="@mipmap/mine_normal"
app:tabIconSelected="@mipmap/mine_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
</com.yinglan.alphatabs.AlphaTabsIndicator>
<com.yinglan.alphatabs.AlphaTabsIndicator
android:id="@+id/alphaIndicator3"
android:layout_width="55dp"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:background="@android:color/white"
android:orientation="vertical">
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@android:color/holo_blue_dark"
app:tabIconNormal="@mipmap/home_normal"
app:tabIconSelected="@mipmap/home_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@android:color/black"
app:tabIconNormal="@mipmap/category_normal"
app:tabIconSelected="@mipmap/category_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@android:color/holo_green_light"
app:tabIconNormal="@mipmap/service_normal"
app:tabIconSelected="@mipmap/service_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
<com.yinglan.alphatabs.AlphaTabView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="5dp"
app:badgeBackgroundColor="@color/colorPrimary"
app:tabIconNormal="@mipmap/mine_normal"
app:tabIconSelected="@mipmap/mine_selected"
app:tabText=""
app:tabTextSize="13sp"
app:textColorNormal="#999999"
app:textColorSelected="#46c01b" />
</com.yinglan.alphatabs.AlphaTabsIndicator>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/activity_sencond.xml | xml | 2016-10-27T07:37:33 | 2024-08-15T11:30:09 | AlphaTabsIndicator | yingLanNull/AlphaTabsIndicator | 1,075 | 2,680 |
```xml
import type { ReactElement } from 'react';
import { c } from 'ttag';
import { useUser } from '@proton/components/hooks';
import type { ProductParam } from '@proton/shared/lib/apps/product';
import type { FreeSubscription } from '@proton/shared/lib/constants';
import {
ADDON_NAMES,
APPS,
CYCLE,
PLANS,
PLAN_TYPES,
isFreeSubscription as getIsFreeSubscription,
} from '@proton/shared/lib/constants';
import { switchPlan } from '@proton/shared/lib/helpers/planIDs';
import {
getCanSubscriptionAccessDuoPlan,
getIpPricePerMonth,
getMaximumCycleForApp,
getPricePerCycle,
hasMaximumCycle,
hasSomeAddonOrPlan,
} from '@proton/shared/lib/helpers/subscription';
import {
Audience,
type Currency,
type Cycle,
type FreePlanDefault,
type Organization,
type Plan,
type PlanIDs,
type PlansMap,
Renew,
type SubscriptionModel,
type VPNServersCountData,
} from '@proton/shared/lib/interfaces';
import { FREE_PLAN } from '@proton/shared/lib/subscription/freePlans';
import { useFlag } from '@proton/unleash';
import isTruthy from '@proton/utils/isTruthy';
import {
CalendarLogo,
DriveLogo,
Icon,
MailLogo,
Option,
PassLogo,
Price,
SelectTwo,
Tabs,
VpnLogo,
WalletLogo,
} from '../../../components';
import CurrencySelector from '../CurrencySelector';
import CycleSelector, { getRestrictedCycle } from '../CycleSelector';
import { getAllFeatures } from '../features';
import type { ShortPlanLike } from '../features/interface';
import { isShortPlanLike } from '../features/interface';
import { getShortPlan, getVPNEnterprisePlan } from '../features/plan';
import PlanCard from './PlanCard';
import PlanCardFeatures, { PlanCardFeatureList, PlanCardFeaturesShort } from './PlanCardFeatures';
import { useCancellationFlow } from './cancellationFlow';
import useCancellationTelemetry from './cancellationFlow/useCancellationTelemetry';
import VpnEnterpriseAction from './helpers/VpnEnterpriseAction';
import { getBundleProPlanToUse, getVPNPlanToUse, notHigherThanAvailableOnBackend } from './helpers/payment';
import './PlanSelection.scss';
export interface SelectedProductPlans {
[Audience.B2C]: PLANS;
[Audience.B2B]: PLANS;
[Audience.FAMILY]: PLANS;
}
const getPlansList = (enabledProductPlans: PLANS[], plansMap: PlansMap) => {
return enabledProductPlans
.map((planName) => {
const plan = plansMap[planName];
if (plan) {
return {
planName,
label: plan.Title,
};
}
})
.filter(isTruthy);
};
const getPlanPanel = (enabledProductPlans: PLANS[], planName: PLANS, plansMap: PlansMap) => {
if (enabledProductPlans.includes(planName)) {
return plansMap[planName];
}
};
interface Tab {
title: string;
content: ReactElement;
audience: Audience;
}
interface Props {
app: ProductParam;
planIDs: PlanIDs;
currency: Currency;
hasPlanSelectionComparison?: boolean;
hasFreePlan?: boolean;
cycle: Cycle;
minimumCycle?: Cycle;
maximumCycle?: Cycle;
plans: Plan[];
plansMap: PlansMap;
freePlan: FreePlanDefault;
vpnServers: VPNServersCountData;
loading?: boolean;
mode: 'signup' | 'settings' | 'modal' | 'upsell-modal';
onChangePlanIDs: (newPlanIDs: PlanIDs, cycle: Cycle) => void;
onChangeCurrency: (newCurrency: Currency) => void;
onChangeCycle: (newCyle: Cycle) => void;
audience: Audience;
onChangeAudience: (newAudience: Audience) => void;
selectedProductPlans: SelectedProductPlans;
onChangeSelectedProductPlans: (newPlans: SelectedProductPlans) => void;
subscription?: SubscriptionModel | FreeSubscription;
organization?: Organization;
filter?: Audience[];
}
export const getPrice = (plan: Plan, cycle: Cycle, plansMap: PlansMap): number | null => {
const price = getPricePerCycle(plan, cycle);
if (price === undefined) {
return null;
}
const plansThatMustUseAddonPricing = {
[PLANS.VPN_PRO]: ADDON_NAMES.MEMBER_VPN_PRO,
[PLANS.VPN_BUSINESS]: ADDON_NAMES.MEMBER_VPN_BUSINESS,
[PLANS.PASS_PRO]: ADDON_NAMES.MEMBER_PASS_PRO,
[PLANS.PASS_BUSINESS]: ADDON_NAMES.MEMBER_PASS_BUSINESS,
};
type PlanWithAddon = keyof typeof plansThatMustUseAddonPricing;
// If the current plan is one of those that must use addon pricing,
// then we find the matching addon object and return its price
for (const planWithAddon of Object.keys(plansThatMustUseAddonPricing) as PlanWithAddon[]) {
if (plan.Name !== planWithAddon) {
continue;
}
const addonName = plansThatMustUseAddonPricing[planWithAddon];
const memberAddon = plansMap[addonName];
const memberPrice = memberAddon ? getPricePerCycle(memberAddon, cycle) : undefined;
if (memberPrice === undefined) {
continue;
}
return memberPrice;
}
return price;
};
const getCycleSelectorOptions = () => {
const oneMonth = { text: c('Billing cycle option').t`1 month`, value: CYCLE.MONTHLY };
const oneYear = { text: c('Billing cycle option').t`12 months`, value: CYCLE.YEARLY };
const twoYears = { text: c('Billing cycle option').t`24 months`, value: CYCLE.TWO_YEARS };
return [oneMonth, oneYear, twoYears];
};
const ActionLabel = ({ plan, currency, cycle }: { plan: Plan; currency: Currency; cycle: Cycle }) => {
const serverPrice = <Price currency={currency}>{getIpPricePerMonth(cycle)}</Price>;
// translator: example of full sentence: "VPN Business requires at least 1 dedicated server (CHF 39.99 /month)"
const serverPriceStr = c('Info').jt`(${serverPrice} /month)`;
const serverPricePerMonth = <span className="text-nowrap">{serverPriceStr}</span>;
return (
<div className="mt-6 flex flex-nowrap color-weak">
<div className="shrink-0 mr-2">
<Icon name="info-circle" />
</div>
<div>{c('Info').jt`${plan.Title} requires at least 1 dedicated server ${serverPricePerMonth}`}</div>
</div>
);
};
const PlanSelection = ({
app,
mode,
hasFreePlan,
planIDs,
plans,
plansMap,
freePlan,
vpnServers,
cycle: cycleProp,
minimumCycle: maybeMinimumCycle,
maximumCycle: maybeMaximumCycle,
currency,
loading,
subscription,
organization,
onChangePlanIDs,
onChangeCurrency,
onChangeCycle,
audience,
onChangeAudience,
selectedProductPlans,
onChangeSelectedProductPlans,
filter,
}: Props) => {
const canAccessWalletPlan = useFlag('WalletPlan');
const canAccessDriveBusinessPlan = useFlag('DriveBizPlan');
const canAccessDuoPlan = useFlag('DuoPlan') && getCanSubscriptionAccessDuoPlan(subscription);
const [user] = useUser();
const isVpnSettingsApp = app == APPS.PROTONVPN_SETTINGS;
const isPassSettingsApp = app == APPS.PROTONPASS;
const isDriveSettingsApp = app == APPS.PROTONDRIVE;
const currentPlan = subscription ? subscription.Plans?.find(({ Type }) => Type === PLAN_TYPES.PLAN) : null;
const isFreeSubscription = getIsFreeSubscription(subscription);
const renderCycleSelector = isFreeSubscription;
const enabledProductB2CPlans = [
PLANS.MAIL,
getVPNPlanToUse({ plansMap, planIDs, cycle: subscription?.Cycle }),
PLANS.DRIVE,
PLANS.PASS,
canAccessWalletPlan && PLANS.WALLET,
].filter(isTruthy);
const bundleProPlan = getBundleProPlanToUse({ plansMap, planIDs });
const { b2bAccess, b2cAccess, redirectToCancellationFlow } = useCancellationFlow();
const { sendStartCancellationPricingReport } = useCancellationTelemetry();
const alreadyHasMaxCycle = hasMaximumCycle(subscription);
let maximumCycle: Cycle | undefined = maybeMaximumCycle;
if (audience === Audience.B2B) {
if (maybeMaximumCycle !== undefined) {
maximumCycle = Math.min(maybeMaximumCycle, CYCLE.YEARLY);
} else {
maximumCycle = CYCLE.YEARLY;
}
}
if (maximumCycle === undefined) {
maximumCycle = getMaximumCycleForApp(app);
}
const cycleSelectorOptions = getCycleSelectorOptions();
const { cycle: restrictedCycle } = getRestrictedCycle({
cycle: cycleProp,
minimumCycle: maybeMinimumCycle,
maximumCycle,
options: cycleSelectorOptions,
});
function excludingCurrentPlanWithMaxCycle(plan: Plan | ShortPlanLike): boolean {
if (isShortPlanLike(plan)) {
return true;
}
const isCurrentPlan = currentPlan?.ID === plan.ID;
const shouldNotRenderCurrentPlan = isCurrentPlan && alreadyHasMaxCycle;
return !shouldNotRenderCurrentPlan;
}
function excludingTheOnlyFreePlan(
plan: Plan | ShortPlanLike,
_: number,
allPlans: (Plan | ShortPlanLike)[]
): boolean {
return !(plan === FREE_PLAN && allPlans.length === 1);
}
function filterPlans(plans: (Plan | null | undefined)[]): Plan[];
function filterPlans(plans: (Plan | ShortPlanLike | null | undefined)[]): (Plan | ShortPlanLike)[];
function filterPlans(plans: (Plan | ShortPlanLike | null | undefined)[]): (Plan | ShortPlanLike)[] {
return plans.filter(isTruthy).filter(excludingCurrentPlanWithMaxCycle).filter(excludingTheOnlyFreePlan);
}
let IndividualPlans = filterPlans([
hasFreePlan ? FREE_PLAN : null,
getPlanPanel(enabledProductB2CPlans, selectedProductPlans[Audience.B2C], plansMap) || plansMap[PLANS.MAIL],
plansMap[PLANS.BUNDLE],
canAccessDuoPlan ? plansMap[PLANS.DUO] : null,
]);
let FamilyPlans = filterPlans([
hasFreePlan ? FREE_PLAN : null,
canAccessDuoPlan ? plansMap[PLANS.DUO] : null,
plansMap[PLANS.FAMILY],
]);
const vpnB2BPlans = filterPlans([
plansMap[PLANS.VPN_PRO],
plansMap[PLANS.VPN_BUSINESS],
getVPNEnterprisePlan(vpnServers),
]);
const passB2BPlans = filterPlans([
plansMap[PLANS.PASS_PRO],
plansMap[PLANS.PASS_BUSINESS],
plansMap[bundleProPlan],
]);
const driveB2BPlans = filterPlans([
canAccessDriveBusinessPlan ? plansMap[PLANS.DRIVE_BUSINESS] : undefined,
plansMap[bundleProPlan],
]);
let B2BPlans: (Plan | ShortPlanLike)[] = [];
/**
* The VPN B2B plans should be displayed only in the ProtonVPN Settings app (protonvpn.com).
*
* The check for length of plans is needed for the case if the VPN B2B plans are not available.
* Then we should fallback to the usual set of plans. It can happen if backend doesn't return the VPN B2B plans.
*/
const isVpnB2bPlans = isVpnSettingsApp && vpnB2BPlans.length !== 0;
const isPassB2bPlans = isPassSettingsApp && passB2BPlans.length !== 0;
const isDriveB2bPlans = isDriveSettingsApp && driveB2BPlans.length !== 0;
if (isVpnB2bPlans) {
B2BPlans = vpnB2BPlans;
} else if (isPassB2bPlans) {
B2BPlans = passB2BPlans;
} else if (isDriveB2bPlans) {
B2BPlans = driveB2BPlans;
} else {
B2BPlans = filterPlans([plansMap[PLANS.MAIL_PRO], plansMap[PLANS.MAIL_BUSINESS], plansMap[bundleProPlan]]);
}
if (app === APPS.PROTONWALLET && !canAccessWalletPlan) {
IndividualPlans = filterPlans([plansMap[PLANS.VISIONARY]]);
FamilyPlans = [];
B2BPlans = [];
}
const isSignupMode = mode === 'signup';
const features = getAllFeatures({
plansMap,
serversCount: vpnServers,
freePlan,
});
const plansListB2C = getPlansList(enabledProductB2CPlans, plansMap);
const b2cRecommendedPlans = [
hasSomeAddonOrPlan(subscription, [PLANS.BUNDLE, PLANS.VISIONARY, PLANS.FAMILY]) ? undefined : PLANS.BUNDLE,
PLANS.DUO,
PLANS.FAMILY,
].filter(isTruthy);
const familyRecommendedPlans = [
hasSomeAddonOrPlan(subscription, [
PLANS.FAMILY,
PLANS.MAIL_PRO,
PLANS.MAIL_BUSINESS,
PLANS.BUNDLE_PRO,
PLANS.BUNDLE_PRO_2024,
PLANS.VISIONARY,
])
? undefined
: PLANS.DUO,
PLANS.FAMILY,
].filter(isTruthy);
const b2bRecommendedPlans = [PLANS.BUNDLE_PRO, PLANS.BUNDLE_PRO_2024];
const hasRecommended = new Set<Audience>();
const renderPlanCard = (plan: Plan, audience: Audience, recommendedPlans: PLANS[]) => {
const isFree = plan.ID === PLANS.FREE;
const isCurrentPlan = isFree ? !currentPlan : currentPlan?.ID === plan.ID;
const shouldNotRenderCurrentPlan = isCurrentPlan && alreadyHasMaxCycle;
if (shouldNotRenderCurrentPlan) {
return null;
}
const isRecommended = !hasRecommended.has(audience) && recommendedPlans.includes(plan.Name as PLANS);
// Only find one recommended plan, in order of priority
if (isRecommended) {
hasRecommended.add(audience);
}
const shortPlan = getShortPlan(plan.Name as PLANS, plansMap, { vpnServers, freePlan });
if (!shortPlan) {
return null;
}
// This was added to display Wallet Plus 12 even if users selects 24 months. wallet2024 doesn't have 24 cycle
// on the backend, so without this hack the frontend attempts to display wallet2024 24 months, doesn't
// find prices for it and completely hides the card of wallet plan.
const cycle = notHigherThanAvailableOnBackend({ [plan.Name]: 1 }, plansMap, restrictedCycle);
const planTitle = shortPlan.title;
const selectedPlanLabel = isFree ? c('Action').t`Current plan` : c('Action').t`Edit subscription`;
const action = isCurrentPlan ? selectedPlanLabel : c('Action').t`Select ${planTitle}`;
const actionLabel =
plan.Name === PLANS.VPN_BUSINESS ? <ActionLabel plan={plan} currency={currency} cycle={cycle} /> : null;
const plansList = audience === Audience.B2C ? plansListB2C : [];
const isSelectable = plansList.some(({ planName: otherPlanName }) => otherPlanName === plan.Name);
const selectedPlan = plansList.some(
({ planName: otherPlanName }) => otherPlanName === selectedProductPlans[audience]
)
? selectedProductPlans[audience]
: plansList[0]?.planName;
const price = getPrice(plan, cycle, plansMap);
if (price === null) {
return null;
}
const featuresElement =
mode === 'settings' || mode === 'upsell-modal' || (audience === Audience.B2B && isVpnSettingsApp) ? (
<PlanCardFeaturesShort plan={shortPlan} icon />
) : (
<PlanCardFeatures audience={audience} features={features} planName={shortPlan.plan} />
);
return (
<PlanCard
isCurrentPlan={!isSignupMode && isCurrentPlan}
action={action}
actionLabel={actionLabel}
enableActionLabelSpacing={isVpnB2bPlans && audience === Audience.B2B}
info={shortPlan.description}
planName={plan.Name as PLANS}
planTitle={
plansList && isSelectable ? (
<SelectTwo
value={selectedPlan}
onChange={({ value: newPlanName }) => {
onChangeSelectedProductPlans({ ...selectedProductPlans, [audience]: newPlanName });
}}
>
{plansList.map(({ planName, label }) => (
<Option key={label} value={planName} title={label}>
{label}
</Option>
))}
</SelectTwo>
) : (
planTitle
)
}
recommended={isRecommended}
currency={currency}
disabled={
loading ||
(isFree && !isSignupMode && isCurrentPlan) ||
(plan.ID === PLANS.FREE && !isFreeSubscription && subscription?.Renew === Renew.Disabled)
}
cycle={cycle}
key={plan.ID}
price={price}
features={featuresElement}
onSelect={(planName) => {
// Mail plus users selecting free plan are redirected to the cancellation reminder flow
if (planName === PLANS.FREE && (b2bAccess || b2cAccess)) {
sendStartCancellationPricingReport();
redirectToCancellationFlow();
return;
}
onChangePlanIDs(
switchPlan({
planIDs,
planID: isFree ? undefined : planName,
organization,
plans,
user,
}),
cycle
);
}}
/>
);
};
const renderShortPlanCard = (plan: ShortPlanLike) => {
return (
// this render contains some assumptions that are valid only because we currently have the only UI plan.
// If we get more later, then this code must be generalized. Examples: "Let's talk" price might be
// different, so is the actionElement.
<PlanCard
isCurrentPlan={false}
actionElement={<VpnEnterpriseAction />}
enableActionLabelSpacing={isVpnB2bPlans && audience === Audience.B2B}
info={plan.description}
planName={plan.plan as any}
planTitle={plan.title}
recommended={false}
currency={currency}
cycle={restrictedCycle}
key={plan.plan}
price={
// translator: displayed instead of price for VPN Enterprise plan. User should contact Sales first.
c('Action').t`Let's talk`
}
features={<PlanCardFeatureList features={plan.features} icon />}
/>
);
};
const tabs: Tab[] = [
IndividualPlans.length > 0 && {
title: c('Tab subscription modal').t`For individuals`,
content: (
<div
className="plan-selection plan-selection--b2c mt-4"
style={{ '--plan-selection-number': IndividualPlans.length }}
data-testid="b2c-plan"
>
{IndividualPlans.map((plan) => renderPlanCard(plan, Audience.B2C, b2cRecommendedPlans))}
</div>
),
audience: Audience.B2C,
},
FamilyPlans.length > 0 && {
title: c('Tab subscription modal').t`For families`,
content: (
<div
className="plan-selection plan-selection--family mt-4"
style={{ '--plan-selection-number': FamilyPlans.length }}
>
{FamilyPlans.map((plan) => renderPlanCard(plan, Audience.FAMILY, familyRecommendedPlans))}
</div>
),
audience: Audience.FAMILY,
},
B2BPlans.length > 0 && {
title: c('Tab subscription modal').t`For businesses`,
content: (
<div
className="plan-selection plan-selection--b2b mt-4"
style={{ '--plan-selection-number': B2BPlans.length }}
data-testid="b2b-plan"
>
{B2BPlans.map((plan) => {
if (isShortPlanLike(plan)) {
return renderShortPlanCard(plan);
} else {
return renderPlanCard(plan, Audience.B2B, b2bRecommendedPlans);
}
})}
</div>
),
audience: Audience.B2B,
},
].filter((tab): tab is Tab => {
if (!tab) {
return false;
}
return filter?.includes(tab.audience) ?? true;
});
const currencyItem = (
<CurrencySelector mode="select-two" currency={currency} onSelect={onChangeCurrency} disabled={loading} />
);
const currencySelectorRow = (
<div className="flex justify-space-between flex-column md:flex-row">
<div className="hidden lg:inline-block visibility-hidden">{currencyItem}</div>
<div className="flex justify-center w-full lg:w-auto">
{renderCycleSelector && (
<CycleSelector
mode="buttons"
cycle={restrictedCycle}
onSelect={onChangeCycle}
disabled={loading}
minimumCycle={maybeMinimumCycle}
maximumCycle={maximumCycle}
options={cycleSelectorOptions}
/>
)}
</div>
<div className="flex mx-auto lg:mx-0 mt-4 lg:mt-0">{currencyItem}</div>
</div>
);
const logosRow = (
<div className="my-6 flex justify-center flex-nowrap items-center color-weak">
<MailLogo variant="glyph-only" />
<Icon name="plus" alt="+" className="mx-2" />
<CalendarLogo variant="glyph-only" />
<Icon name="plus" alt="+" className="mx-2" />
<DriveLogo variant="glyph-only" />
<Icon name="plus" alt="+" className="mx-2" />
<VpnLogo variant="glyph-only" />
<Icon name="plus" alt="+" className="mx-2" />
<PassLogo variant="glyph-only" />
{canAccessWalletPlan && (
<>
<Icon name="plus" alt="+" className="mx-2" />
<WalletLogo variant="glyph-only" />
</>
)}
</div>
);
const tabNumberToAudience = (tabNumber: number): Audience => {
return tabs[tabNumber].audience ?? Audience.B2C;
};
const audienceToTabNumber = (audience: Audience): number => {
const tabIndex = tabs.findIndex((tab) => tab.audience === audience);
return tabIndex !== -1 ? tabIndex : 0;
};
return (
<>
<div className="mb-6">
<Tabs
value={audienceToTabNumber(audience)}
onChange={(tabNumber) => onChangeAudience(tabNumberToAudience(tabNumber))}
tabs={tabs}
fullWidth={true}
containerClassName="inline-block"
navContainerClassName="text-center lg-text-nowrap"
gap={
mode === 'settings' ? (
<>
{logosRow}
{currencySelectorRow}
</>
) : (
<div className="mt-6">{currencySelectorRow}</div>
)
}
/>
</div>
</>
);
};
export default PlanSelection;
``` | /content/code_sandbox/packages/components/containers/payments/subscription/PlanSelection.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 5,259 |
```xml
import { StripTagsPipe } from './strip-tags';
describe('StripTagsPipe Tests', () => {
let pipe: StripTagsPipe;
beforeEach(() => {
pipe = new StripTagsPipe();
});
it('Should strip tags', () => {
expect(pipe.transform('<a href="">foo</a>')).toEqual('foo');
expect(pipe.transform('<p class="foo">bar</p>')).toEqual('bar');
});
it('Should strip tags only tags which are not allowed', () => {
expect(pipe.transform('<a href="">foo</a><p class="foo">bar</p>', 'p')).toEqual('foo<p class="foo">bar</p>');
expect(pipe.transform('<a href="">foo</a><p class="foo">bar</p>', 'a')).toEqual('<a href="">foo</a>bar');
expect(pipe.transform('<a href="">foo</a><p class="foo">bar</p>', 'p', 'a')).toEqual(
'<a href="">foo</a><p class="foo">bar</p>'
);
});
});
``` | /content/code_sandbox/src/ng-pipes/pipes/string/strip-tags.spec.ts | xml | 2016-11-24T22:03:44 | 2024-08-15T12:52:49 | ngx-pipes | danrevah/ngx-pipes | 1,589 | 232 |
```xml
<!--
~ Nextcloud - Android Client
~
-->
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:tint="#FF000000"
android:viewportWidth="960"
android:viewportHeight="960">
<path
android:fillColor="@android:color/white"
android:pathData="M200,840Q167,840 143.5,816.5Q120,793 120,760L120,200Q120,167 143.5,143.5Q167,120 200,120L560,120L560,200L200,200Q200,200 200,200Q200,200 200,200L200,760Q200,760 200,760Q200,760 200,760L760,760Q760,760 760,760Q760,760 760,760L760,400L840,400L840,760Q840,793 816.5,816.5Q793,840 760,840L200,840ZM320,680L320,600L640,600L640,680L320,680ZM320,560L320,480L640,480L640,560L320,560ZM320,440L320,360L640,360L640,440L320,440ZM680,360L680,280L600,280L600,200L680,200L680,120L760,120L760,200L840,200L840,280L760,280L760,360L680,360Z" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_post_add.xml | xml | 2016-06-06T21:23:36 | 2024-08-16T18:22:36 | android | nextcloud/android | 4,122 | 359 |
```xml
import { ReactNode } from 'react';
export type RadioValue = number | string;
export interface BaseRadioProps {
disabled?: boolean;
defaultChecked?: boolean;
checked?: boolean;
value?: RadioValue;
id?: string;
indeterminate?: boolean;
children?: ReactNode;
}
export interface BaseRadioGroupProps {
type?: 'button' | 'list';
disabled?: boolean;
block?: boolean;
compact?: boolean;
defaultValue?: RadioValue;
value?: RadioValue;
onChange?: (value: RadioValue) => void;
children?: ReactNode;
listIconAlign?: 'before' | 'after';
}
``` | /content/code_sandbox/packages/zarm/src/radio/interface.ts | xml | 2016-07-13T11:45:37 | 2024-08-12T19:23:48 | zarm | ZhongAnTech/zarm | 1,707 | 140 |
```xml
import { defineComponent, onErrorCaptured, ref } from 'vue'
import { useNuxtApp } from '../nuxt'
export default defineComponent({
emits: {
error (_error: unknown) {
return true
},
},
setup (_props, { slots, emit }) {
const error = ref<Error | null>(null)
const nuxtApp = useNuxtApp()
onErrorCaptured((err, target, info) => {
if (import.meta.client && (!nuxtApp.isHydrating || !nuxtApp.payload.serverRendered)) {
emit('error', err)
nuxtApp.hooks.callHook('vue:error', err, target, info)
error.value = err
return false
}
})
function clearError () {
error.value = null
}
return () => error.value ? slots.error?.({ error, clearError }) : slots.default?.()
},
})
``` | /content/code_sandbox/packages/nuxt/src/app/components/nuxt-error-boundary.ts | xml | 2016-10-26T11:18:47 | 2024-08-16T19:32:46 | nuxt | nuxt/nuxt | 53,705 | 203 |
```xml
<?xml version="1.0"?>
<psalm
xmlns:xsi="path_to_url"
xmlns="path_to_url"
xsi:schemaLocation="path_to_url vendor/vimeo/psalm/config.xsd"
errorLevel="2"
resolveFromConfigFile="true"
findUnusedBaselineEntry="false"
findUnusedCode="false"
allowStringToStandInForClass="true"
>
<projectFiles>
<directory name="apps"/>
<directory name="src"/>
<directory name="tests"/>
<ignoreFiles>
<directory name="apps/*/*/var"/>
<directory name="vendor"/>
<directory name="src/Shared/Infrastructure/Bus/Event/RabbitMq"/>
<directory name="src/Shared/Infrastructure/Symfony"/>
<directory name="tests/Shared/Infrastructure/Bus/Event/RabbitMq"/>
<directory name="tests/Shared/Infrastructure/Mink"/>
<directory name="tests/Shared/Infrastructure/PhpUnit/Constraint"/>
</ignoreFiles>
</projectFiles>
<issueHandlers>
<PossiblyUndefinedMethod>
<errorLevel type="suppress">
<directory name="tests"/>
</errorLevel>
</PossiblyUndefinedMethod>
<RiskyTruthyFalsyComparison>
<errorLevel type="suppress">
<directory name="apps"/>
<directory name="src"/>
<directory name="tests"/>
</errorLevel>
</RiskyTruthyFalsyComparison>
<PossiblyUndefinedArrayOffset>
<errorLevel type="suppress">
<directory name="apps"/>
<directory name="src"/>
<directory name="tests"/>
</errorLevel>
</PossiblyUndefinedArrayOffset>
<PossiblyInvalidArgument>
<errorLevel type="suppress">
<directory name="tests"/>
</errorLevel>
</PossiblyInvalidArgument>
<PossiblyNullReference>
<errorLevel type="suppress">
<directory name="tests"/>
</errorLevel>
</PossiblyNullReference>
<PossiblyNullArgument>
<errorLevel type="suppress">
<directory name="tests"/>
</errorLevel>
</PossiblyNullArgument>
<PropertyNotSetInConstructor>
<errorLevel type="suppress">
<directory name="tests"/>
</errorLevel>
</PropertyNotSetInConstructor>
<MoreSpecificReturnType>
<errorLevel type="suppress">
<file name="apps/*/*/src/*Kernel.php"/>
</errorLevel>
</MoreSpecificReturnType>
<UnresolvableInclude>
<errorLevel type="suppress">
<file name="apps/*/*/src/*Kernel.php"/>
</errorLevel>
</UnresolvableInclude>
</issueHandlers>
<plugins>
<pluginClass class="Psalm\MockeryPlugin\Plugin"/>
<pluginClass class="Psalm\SymfonyPsalmPlugin\Plugin"/>
<pluginClass class="Psalm\PhpUnitPlugin\Plugin"/>
</plugins>
</psalm>
``` | /content/code_sandbox/psalm.xml | xml | 2016-11-17T12:56:16 | 2024-08-14T20:32:22 | php-ddd-example | CodelyTV/php-ddd-example | 2,948 | 642 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Behavior Version="5">
<Node Class="Behaviac.Design.Nodes.Behavior" AgentType="AgentNodeTest" Domains="" Enable="true" HasOwnPrefabData="false" Id="-1" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<DescriptorRefs value="0:" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Parallel" ChildFinishPolicy="CHILDFINISH_LOOP" Enable="true" ExitPolicy="EXIT_ABORT_RUNNINGSIBLINGS" FailurePolicy="FAIL_ON_ONE" HasOwnPrefabData="false" Id="0" PrefabName="" PrefabNodeId="-1" SuccessPolicy="SUCCEED_ON_ALL">
<Comment Background="NoColor" Text="" />
<Attachment Class="PluginBehaviac.Events.Precondition" BinaryOperator="And" Enable="true" Id="1" Operator="Equal" Opl="Self.AgentNodeTest::enter_action_1(0)" Opr1="""" Opr2="const bool true" Phase="Enter" PrefabAttachmentId="-1" />
<Attachment Class="PluginBehaviac.Events.Effector" Enable="true" Id="2" Operator="Invalid" Opl="Self.AgentNodeTest::exit_action_1(0)" Opr1="""" Opr2="""" Phase="Success" PrefabAttachmentId="-1" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.WaitforSignal" Enable="true" HasOwnPrefabData="false" Id="3" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Attachment Class="PluginBehaviac.Events.Precondition" BinaryOperator="And" Enable="true" Id="4" Operator="Equal" Opl="Self.AgentNodeTest::enter_action_2(3,"hello")" Opr1="""" Opr2="const bool true" Phase="Enter" PrefabAttachmentId="-1" />
<Attachment Class="PluginBehaviac.Events.Effector" Enable="true" Id="5" Operator="Invalid" Opl="Self.AgentNodeTest::exit_action_2(5,"world")" Opr1="""" Opr2="""" Phase="Success" PrefabAttachmentId="-1" />
<Connector Identifier="_custom_condition">
<Node Class="PluginBehaviac.Nodes.Condition" Enable="true" HasOwnPrefabData="false" Id="8" Operator="Equal" Opl="int Self.AgentNodeTest::testVar_0" Opr="const int 0" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
</Connector>
</Node>
<Node Class="PluginBehaviac.Nodes.Action" Enable="true" HasOwnPrefabData="false" Id="9" Method="Self.AgentNodeTest::setTestVar_3(0)" PrefabName="" PrefabNodeId="-1" ResultFunctor="""" ResultOption="BT_SUCCESS">
<Comment Background="NoColor" Text="" />
<Attachment Class="PluginBehaviac.Events.Precondition" BinaryOperator="And" Enable="true" Id="6" Operator="Equal" Opl="Self.AgentNodeTest::enter_action_0()" Opr1="""" Opr2="const bool true" Phase="Enter" PrefabAttachmentId="-1" />
<Attachment Class="PluginBehaviac.Events.Effector" Enable="true" Id="7" Operator="Invalid" Opl="Self.AgentNodeTest::exit_action_0()" Opr1="""" Opr2="""" Phase="Success" PrefabAttachmentId="-1" />
</Node>
</Connector>
</Node>
</Connector>
</Node>
</Behavior>
``` | /content/code_sandbox/integration/unity/Assets/behaviac/workspace/behaviors/node_test/enter_exit_action_ut_2.xml | xml | 2016-11-21T05:08:08 | 2024-08-16T07:18:30 | behaviac | Tencent/behaviac | 2,831 | 869 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="path_to_url">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{57C873CA-332D-13A8-31F9-2C6F4D30497F}</ProjectGuid>
<OutputType>Library</OutputType>
<AssemblyName>Assembly-CSharp</AssemblyName>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile>Unity Subset v3.5</TargetFrameworkProfile>
<CompilerResponseFile></CompilerResponseFile>
<UnityProjectType>Game:1</UnityProjectType>
<UnityBuildTarget>Android:13</UnityBuildTarget>
<UnityVersion>5.5.0f3</UnityVersion>
<RootNamespace></RootNamespace>
<LangVersion>4</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>false</Optimize>
<OutputPath>Temp\UnityVS_bin\Debug\</OutputPath>
<IntermediateOutputPath>Temp\UnityVS_obj\Debug\</IntermediateOutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DefineConstants>DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_5_0;UNITY_5_5;UNITY_5;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_GENERICS;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_SCRIPTING_NEW_CSHARP_COMPILER;UNITY_ANDROID;ENABLE_SUBSTANCE;UNITY_ANDROID_API;ENABLE_EGL;ENABLE_NETWORK;ENABLE_RUNTIME_GI;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;PLATFORM_SUPPORTS_ADS_ID;UNITY_CAN_SHOW_SPLASH_SCREEN;ENABLE_VIDEO;ENABLE_VR;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;ENABLE_MONO;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE</DefineConstants>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>false</Optimize>
<OutputPath>Temp\UnityVS_bin\Release\</OutputPath>
<IntermediateOutputPath>Temp\UnityVS_obj\Release\</IntermediateOutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DefineConstants>TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_5_0;UNITY_5_5;UNITY_5;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_GENERICS;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_SCRIPTING_NEW_CSHARP_COMPILER;UNITY_ANDROID;ENABLE_SUBSTANCE;UNITY_ANDROID_API;ENABLE_EGL;ENABLE_NETWORK;ENABLE_RUNTIME_GI;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;PLATFORM_SUPPORTS_ADS_ID;UNITY_CAN_SHOW_SPLASH_SCREEN;ENABLE_VIDEO;ENABLE_VR;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;ENABLE_MONO;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE</DefineConstants>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.XML" />
<Reference Include="System.Core" />
<Reference Include="Boo.Lang" />
<Reference Include="UnityScript.Lang" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml.Linq" />
<Reference Include="UnityEngine">
<HintPath>Library\UnityAssemblies\UnityEngine.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.UI">
<HintPath>Library\UnityAssemblies\UnityEngine.UI.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.Networking">
<HintPath>Library\UnityAssemblies\UnityEngine.Networking.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.PlaymodeTestsRunner">
<HintPath>Library\UnityAssemblies\UnityEngine.PlaymodeTestsRunner.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.Analytics">
<HintPath>Library\UnityAssemblies\UnityEngine.Analytics.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.HoloLens">
<HintPath>Library\UnityAssemblies\UnityEngine.HoloLens.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.VR">
<HintPath>Library\UnityAssemblies\UnityEngine.VR.dll</HintPath>
</Reference>
<Reference Include="UnityEditor">
<HintPath>Library\UnityAssemblies\UnityEditor.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Assets\Scripts\SystemInfoController.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="GenerateTargetFrameworkMonikerAttribute" />
</Project>
``` | /content/code_sandbox/SomeTest/SystemInfoDemo/SystemInfoDemo.csproj | xml | 2016-04-25T14:37:08 | 2024-08-16T09:19:37 | Unity3DTraining | XINCGer/Unity3DTraining | 7,368 | 1,725 |
```xml
import { validateMaximumLength } from "./util";
it("limits to maximum when string is provided", () => {
expect(() => validateMaximumLength(5, "123456")).toThrow();
});
it("limits to maximum when string is not provided", () => {
expect(validateMaximumLength(5)).toEqual(undefined);
});
it("returns the string when string is provided and is within the length allowances", () => {
expect(validateMaximumLength(5, "1234")).toEqual("1234");
});
``` | /content/code_sandbox/server/src/core/server/graph/mutators/util.spec.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 104 |
```xml
import customScalars from '@erxes/api-utils/src/customScalars';
import mutations from './mutations';
import queries from './queries';
import { KhanbankAccount } from './accounts';
import { KhanbankStatement } from './statements';
const resolvers: any = async () => ({
...customScalars,
KhanbankAccount,
// KhanbankStatement,
Mutation: {
...mutations
},
Query: {
...queries
}
});
export default resolvers;
``` | /content/code_sandbox/packages/plugin-khanbank-api/src/graphql/resolvers/index.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 98 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../LocalizableStrings.resx">
<body>
<trans-unit id="CannotFindAManifestFile">
<source>Cannot find a manifest file.
For a list of locations searched, specify the "-d" option before the tool name.</source>
<target state="translated"> .
"-d" .</target>
<note />
</trans-unit>
<trans-unit id="CannotFindPackageIdInManifest">
<source>Cannot find a package with the package id {0} in the manifest file.</source>
<target state="translated"> ID {0} .</target>
<note />
</trans-unit>
<trans-unit id="ListOfSearched">
<source>The list of searched paths:
{0}</source>
<target state="translated"> :
{0}</target>
<note />
</trans-unit>
<trans-unit id="ManifestHasMarkOfTheWeb">
<source>File {0} came from another computer and might be blocked to help protect this computer. For more information, including how to unblock, see path_to_url
<target state="translated">{0} . path_to_url .</target>
<note />
</trans-unit>
<trans-unit id="ManifestPackageIdCollision">
<source>Cannot add package. Manifest file already contains version {0} of the package {1}. Uninstall/install or edit manifest file {2} to specify the new version {3}.</source>
<target state="translated"> . {1} {0} . {3}() {2}() / .</target>
<note />
</trans-unit>
<trans-unit id="MultipleSamePackageId">
<source>More than one entry exists for package(s): {0}.</source>
<target state="translated"> {0} .</target>
<note />
</trans-unit>
<trans-unit id="ToolMissingRollForward">
<source>Missing 'rollForward' entry.</source>
<target state="translated">'rollForward' .</target>
<note />
</trans-unit>
<trans-unit id="UnexpectedTypeInJson">
<source>Expected a {0} for property '{1}'.</source>
<target state="translated">'{1}' {0}() .</target>
<note />
</trans-unit>
<trans-unit id="VersionIsInvalid">
<source>Version {0} is invalid.</source>
<target state="translated"> {0}() .</target>
<note />
</trans-unit>
<trans-unit id="FieldCommandsIsMissing">
<source>Missing 'commands' entry.</source>
<target state="translated">'commands' .</target>
<note />
</trans-unit>
<trans-unit id="InvalidManifestFilePrefix">
<source>Invalid manifest file. Path {0}:
{1}</source>
<target state="translated"> . {0}:
{1}</target>
<note />
</trans-unit>
<trans-unit id="InPackage">
<source>In package {0}:
{1}</source>
<target state="translated"> {0}:
{1}</target>
<note />
</trans-unit>
<trans-unit id="ManifestVersionHigherThanSupported">
<source>Manifest version is {0}. This manifest may not be supported in this SDK version that can support up to manifest version {1}.</source>
<target state="translated"> {0}. {1} SDK .</target>
<note />
</trans-unit>
<trans-unit id="ManifestVersion0">
<source>Manifest version 0 is not supported.</source>
<target state="translated"> 0 .</target>
<note />
</trans-unit>
<trans-unit id="ToolMissingVersion">
<source>Missing 'version' entry.</source>
<target state="translated">'version' .</target>
<note />
</trans-unit>
<trans-unit id="JsonParsingError">
<source>Json parsing error in file {0} : {1}</source>
<target state="translated">{0} Json : {1}</target>
<note />
</trans-unit>
<trans-unit id="ManifestMissingIsRoot">
<source>Missing 'isRoot' entry.</source>
<target state="translated">'isRoot' .</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Cli/dotnet/ToolManifest/xlf/LocalizableStrings.ko.xlf | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 1,106 |
```xml
import map from "./index";
// OK
const test1: Record<string, string[]> = map({ a: "string" }, (value) =>
value.split("")
);
const test2: Record<string, string> = map(
{ a: "string" },
(value, key) => key + value
);
const test3: Record<string, boolean> = map(
{ a: "string", string: "a", b: "string" },
(value, key, obj) => obj[value] === key
);
// Not OK
// @ts-expect-error
const test4: Record<string, string> = map({ foo: 1 }, (value) => value + 1);
// @ts-expect-error
map();
// @ts-expect-error
map({ foo: 1 });
// @ts-expect-error
map((value: string) => {});
// @ts-expect-error
map({ foo: 1 }, "");
// @ts-expect-error
map({ foo: 1 }, {});
// @ts-expect-error
map({ a: 1 }, (value: string) => {});
``` | /content/code_sandbox/packages/object-map-values/index.tests.ts | xml | 2016-06-26T02:04:54 | 2024-08-15T00:08:43 | just | angus-c/just | 5,974 | 241 |
```xml
///
///
///
/// path_to_url
///
/// Unless required by applicable law or agreed to in writing, software
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
///
import {
ChangeDetectorRef,
Component,
forwardRef,
Input,
OnChanges,
OnInit,
SimpleChanges,
ViewEncapsulation
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
UntypedFormArray,
UntypedFormBuilder,
UntypedFormGroup
} from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { WidgetConfigComponent } from '@home/components/widget/widget-config.component';
import { DataKey, DatasourceType, widgetType } from '@shared/models/widget.models';
import { DataKeyType } from '@shared/models/telemetry/telemetry.models';
import { UtilsService } from '@core/services/utils.service';
import { DataKeysCallbacks } from '@home/components/widget/config/data-keys.component.models';
import { aggregatedValueCardDefaultKeySettings } from '@home/components/widget/lib/cards/aggregated-value-card.models';
@Component({
selector: 'tb-aggregated-data-keys-panel',
templateUrl: './aggregated-data-keys-panel.component.html',
styleUrls: ['./aggregated-data-keys-panel.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AggregatedDataKeysPanelComponent),
multi: true
}
],
encapsulation: ViewEncapsulation.None
})
export class AggregatedDataKeysPanelComponent implements ControlValueAccessor, OnInit, OnChanges {
@Input()
disabled: boolean;
@Input()
datasourceType: DatasourceType;
@Input()
keyName: string;
dataKeyType: DataKeyType;
keysListFormGroup: UntypedFormGroup;
get widgetType(): widgetType {
return this.widgetConfigComponent.widgetType;
}
get callbacks(): DataKeysCallbacks {
return this.widgetConfigComponent.widgetConfigCallbacks;
}
get noKeys(): boolean {
const keys: DataKey[] = this.keysListFormGroup.get('keys').value;
return keys.length === 0;
}
private propagateChange = (_val: any) => {};
constructor(private fb: UntypedFormBuilder,
private dialog: MatDialog,
private cd: ChangeDetectorRef,
private utils: UtilsService,
private widgetConfigComponent: WidgetConfigComponent) {
}
ngOnInit() {
this.keysListFormGroup = this.fb.group({
keys: [this.fb.array([]), []]
});
this.keysListFormGroup.valueChanges.subscribe(
(val) => this.propagateChange(this.keysListFormGroup.get('keys').value)
);
this.updateParams();
}
ngOnChanges(changes: SimpleChanges): void {
for (const propName of Object.keys(changes)) {
const change = changes[propName];
if (!change.firstChange && change.currentValue !== change.previousValue) {
if (['datasourceType'].includes(propName)) {
this.updateParams();
}
}
}
}
private updateParams() {
if (this.datasourceType === DatasourceType.function) {
this.dataKeyType = DataKeyType.function;
} else {
this.dataKeyType = DataKeyType.timeseries;
}
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
if (isDisabled) {
this.keysListFormGroup.disable({emitEvent: false});
} else {
this.keysListFormGroup.enable({emitEvent: false});
}
}
writeValue(value: DataKey[] | undefined): void {
this.keysListFormGroup.setControl('keys', this.prepareKeysFormArray(value), {emitEvent: false});
}
keysFormArray(): UntypedFormArray {
return this.keysListFormGroup.get('keys') as UntypedFormArray;
}
trackByKey(index: number, keyControl: AbstractControl): any {
return keyControl;
}
removeKey(index: number) {
(this.keysListFormGroup.get('keys') as UntypedFormArray).removeAt(index);
}
addKey() {
const dataKey = this.callbacks.generateDataKey(this.keyName, this.dataKeyType, null,
true,null);
dataKey.decimals = 0;
dataKey.settings = {...aggregatedValueCardDefaultKeySettings};
const keysArray = this.keysListFormGroup.get('keys') as UntypedFormArray;
const keyControl = this.fb.control(dataKey, []);
keysArray.push(keyControl);
}
private prepareKeysFormArray(keys: DataKey[] | undefined): UntypedFormArray {
const keysControls: Array<AbstractControl> = [];
if (keys) {
keys.forEach((key) => {
keysControls.push(this.fb.control(key, []));
});
}
return this.fb.array(keysControls);
}
}
``` | /content/code_sandbox/ui-ngx/src/app/modules/home/components/widget/config/basic/cards/aggregated-data-keys-panel.component.ts | xml | 2016-12-01T09:33:30 | 2024-08-16T19:58:25 | thingsboard | thingsboard/thingsboard | 16,820 | 1,065 |
```xml
<project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-modules</artifactId>
<version>1.20.0-SNAPSHOT</version>
</parent>
<artifactId>jts-tests</artifactId>
<name>${project.groupId}:${project.artifactId}</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>org.locationtech.jtstest.testrunner.JTSTestRunnerCmd</mainClass>
</manifest>
</archive>
<finalName>JTSTestRunner</finalName>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
``` | /content/code_sandbox/modules/tests/pom.xml | xml | 2016-01-25T18:08:41 | 2024-08-15T17:34:53 | jts | locationtech/jts | 1,923 | 430 |
```xml
/*
* Wire
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see path_to_url
*
*/
import {Tooltip} from '@wireapp/react-ui-kit';
import {AVATAR_SIZE, Avatar} from 'Components/Avatar';
import * as Icon from 'Components/Icon';
import {UserBlockedBadge} from 'Components/UserBlockedBadge/UserBlockedBadge';
import {UserName} from 'Components/UserName';
import {ContentMessage} from 'src/script/entity/message/ContentMessage';
import {DeleteMessage} from 'src/script/entity/message/DeleteMessage';
import {User} from 'src/script/entity/User';
import {ServiceEntity} from 'src/script/integration/ServiceEntity';
import {useKoSubscribableChildren} from 'Util/ComponentUtil';
import {t} from 'Util/LocalizerUtil';
type MessageHeaderParams = {
message: ContentMessage | DeleteMessage;
onClickAvatar: (user: User | ServiceEntity) => void;
focusTabIndex?: number;
/** Will not display the guest, federated or service badges next to the user name */
noBadges?: boolean;
/** Will not use the user's accent color to display the user name */
noColor?: boolean;
uieName?: string;
children?: React.ReactNode;
};
function BadgeSection({sender}: {sender: User}) {
return (
<>
{sender.isService && (
<span className="message-header-icon-service">
<Icon.ServiceIcon />
</span>
)}
{sender.isExternal() && (
<Tooltip body={t('rolePartner')} data-uie-name="sender-external" className="message-header-icon-external">
<Icon.ExternalIcon />
</Tooltip>
)}
{sender.isFederated && (
<Tooltip className="message-header-icon-guest" body={sender.handle} data-uie-name="sender-federated">
<Icon.FederationIcon />
</Tooltip>
)}
{sender.isDirectGuest() && !sender.isFederated && (
<Tooltip
className="message-header-icon-guest"
body={t('conversationGuestIndicator')}
data-uie-name="sender-guest"
>
<Icon.GuestIcon />
</Tooltip>
)}
</>
);
}
export function MessageHeader({
message,
onClickAvatar,
focusTabIndex,
noBadges = false,
noColor = false,
uieName = '',
children,
}: MessageHeaderParams) {
const {user: sender} = useKoSubscribableChildren(message, ['user']);
const {isAvailable, isBlocked} = useKoSubscribableChildren(sender, ['isAvailable', 'isBlocked']);
return (
<div className="message-header">
<div className="message-header-icon">
<Avatar
tabIndex={focusTabIndex}
participant={sender}
onAvatarClick={onClickAvatar}
avatarSize={AVATAR_SIZE.X_SMALL}
/>
</div>
<div className="message-header-label" data-uie-name={uieName}>
<h4
className={`message-header-label-sender ${!noColor && message.accent_color()}`}
css={!isAvailable ? {color: 'var(--text-input-placeholder)'} : {}}
data-uie-name={uieName ? `${uieName}-sender-name` : 'sender-name'}
data-uie-uid={sender.id}
>
<UserName user={sender} />
</h4>
{isBlocked && (
<span css={{marginLeft: 4}}>
<UserBlockedBadge />
</span>
)}
{!noBadges && <BadgeSection sender={sender} />}
{children}
</div>
</div>
);
}
``` | /content/code_sandbox/src/script/components/MessagesList/Message/ContentMessage/MessageHeader.tsx | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 860 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>mosh1</key>
<array>
<string>MAIN</string>
<string>blink_mosh_main</string>
<string></string>
<string>no</string>
</array>
<key>skstore</key>
<array>
<string>MAIN</string>
<string>skstore_main</string>
<string></string>
<string>no</string>
</array>
<key>fcp</key>
<array>
<string>MAIN</string>
<string>copyfiles_main</string>
<string></string>
<string>no</string>
</array>
<key>sftp</key>
<array>
<string>MAIN</string>
<string>copyfiles_main</string>
<string></string>
<string>no</string>
</array>
<key>scp</key>
<array>
<string>MAIN</string>
<string>copyfiles_main</string>
<string></string>
<string>no</string>
</array>
<key>ssh</key>
<array>
<string>MAIN</string>
<string>blink_ssh_main</string>
<string>axR:L:Vo:CGp:i:hqTtvl:F:</string>
<string>no</string>
</array>
<key>build</key>
<array>
<string>MAIN</string>
<string>build_main</string>
<string></string>
<string>no</string>
</array>
<key>facecam</key>
<array>
<string>MAIN</string>
<string>facecam_main</string>
<string></string>
<string>no</string>
</array>
<key>ssh-add</key>
<array>
<string>MAIN</string>
<string>blink_ssh_add</string>
<string>axR:L:Vo:CGp:i:hqTtvl:F:</string>
<string>no</string>
</array>
<key>ssh-agent</key>
<array>
<string>MAIN</string>
<string>ssh_agent_main</string>
<string>axR:L:Vo:CGp:i:hqTtvl:F:</string>
<string>no</string>
</array>
<key>help</key>
<array>
<string>MAIN</string>
<string>help_main</string>
<string></string>
<string>no</string>
</array>
<key>device-info</key>
<array>
<string>MAIN</string>
<string>device_info_main</string>
<string></string>
<string>no</string>
</array>
<key>config</key>
<array>
<string>MAIN</string>
<string>config_main</string>
<string></string>
<string>no</string>
</array>
<key>whatsnew</key>
<array>
<string>MAIN</string>
<string>whatsnew_main</string>
<string></string>
<string>no</string>
</array>
<key>clear</key>
<array>
<string>MAIN</string>
<string>clear_main</string>
<string></string>
<string>no</string>
</array>
<key>showkey</key>
<array>
<string>MAIN</string>
<string>showkey_main</string>
<string></string>
<string>no</string>
</array>
<key>history</key>
<array>
<string>MAIN</string>
<string>history_main</string>
<string>c</string>
<string>no</string>
</array>
<key>geo</key>
<array>
<string>MAIN</string>
<string>geo_main</string>
<string></string>
<string>no</string>
</array>
<key>bench</key>
<array>
<string>MAIN</string>
<string>bench_main</string>
<string></string>
<string>no</string>
</array>
<key>open</key>
<array>
<string>MAIN</string>
<string>open_main</string>
<string></string>
<string>file</string>
</array>
<key>link-files</key>
<array>
<string>MAIN</string>
<string>link_files_main</string>
<string></string>
<string>no</string>
</array>
<key>udptunnel</key>
<array>
<string>MAIN</string>
<string>udptunnel_main</string>
<string></string>
<string>no</string>
</array>
<key>say</key>
<array>
<string>MAIN</string>
<string>say_main</string>
<string>f:v:r:</string>
<string>no</string>
</array>
<key>openurl</key>
<array>
<string>MAIN</string>
<string>blink_openurl_main</string>
<string></string>
<string>no</string>
</array>
<key>code</key>
<array>
<string>MAIN</string>
<string>code_main</string>
<string></string>
<string>no</string>
</array>
<key>browse</key>
<array>
<string>MAIN</string>
<string>browse_main</string>
<string></string>
<string>no</string>
</array>
<key>xcall</key>
<array>
<string>MAIN</string>
<string>blink_xcall_main</string>
<string>ap:j:b:</string>
<string>no</string>
</array>
</dict>
</plist>
``` | /content/code_sandbox/Resources/blinkCommandsDictionary.plist | xml | 2016-03-29T10:43:10 | 2024-08-16T04:03:19 | blink | blinksh/blink | 6,114 | 1,414 |
```xml
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { SupportedViewTypes } from '../../../interfaces/db/view'
import { useCloudApi } from '../useCloudApi'
import { SerializedDashboard } from '../../../interfaces/db/dashboard'
import { SerializedTeam } from '../../../interfaces/db/team'
import { useNav } from '../../stores/nav'
import { getMapValues } from '../../../../design/lib/utils/array'
import {
SerializedQuery,
SerializedSmartView,
} from '../../../interfaces/db/smartView'
import { BulkApiActionRes } from '../../../../design/lib/hooks/useBulkApi'
import { Layout } from 'react-grid-layout'
import { isEqual, pick } from 'lodash'
import {
UpdateSmartViewRequestBody,
UpdateSmartViewResponseBody,
} from '../../../api/teams/smartViews'
interface DashboardStoreProps {
dashboard: SerializedDashboard
smartViews: SerializedSmartView[]
team: SerializedTeam
}
export type DashboardActionsRef = React.MutableRefObject<{
addSmartView: (body: {
name: string
condition: SerializedQuery
view: SupportedViewTypes
}) => Promise<BulkApiActionRes>
updateSmartView: (
smartView: SerializedSmartView,
body: UpdateSmartViewRequestBody
) => Promise<BulkApiActionRes>
removeSmartView: (smartView: SerializedSmartView) => Promise<BulkApiActionRes>
removeDashboard: () => Promise<BulkApiActionRes>
updateDashboardLayout: (layouts: Layout[]) => void
}>
export function useDashboard({
dashboard: initialDashboard,
smartViews: initialSmartViews,
team,
}: DashboardStoreProps) {
const dashboardRef = useRef(initialDashboard.id)
const [smartViews, setSmartViews] = useState(initialSmartViews)
const [dashboardData, setDashboardData] = useState(
initialDashboard.data || {}
)
const { dashboardsMap, updateViewsMap } = useNav()
const {
createSmartViewApi,
deleteDashboard,
deleteSmartViewApi,
updateDashboard,
updateSmartViewApi,
sendingMap,
} = useCloudApi()
useEffect(() => {
if (initialDashboard.id !== dashboardRef.current) {
dashboardRef.current = initialDashboard.id
setSmartViews(initialSmartViews)
setDashboardData(initialDashboard.data || {})
}
}, [initialDashboard, initialSmartViews])
const dashboard = useMemo(() => {
return getMapValues(dashboardsMap).find(
(val) => val.id === initialDashboard.id
)
}, [initialDashboard.id, dashboardsMap])
const updateDashboardLayout = useCallback(
(layouts: Layout[]) => {
const cleanedLayouts = cleanupLayouts(layouts)
if (!isEqual(dashboardData.itemsLayouts, cleanedLayouts)) {
const newData = { ...dashboardData, itemsLayouts: cleanedLayouts }
setDashboardData(newData)
updateDashboard(initialDashboard, {
data: newData,
})
}
},
[updateDashboard, initialDashboard, dashboardData]
)
const addSmartView = useCallback(
async (body: {
name: string
condition: SerializedQuery
view: SupportedViewTypes
}) => {
const res = await createSmartViewApi(team.id, {
dashboardId: initialDashboard.id,
name: body.name,
condition: body.condition,
view: body.view,
teamId: team.id,
})
if (!res.err) {
setDashboardData((prev) => {
return {
...prev,
itemsLayouts: [
...(prev.itemsLayouts || []),
{
i: res.data.data.id,
x: 0,
y: 0,
w: 3,
h: 4,
},
],
}
})
setSmartViews((prev) => [...prev, res.data.data])
updateViewsMap([res.data.data.viewId, res.data.data.view])
}
return res
},
[initialDashboard.id, team.id, createSmartViewApi, updateViewsMap]
)
const removeSmartView = useCallback(
async (smartView: SerializedSmartView) => {
const res = await deleteSmartViewApi(smartView)
if (!res.err) {
setSmartViews((prev) => prev.filter((val) => val.id !== smartView.id))
setDashboardData((prev) => {
return {
...prev,
itemsLayouts: (prev.itemsLayouts || []).filter(
(val) => val.i !== smartView.id
),
}
})
}
return res
},
[deleteSmartViewApi]
)
const updateSmartView = useCallback(
async (
smartView: SerializedSmartView,
body: UpdateSmartViewRequestBody
) => {
const res = await updateSmartViewApi(smartView, body)
if (!res.err) {
const updatedSmartviewData = res.data as UpdateSmartViewResponseBody
setSmartViews((prev) =>
prev.reduce((acc, val) => {
if (val.id === updatedSmartviewData.data.id) {
acc.push(updatedSmartviewData.data)
} else {
acc.push(val)
}
return acc
}, [] as SerializedSmartView[])
)
updateViewsMap([
updatedSmartviewData.data.viewId,
updatedSmartviewData.data.view,
])
}
return res
},
[updateSmartViewApi, updateViewsMap]
)
const removeDashboard = useCallback(async () => {
const res = await deleteDashboard(initialDashboard)
if (!res.err) {
setSmartViews([])
}
return res
}, [deleteDashboard, initialDashboard])
const actionsRef: DashboardActionsRef = useRef({
addSmartView,
removeSmartView,
removeDashboard,
updateDashboardLayout,
updateSmartView,
})
useEffect(() => {
actionsRef.current = {
addSmartView,
removeSmartView,
removeDashboard,
updateDashboardLayout,
updateSmartView,
}
}, [
addSmartView,
removeSmartView,
removeDashboard,
updateDashboardLayout,
updateSmartView,
])
return {
sendingMap,
dashboard,
smartViews,
actionsRef,
dashboardData,
}
}
function cleanupLayouts(layouts: Layout[]) {
return layouts.map((layout) => pick(layout, 'i', 'x', 'y', 'w', 'h'))
}
``` | /content/code_sandbox/src/cloud/lib/hooks/dashboards/useDashboard.ts | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 1,389 |
```xml
import { c } from 'ttag';
import { FileNameDisplay } from '@proton/components/components';
import { FilePreviewContent } from '@proton/components/containers/filePreview/FilePreview';
import { useActiveBreakpoint } from '@proton/components/hooks';
import type { DecryptedLink } from '../../store';
import { useDownloadScanFlag } from '../../store';
import { usePublicFileView } from '../../store/_views/useFileView';
import { FileBrowserStateProvider } from '../FileBrowser';
import { useUpsellFloatingModal } from '../modals/UpsellFloatingModal';
import HeaderSecureLabel from './Layout/HeaderSecureLabel';
import HeaderSize from './Layout/HeaderSize';
import SharedPageFooter from './Layout/SharedPageFooter';
import SharedPageHeader from './Layout/SharedPageHeader';
import SharedPageLayout from './Layout/SharedPageLayout';
import SharedPageTransferManager from './TransferModal/SharedPageTransferManager';
interface Props {
token: string;
link: DecryptedLink;
}
export default function SharedFilePage({ token, link }: Props) {
const { isLinkLoading, isContentLoading, error, contents, downloadFile } = usePublicFileView(token, link.linkId);
const [renderUpsellFloatingModal] = useUpsellFloatingModal();
const isDownloadScanEnabled = useDownloadScanFlag();
const { viewportWidth } = useActiveBreakpoint();
return (
<FileBrowserStateProvider itemIds={[link.linkId]}>
<SharedPageLayout
FooterComponent={<SharedPageFooter rootItem={link} items={[{ id: link.linkId, ...link }]} />}
>
<SharedPageHeader rootItem={link} items={[{ id: link.linkId, ...link }]} className="mt-3 mb-4">
<div className="w-full flex flex-nowrap flex-column md:items-center md:flex-row">
<FileNameDisplay className="text-4xl text-bold py-1 md:p-1" text={link.name} />
<div
className="flex md:flex-1 shrink-0 md:gap-4 md:flex-row-reverse md:grow-1 min-w-custom"
style={{ '--min-w-custom': 'max-content' }}
>
{!isDownloadScanEnabled ? (
<HeaderSecureLabel className="md:ml-auto" />
) : (
<div className="md:ml-auto" />
)}
{link.size ? <HeaderSize size={link.size} /> : null}
</div>
</div>
</SharedPageHeader>
<FilePreviewContent
isMetaLoading={isLinkLoading}
isLoading={isContentLoading}
onDownload={!viewportWidth['<=small'] ? downloadFile : undefined}
error={error ? error.message || error.toString?.() || c('Info').t`Unknown error` : undefined}
contents={contents}
fileName={link?.name}
mimeType={link?.mimeType}
fileSize={link?.size}
imgThumbnailUrl={link?.cachedThumbnailUrl}
isPublic
/>
</SharedPageLayout>
<SharedPageTransferManager rootItem={link} />
{renderUpsellFloatingModal}
</FileBrowserStateProvider>
);
}
``` | /content/code_sandbox/applications/drive/src/app/components/SharedPage/SharedFilePage.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 682 |
```xml
type T = {
0: string;
5: number;
}
type U = {
0: string;
"5": number;
}
``` | /content/code_sandbox/tests/format/typescript/quote-props/types.ts | xml | 2016-11-29T17:13:37 | 2024-08-16T17:29:57 | prettier | prettier/prettier | 48,913 | 35 |
```xml
'use strict';
import { inject, injectable } from 'inversify';
import { Uri } from 'vscode';
import { Product } from '../common/types';
import { IServiceContainer } from '../ioc/types';
import * as pytest from './configuration/pytest/testConfigurationManager';
import {
ITestConfigSettingsService,
ITestConfigurationManager,
ITestConfigurationManagerFactory,
} from './common/types';
import * as unittest from './configuration/unittest/testConfigurationManager';
@injectable()
export class TestConfigurationManagerFactory implements ITestConfigurationManagerFactory {
constructor(@inject(IServiceContainer) private serviceContainer: IServiceContainer) {}
public create(wkspace: Uri, product: Product, cfg?: ITestConfigSettingsService): ITestConfigurationManager {
switch (product) {
case Product.unittest: {
return new unittest.ConfigurationManager(wkspace, this.serviceContainer, cfg);
}
case Product.pytest: {
return new pytest.ConfigurationManager(wkspace, this.serviceContainer, cfg);
}
default: {
throw new Error('Invalid test configuration');
}
}
}
}
``` | /content/code_sandbox/src/client/testing/configurationFactory.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 234 |
```xml
<resources>
<string name="app_name">AndroidRoomTodoList</string>
<string name="title_activity_todo_note">TodoNoteActivity</string>
</resources>
``` | /content/code_sandbox/Android/AndroidRoom-TodoListApp/app/src/main/res/values/strings.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 38 |
```xml
<FindBugsFilter>
<Match>
<Package name="org.ballerinalang.maven" />
</Match>
<Match>
<Package name="org.ballerinalang.maven.bala.client" />
</Match>
</FindBugsFilter>
``` | /content/code_sandbox/misc/maven-resolver/spotbugs-exclude.xml | xml | 2016-11-16T14:58:44 | 2024-08-15T15:15:21 | ballerina-lang | ballerina-platform/ballerina-lang | 3,561 | 58 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<Import Project="..\..\..\configureawait.props" />
<Import Project="..\..\..\common.props" />
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<WarningsAsErrors>Nullable</WarningsAsErrors>
<AssemblyName>Volo.Abp.AspNetCore.Mvc.Client</AssemblyName>
<PackageId>Volo.Abp.AspNetCore.Mvc.Client</PackageId>
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<IsPackable>true</IsPackable>
<OutputType>Library</OutputType>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<RootNamespace />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Volo.Abp.AspNetCore.Mvc.Client.Common\Volo.Abp.AspNetCore.Mvc.Client.Common.csproj" />
<ProjectReference Include="..\Volo.Abp.EventBus\Volo.Abp.EventBus.csproj" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo.Abp.AspNetCore.Mvc.Client.csproj | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 280 |
```xml
/**
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {HighlightedToken} from './textmate-lib/tokenize';
import {CSS_CLASS_PREFIX} from './textmate-lib/textmateStyles';
import {diffWordsWithSpace} from 'diff';
/** Type of Chunk: Added, Removed, Unmodified. */
type ChunkType = 'A' | 'R' | 'U';
/**
* The Myers difference algorithm used by the `diff` Node module is O(ND) where
* N is the sum of the lengths of the two inputs and D is size of the minimum
* edit script for the two inputs. As such, large values of N can result in
* extremely long running times while likely providing little value for the
* user. For example, a large blob of JSON on a single line compared with the
* first line of the pretty-printed version (containing only `{`) could be an
* expensive diff to compute while telling the user nothing of interest.
*
* To defend against such pathological cases, we should not bother to compute
* the intraline diff in certain cases. As an initial heuristic, we impose a
* threshold for the "maximum input" (i.e., the sum of the lengths of the
* strings being compared) for which an intraline diff should be computed.
*
* Incidentally, tokenization for syntax highlighting has similar issues. At
* least as of Oct 2022, rather than impose a "max line length," VS Code imposes
* a "time spent" threshold:
*
* path_to_url#L39
*
* It might be worth considering something similar for intraline diffs.
*/
export const MAX_INPUT_LENGTH_FOR_INTRALINE_DIFF = 300;
/**
* Normalized version of a `diff.Change` returned by `diffWords()` that is
* easier to work with when interleaving with syntax higlight information.
*/
type Chunk = {
type: ChunkType;
start: number;
end: number;
};
/**
* Takes a modified line in the form of `beforeLine` and `afterLine` along with
* syntax highlighting information that covers each respective line and
* returns a ReactFragment to display the before/after versions of a line in a
* side-by-side diff.
*/
export function createTokenizedIntralineDiff(
beforeLine: string,
beforeTokens: HighlightedToken[],
afterLine: string,
afterTokens: HighlightedToken[],
): [React.ReactFragment | null, React.ReactFragment | null] {
if (beforeLine.length + afterLine.length > MAX_INPUT_LENGTH_FOR_INTRALINE_DIFF) {
return [
applyTokenizationToLine(beforeLine, beforeTokens),
applyTokenizationToLine(afterLine, afterTokens),
];
}
const changes = diffWordsWithSpace(beforeLine, afterLine);
const beforeChunks: Chunk[] = [];
const afterChunks: Chunk[] = [];
let beforeLength = 0;
let afterLength = 0;
changes.forEach(change => {
const {added, removed, value} = change;
const len = value.length;
if (added) {
const end = afterLength + len;
addOrExtend(afterChunks, 'A', afterLength, end);
afterLength = end;
} else if (removed) {
const end = beforeLength + len;
addOrExtend(beforeChunks, 'R', beforeLength, end);
beforeLength = end;
} else {
const beforeEnd = beforeLength + len;
addOrExtend(beforeChunks, 'U', beforeLength, beforeEnd);
beforeLength = beforeEnd;
const afterEnd = afterLength + len;
addOrExtend(afterChunks, 'U', afterLength, afterEnd);
afterLength = afterEnd;
}
});
// Note that the logic in mergeChunksAndTokens() could be done as part of this
// function to avoid an additional pass over the chunks, but the bookkeeping
// might get messy.
return [
mergeChunksAndTokens(beforeLine, beforeChunks, beforeTokens),
mergeChunksAndTokens(afterLine, afterChunks, afterTokens),
];
}
function addOrExtend(chunks: Chunk[], type: ChunkType, start: number, end: number) {
const lastEntry = chunks[chunks.length - 1];
if (lastEntry?.type === type && lastEntry?.end === start) {
lastEntry.end = end;
} else {
chunks.push({type, start, end});
}
}
/** TODO: Create proper machinery to strip assertions from production builds. */
const ENABLE_ASSERTIONS = false;
type ChunkSpanProps = {
key: number;
className: string;
content: string;
isChunkStart: boolean;
isChunkEnd: boolean;
};
function ChunkSpan({
key,
className,
content,
isChunkStart,
isChunkEnd,
}: ChunkSpanProps): React.ReactNode {
let fullClassName = className;
if (isChunkStart) {
fullClassName += ' patch-word-begin';
}
if (isChunkEnd) {
fullClassName += ' patch-word-end';
}
return (
<span key={key} className={fullClassName}>
{content}
</span>
);
}
/**
* Interleave chunks and tokens to produce a properly styled intraline diff.
*/
function mergeChunksAndTokens(
line: string,
chunks: Chunk[],
tokens: HighlightedToken[],
): React.ReactFragment | null {
if (tokens.length == 0) {
return null;
}
if (ENABLE_ASSERTIONS) {
// We expect the following invariants to hold, by construction.
// eslint-disable-next-line no-console
console.assert(
chunks.length !== 0,
'chunks is never empty, even if the line is the empty string',
);
// eslint-disable-next-line no-console
console.assert(
chunks[chunks.length - 1].end === tokens[tokens.length - 1].end,
'the final chunk and token must have the same end index to ensure the loop breaks properly',
);
}
const spans: ChunkSpanProps[] = [];
let chunkIndex = 0;
let tokenIndex = 0;
let lastEndIndex = 0;
let lastChunkType: ChunkType = 'U';
let isChunkStart = false;
const maxChunkIndex = chunks.length;
const maxTokenIndex = tokens.length;
while (chunkIndex < maxChunkIndex && tokenIndex < maxTokenIndex) {
const chunk = chunks[chunkIndex];
const token = tokens[tokenIndex];
const start = lastEndIndex;
if (chunk.end === token.end) {
lastEndIndex = chunk.end;
++chunkIndex;
++tokenIndex;
} else if (chunk.end < token.end) {
lastEndIndex = chunk.end;
++chunkIndex;
} else {
lastEndIndex = token.end;
++tokenIndex;
}
const chunkType = chunk.type;
if (lastChunkType !== 'U' && chunkType !== lastChunkType) {
spans[spans.length - 1].isChunkEnd = true;
}
isChunkStart = chunkType !== 'U' && (chunkType !== lastChunkType || spans.length === 0);
spans.push(createSpan(line, start, lastEndIndex, token.color, chunkType, isChunkStart));
lastChunkType = chunkType;
}
// Check if last span needs to have isChunkEnd set.
if (lastChunkType !== 'U') {
spans[spans.length - 1].isChunkEnd = true;
}
return spans.map(ChunkSpan);
}
/**
* Creates the <span> with the appropriate CSS classes to display a portion of
* an intraline diff with syntax highlighting.
*/
function createSpan(
line: string,
start: number,
end: number,
color: number,
type: ChunkType,
isChunkStart: boolean,
): ChunkSpanProps {
let patchClass;
switch (type) {
case 'U':
patchClass = '';
break;
case 'A':
patchClass = ' patch-add-word';
break;
case 'R':
patchClass = ' patch-remove-word';
break;
}
const className = `${CSS_CLASS_PREFIX}${color}${patchClass}`;
return {
key: start,
className,
content: line.slice(start, end),
isChunkStart,
isChunkEnd: false,
};
}
export function applyTokenizationToLine(
line: string,
tokenization: readonly HighlightedToken[],
): React.ReactFragment {
return tokenization.map(({start, end, color}) => {
return (
<span key={start} className={`${CSS_CLASS_PREFIX}${color}`}>
{line.slice(start, end)}
</span>
);
});
}
``` | /content/code_sandbox/addons/shared/createTokenizedIntralineDiff.tsx | xml | 2016-05-05T16:53:47 | 2024-08-16T19:12:02 | sapling | facebook/sapling | 5,987 | 1,916 |
```xml
import React from 'react'
import { Chord } from '@nivo/chord'
import styled from 'styled-components'
import chordLightNeutralImg from '../../assets/icons/chord-light-neutral.png'
import chordLightColoredImg from '../../assets/icons/chord-light-colored.png'
import chordDarkNeutralImg from '../../assets/icons/chord-dark-neutral.png'
import chordDarkColoredImg from '../../assets/icons/chord-dark-colored.png'
import { ICON_SIZE, Icon, colors, IconImg } from './styled'
import { IconType } from './types'
const Wrapper = styled.div<{
ribbonColor: string
}>`
& svg > g > g:first-child path:nth-child(1),
& svg > g > g:first-child path:nth-child(3) {
fill: none;
}
& svg > g > g:first-child path:nth-child(2),
& svg > g > g:first-child path:nth-child(4),
& svg > g > g:first-child path:nth-child(5) {
fill: ${({ ribbonColor }) => ribbonColor};
opacity: 1;
}
`
const chartProps = {
width: ICON_SIZE,
height: ICON_SIZE,
keys: ['A', 'B', 'C', 'D'],
data: [
[0, 2, 3, 0], // A
[2, 0, 0, 2], // B
[4, 0, 4, 4], // C
[0, 2, 3, 0], // D
],
margin: {
top: 1,
right: 1,
bottom: 1,
left: 1,
},
innerRadiusRatio: 0.84,
innerRadiusOffset: 0,
padAngle: 0.05,
arcBorderWidth: 0,
ribbonBorderWidth: 0,
enableLabel: false,
isInteractive: false,
animate: false,
}
const ChordIconItem = ({ type }: { type: IconType }) => (
<Icon id={`chord-${type}`} type={type}>
<Wrapper ribbonColor={colors[type].colors[1]}>
<Chord {...chartProps} colors={[colors[type].colors[4]]} />
</Wrapper>
</Icon>
)
export const ChordIcon = () => (
<>
<ChordIconItem type="lightNeutral" />
<IconImg url={chordLightNeutralImg} />
<ChordIconItem type="lightColored" />
<IconImg url={chordLightColoredImg} />
<ChordIconItem type="darkNeutral" />
<IconImg url={chordDarkNeutralImg} />
<ChordIconItem type="darkColored" />
<IconImg url={chordDarkColoredImg} />
</>
)
``` | /content/code_sandbox/website/src/components/icons/ChordIcon.tsx | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 614 |
```xml
import { IPropertyPaneCustomFieldProps, WebPartContext } from "@microsoft/sp-webpart-base";
export interface IPropertyPaneFilePickerProps {
key: string;
label?: string;
buttonLabel: string;
value: string;
disabled?: boolean;
webPartContext: WebPartContext;
disableLocalUpload?: boolean;
disableWebSearchTab?: boolean;
disableCentralAssetRepo?: boolean; // not supported yet
hasMySiteTab?: boolean;
accepts?: string;
itemType: ItemType;
required?: boolean;
onSave:(value:string)=>void;
}
export interface IPropertyPaneFilePickerPropsInternal extends IPropertyPaneCustomFieldProps, IPropertyPaneFilePickerProps {}
export enum ItemType {
Documents,
Images
}
``` | /content/code_sandbox/samples/react-comparer/src/controls/PropertyPaneFilePicker/IPropertyPaneFilePicker.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 162 |
```xml
import { promptForPylanceInstall } from '../activation/common/languageServerChangeHandler';
import { NodeLanguageServerAnalysisOptions } from '../activation/node/analysisOptions';
import { NodeLanguageClientFactory } from '../activation/node/languageClientFactory';
import { NodeLanguageServerProxy } from '../activation/node/languageServerProxy';
import { NodeLanguageServerManager } from '../activation/node/manager';
import { ILanguageServerOutputChannel } from '../activation/types';
import { IApplicationShell, ICommandManager, IWorkspaceService } from '../common/application/types';
import { PYLANCE_EXTENSION_ID } from '../common/constants';
import { IFileSystem } from '../common/platform/types';
import {
IConfigurationService,
IDisposable,
IExperimentService,
IExtensions,
IInterpreterPathService,
Resource,
} from '../common/types';
import { Pylance } from '../common/utils/localize';
import { IEnvironmentVariablesProvider } from '../common/variables/types';
import { IInterpreterService } from '../interpreter/contracts';
import { IServiceContainer } from '../ioc/types';
import { traceLog } from '../logging';
import { PythonEnvironment } from '../pythonEnvironments/info';
import { ILanguageServerExtensionManager } from './types';
export class PylanceLSExtensionManager implements IDisposable, ILanguageServerExtensionManager {
private serverProxy: NodeLanguageServerProxy;
serverManager: NodeLanguageServerManager;
clientFactory: NodeLanguageClientFactory;
analysisOptions: NodeLanguageServerAnalysisOptions;
constructor(
serviceContainer: IServiceContainer,
outputChannel: ILanguageServerOutputChannel,
experimentService: IExperimentService,
readonly workspaceService: IWorkspaceService,
readonly configurationService: IConfigurationService,
interpreterPathService: IInterpreterPathService,
_interpreterService: IInterpreterService,
environmentService: IEnvironmentVariablesProvider,
readonly commandManager: ICommandManager,
fileSystem: IFileSystem,
private readonly extensions: IExtensions,
readonly applicationShell: IApplicationShell,
) {
this.analysisOptions = new NodeLanguageServerAnalysisOptions(outputChannel, workspaceService);
this.clientFactory = new NodeLanguageClientFactory(fileSystem, extensions);
this.serverProxy = new NodeLanguageServerProxy(
this.clientFactory,
experimentService,
interpreterPathService,
environmentService,
workspaceService,
extensions,
);
this.serverManager = new NodeLanguageServerManager(
serviceContainer,
this.analysisOptions,
this.serverProxy,
commandManager,
extensions,
);
}
dispose(): void {
this.serverManager.disconnect();
this.serverManager.dispose();
this.serverProxy.dispose();
this.analysisOptions.dispose();
}
async startLanguageServer(resource: Resource, interpreter?: PythonEnvironment): Promise<void> {
await this.serverManager.start(resource, interpreter);
this.serverManager.connect();
}
async stopLanguageServer(): Promise<void> {
this.serverManager.disconnect();
await this.serverProxy.stop();
}
canStartLanguageServer(): boolean {
const extension = this.extensions.getExtension(PYLANCE_EXTENSION_ID);
return !!extension;
}
async languageServerNotAvailable(): Promise<void> {
await promptForPylanceInstall(
this.applicationShell,
this.commandManager,
this.workspaceService,
this.configurationService,
);
traceLog(Pylance.pylanceNotInstalledMessage);
}
}
``` | /content/code_sandbox/src/client/languageServer/pylanceLSExtensionManager.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 699 |
```xml
import { BuilderElement, XmlComponent } from "@file/xml-components";
// <xsd:complexType name="CT_Language">
// <xsd:attribute name="val" type="s:ST_Lang" use="optional"/>
// <xsd:attribute name="eastAsia" type="s:ST_Lang" use="optional"/>
// <xsd:attribute name="bidi" type="s:ST_Lang" use="optional"/>
// </xsd:complexType>
export interface ILanguageOptions {
readonly value?: string;
readonly eastAsia?: string;
readonly bidirectional?: string;
}
export const createLanguageComponent = (options: ILanguageOptions): XmlComponent =>
new BuilderElement<{
readonly value?: string;
readonly eastAsia?: string;
readonly bidirectional?: string;
}>({
name: "w:lang",
attributes: {
value: {
key: "w:val",
value: options.value,
},
eastAsia: {
key: "w:eastAsia",
value: options.eastAsia,
},
bidirectional: {
key: "w:bidi",
value: options.bidirectional,
},
},
});
``` | /content/code_sandbox/src/file/paragraph/run/language.ts | xml | 2016-03-26T23:43:56 | 2024-08-16T13:02:47 | docx | dolanmiu/docx | 4,139 | 253 |
```xml
import { CollapseContent, Pagination } from "@erxes/ui/src/components";
import Button from "@erxes/ui/src/components/Button";
import DataWithLoader from "@erxes/ui/src/components/DataWithLoader";
import Table from "@erxes/ui/src/components/table";
import Wrapper from "@erxes/ui/src/layout/components/Wrapper";
import { __ } from "@erxes/ui/src/utils/core";
import React from "react";
import Row from "./InventoryCategoryRow";
import { menuSyncerkhet } from "../../constants";
import { Title } from "@erxes/ui-settings/src/styles";
import { ContentBox } from "../../styles";
type Props = {
loading: boolean;
queryParams: any;
toCheckCategories: () => void;
toSyncCategories: (action: string, categories: any[]) => void;
items: any;
};
type State = {
openCollapse: number;
loading: boolean;
};
class InventoryCategory extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
openCollapse: -1,
loading: false,
};
}
renderRow = (data: any, action: string) => {
return data.map((c) => <Row key={c.code} category={c} action={action} />);
};
calculatePagination = (data: any) => {
const { queryParams } = this.props;
if (Object.keys(queryParams).length !== 0) {
if (queryParams.perPage !== undefined && queryParams.page == undefined) {
data = data.slice(queryParams.perPage * 0, queryParams.perPage * 1);
}
if (queryParams.page !== undefined) {
if (queryParams.perPage !== undefined) {
data = data.slice(
Number(queryParams.page - 1) * queryParams.perPage,
Number((queryParams.page - 1) * queryParams.perPage) +
Number(queryParams.perPage)
);
} else {
data = data.slice(
(queryParams.page - 1) * 20,
(queryParams.page - 1) * 20 + 20
);
}
}
} else {
data = data.slice(0, 20);
}
return data;
};
excludeSyncTrue = (data: any) => {
return data.filter((d) => d.syncStatus === false);
};
renderTable = (data: any, action: string) => {
data = this.calculatePagination(data);
const onClickSync = () => {
data = this.excludeSyncTrue(data);
this.props.toSyncCategories(action, data);
};
const syncButton = (
<>
<Button btnStyle="success" icon="check-circle" onClick={onClickSync}>
Sync
</Button>
</>
);
const header = (
<Wrapper.ActionBar
left={<Title>{__(`Categories`)}</Title>}
right={syncButton}
background="colorWhite"
wideSpacing={true}
/>
);
const content = (
<Table $hover={true}>
<thead>
<tr>
<th>{__("Code")}</th>
<th>{__("Name")}</th>
{action === "UPDATE" ? <th>{__("Update Status")}</th> : <></>}
{action === "CREATE" ? <th>{__("Create Status")}</th> : <></>}
{action === "DELETE" ? <th>{__("Delete Status")}</th> : <></>}
</tr>
</thead>
<tbody>{this.renderRow(data, action)}</tbody>
</Table>
);
return (
<>
{header}
<DataWithLoader
data={content}
loading={false}
count={data.length}
emptyText={"Please sync again."}
emptyIcon="leaf"
size="large"
objective={true}
/>
</>
);
};
render() {
const { items } = this.props;
const { openCollapse } = this.state;
const onClickCheck = () => {
this.props.toCheckCategories();
};
const checkOpenCollapse = (num: number): boolean => {
return openCollapse === num ? true : false;
};
const onChangeCollapse = (num: number): void => {
if (num !== openCollapse) {
this.setState({ loading: true });
this.setState({ openCollapse: num }, () => {
this.setState({ loading: false });
});
}
};
const checkButton = (
<Button btnStyle="success" icon="check-circle" onClick={onClickCheck}>
Check
</Button>
);
const content = (
<ContentBox>
<br />
<CollapseContent
title={__(
"Create categories" +
(items.create ? ": " + items.create.count : "")
)}
id={"1"}
onClick={() => {
onChangeCollapse(1);
}}
open={checkOpenCollapse(1)}
>
<>
<DataWithLoader
data={
items.create
? this.renderTable(items.create?.items, "CREATE")
: []
}
loading={false}
emptyText={"Please check first."}
emptyIcon="leaf"
size="large"
objective={true}
/>
<Pagination count={items.create?.count || 0} />
</>
</CollapseContent>
<CollapseContent
title={__(
"Update categories" +
(items.update ? ": " + items.update.count : "")
)}
id={"2"}
onClick={() => {
onChangeCollapse(2);
}}
open={checkOpenCollapse(2)}
>
<>
<DataWithLoader
data={
items.update
? this.renderTable(items.update.items, "UPDATE")
: []
}
loading={false}
emptyText={"Please check first."}
emptyIcon="leaf"
size="large"
objective={true}
/>
<Pagination count={items.update?.count || 0} />
</>
</CollapseContent>
<CollapseContent
title={__(
"Delete categories" +
(items.delete ? ": " + items.delete.count : "")
)}
id={"3"}
onClick={() => {
onChangeCollapse(3);
}}
open={checkOpenCollapse(3)}
>
<>
<DataWithLoader
data={
items.delete
? this.renderTable(items.delete.items, "DELETE")
: []
}
loading={false}
emptyText={"Please check first."}
emptyIcon="leaf"
size="large"
objective={true}
/>
<Pagination count={items.delete?.count || 0} />
</>
</CollapseContent>
</ContentBox>
);
return (
<Wrapper
header={
<Wrapper.Header
title={__(`Check category`)}
queryParams={this.props.queryParams}
submenu={menuSyncerkhet}
/>
}
content={
<DataWithLoader
data={content}
loading={this.props.loading || this.state.loading}
/>
}
actionBar={
<Wrapper.ActionBar
left={<Title>{__(`Categories`)}</Title>}
right={checkButton}
background="colorWhite"
wideSpacing={true}
/>
}
hasBorder={true}
transparent={true}
/>
);
}
}
export default InventoryCategory;
``` | /content/code_sandbox/packages/plugin-syncerkhet-ui/src/components/inventoryCategory/InventoryCategory.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,582 |
```xml
#!/usr/bin/env -S node --no-warnings --loader ts-node/esm
/**
* Wechaty Chatbot SDK - path_to_url
*
* @copyright 2016 Huan LI () <path_to_url and
* Wechaty Contributors <path_to_url
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
import { test } from 'tstest'
import { isTemplateStringArray } from './is-template-string-array.js'
test('isTemplateStringArray', async t => {
function test (
s: string | TemplateStringsArray,
...varList : unknown[]
) {
void varList
if (isTemplateStringArray(s)) {
return true
}
return false
}
const n = 42
const obj = {}
t.ok(test`foo`, 'should return true for template string')
t.ok(test`bar${n}`, 'should return true for template string with one var')
t.ok(test`obj${obj}`, 'should return true for template string with one obj')
t.notOk(test('xixi'), 'should return false for (string) call')
})
``` | /content/code_sandbox/src/pure-functions/is-template-string-array.spec.ts | xml | 2016-05-01T14:36:45 | 2024-08-16T17:27:03 | wechaty | wechaty/wechaty | 19,828 | 277 |
```xml
//
// MusicItemCollectionViewCell.m
// addproject
//
// Created by on 17/3/3.
//
#import "MusicItemCollectionViewCell.h"
#import "UIView+Tools.h"
#import "Masonry.h"
@implementation MusicItemCollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// self.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
// 83, 115
_iconImgView = [[UIImageView alloc] init];
[self addSubview:_iconImgView];
[_iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self).offset(10);
make.width.height.equalTo(@(70));
make.centerX.equalTo(self);
}];
[_iconImgView makeCornerRadius:35 borderColor:nil borderWidth:0];
_iconImgView.layer.masksToBounds = YES;
_nameLabel = [[UILabel alloc] init];
_nameLabel.textColor = [UIColor grayColor];
[_nameLabel setFont:[UIFont systemFontOfSize:11]];
_nameLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_nameLabel];
[_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self);
make.top.equalTo(_iconImgView.mas_bottom).offset(5);
make.left.right.equalTo(_iconImgView);
}];
_CheckMarkImgView = [[UIImageView alloc] init];
_CheckMarkImgView.image = [UIImage imageNamed:@"EditVideoCheckmark"];
[self addSubview:_CheckMarkImgView];
_CheckMarkImgView.frame = CGRectMake(0, 0, 83, 115);
_CheckMarkImgView.contentMode = UIViewContentModeScaleToFill;
_CheckMarkImgView.hidden = YES;
}
return self;
}
@end
``` | /content/code_sandbox/PlayerDemo/CustomVideoCamera/MusicItemCollectionViewCell.mm | xml | 2016-02-02T02:51:55 | 2024-08-09T08:55:27 | WMPlayer | zhengwenming/WMPlayer | 3,272 | 414 |
```xml
<Documentation>
<Docs DocId="T:UIKit.UIColor">
<summary>Colors and Patterns as used in MonoTouch.UIKit.</summary>
<remarks>
<para>
Basic representation for colors in UIKit. UIColors can
be created from various color representations as well as
encoding an alpha transparency channel. In addition to solid
or transparent colors, it is possible to create a UIColor
instance from an image, and use the resulting UIColor as a
brush whenever a UIKit UIColor is used.</para>
<para>
In addition to providing various constructors and some
common colors, the following colors represent system colors:
<see cref="P:UIKit.UIColor.LightTextColor" />, <see cref="P:UIKit.UIColor.DarkTextColor" />, <see cref="P:UIKit.UIColor.GroupTableViewBackgroundColor" />,
<see cref="P:UIKit.UIColor.ViewFlipsideBackgroundColor" />,
<see cref="P:UIKit.UIColor.ScrollViewTexturedBackgroundColor" />
and <see cref="P:UIKit.UIColor.UnderPageBackgroundColor" />.
</para>
<para tool="threads">The members of this class can be used from a background thread.</para>
</remarks>
<related type="externalDocumentation" href="path_to_url">Apple documentation for <c>UIColor</c></related>
</Docs>
</Documentation>
``` | /content/code_sandbox/docs/api/UIKit/UIColor.xml | xml | 2016-04-20T18:24:26 | 2024-08-16T13:29:19 | xamarin-macios | xamarin/xamarin-macios | 2,436 | 294 |
```xml
import { EntityMetadata } from "../metadata/EntityMetadata"
import { RelationMetadata } from "../metadata/RelationMetadata"
import { TypeORMError } from "./TypeORMError"
export class UsingJoinTableIsNotAllowedError extends TypeORMError {
constructor(entityMetadata: EntityMetadata, relation: RelationMetadata) {
super(
`Using JoinTable on ${entityMetadata.name}#${relation.propertyName} is wrong. ` +
`${entityMetadata.name}#${relation.propertyName} has ${relation.relationType} relation, ` +
`however you can use JoinTable only on many-to-many relations.`,
)
}
}
``` | /content/code_sandbox/src/error/UsingJoinTableIsNotAllowedError.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 130 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.percentlayout.widget.PercentRelativeLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"
android:background="@android:color/white"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground">
<ImageView
android:id="@+id/screenshot_image_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:foreground="?android:attr/selectableItemBackground"
android:scaleType="centerCrop"
app:layout_aspectRatio="100%"
app:layout_widthPercent="100%">
</ImageView>
</androidx.percentlayout.widget.PercentRelativeLayout>
``` | /content/code_sandbox/app/src/main/res/layout/layout_screenshot.xml | xml | 2016-05-21T08:47:10 | 2024-08-14T04:13:43 | JAViewer | SplashCodes/JAViewer | 4,597 | 206 |
```xml
import type { InlinePreset } from 'unimport'
import { defineUnimportPreset } from 'unimport'
const commonPresets: InlinePreset[] = [
// vue-demi (mocked)
defineUnimportPreset({
from: 'vue-demi',
imports: [
'isVue2',
'isVue3',
],
}),
]
const granularAppPresets: InlinePreset[] = [
{
from: '#app/components/nuxt-link',
imports: ['defineNuxtLink'],
},
{
imports: ['useNuxtApp', 'tryUseNuxtApp', 'defineNuxtPlugin', 'definePayloadPlugin', 'useRuntimeConfig', 'defineAppConfig'],
from: '#app/nuxt',
},
{
imports: ['requestIdleCallback', 'cancelIdleCallback'],
from: '#app/compat/idle-callback',
},
{
imports: ['setInterval'],
from: '#app/compat/interval',
},
{
imports: ['useAppConfig', 'updateAppConfig'],
from: '#app/config',
},
{
imports: ['defineNuxtComponent'],
from: '#app/composables/component',
},
{
imports: ['useAsyncData', 'useLazyAsyncData', 'useNuxtData', 'refreshNuxtData', 'clearNuxtData'],
from: '#app/composables/asyncData',
},
{
imports: ['useHydration'],
from: '#app/composables/hydrate',
},
{
imports: ['callOnce'],
from: '#app/composables/once',
},
{
imports: ['useState', 'clearNuxtState'],
from: '#app/composables/state',
},
{
imports: ['clearError', 'createError', 'isNuxtError', 'showError', 'useError'],
from: '#app/composables/error',
},
{
imports: ['useFetch', 'useLazyFetch'],
from: '#app/composables/fetch',
},
{
imports: ['useCookie', 'refreshCookie'],
from: '#app/composables/cookie',
},
{
imports: ['onPrehydrate', 'prerenderRoutes', 'useRequestHeader', 'useRequestHeaders', 'useRequestEvent', 'useRequestFetch', 'setResponseStatus'],
from: '#app/composables/ssr',
},
{
imports: ['onNuxtReady'],
from: '#app/composables/ready',
},
{
imports: ['preloadComponents', 'prefetchComponents', 'preloadRouteComponents'],
from: '#app/composables/preload',
},
{
imports: ['abortNavigation', 'addRouteMiddleware', 'defineNuxtRouteMiddleware', 'setPageLayout', 'navigateTo', 'useRoute', 'useRouter'],
from: '#app/composables/router',
},
{
imports: ['isPrerendered', 'loadPayload', 'preloadPayload', 'definePayloadReducer', 'definePayloadReviver'],
from: '#app/composables/payload',
},
{
imports: ['useLoadingIndicator'],
from: '#app/composables/loading-indicator',
},
{
imports: ['getAppManifest', 'getRouteRules'],
from: '#app/composables/manifest',
},
{
imports: ['reloadNuxtApp'],
from: '#app/composables/chunk',
},
{
imports: ['useRequestURL'],
from: '#app/composables/url',
},
{
imports: ['usePreviewMode'],
from: '#app/composables/preview',
},
{
imports: ['useId'],
from: '#app/composables/id',
},
{
imports: ['useRouteAnnouncer'],
from: '#app/composables/route-announcer',
},
]
export const scriptsStubsPreset = {
imports: [
'useScriptTriggerConsent',
'useScriptEventPage',
'useScriptTriggerElement',
'useScript',
'useScriptGoogleAnalytics',
'useScriptPlausibleAnalytics',
'useScriptCrisp',
'useScriptClarity',
'useScriptCloudflareWebAnalytics',
'useScriptFathomAnalytics',
'useScriptMatomoAnalytics',
'useScriptGoogleTagManager',
'useScriptGoogleAdsense',
'useScriptSegment',
'useScriptMetaPixel',
'useScriptXPixel',
'useScriptIntercom',
'useScriptHotjar',
'useScriptStripe',
'useScriptLemonSqueezy',
'useScriptVimeoPlayer',
'useScriptYouTubePlayer',
'useScriptGoogleMaps',
'useScriptNpm',
],
priority: -1,
from: '#app/composables/script-stubs',
} satisfies InlinePreset
// This is a separate preset as we'll swap these out for import from `vue-router` itself in `pages` module
const routerPreset = defineUnimportPreset({
imports: ['onBeforeRouteLeave', 'onBeforeRouteUpdate'],
from: '#app/composables/router',
})
// vue
const vuePreset = defineUnimportPreset({
from: 'vue',
imports: [
// <script setup>
'withCtx',
'withDirectives',
'withKeys',
'withMemo',
'withModifiers',
'withScopeId',
// Lifecycle
'onActivated',
'onBeforeMount',
'onBeforeUnmount',
'onBeforeUpdate',
'onDeactivated',
'onErrorCaptured',
'onMounted',
'onRenderTracked',
'onRenderTriggered',
'onServerPrefetch',
'onUnmounted',
'onUpdated',
// Reactivity
'computed',
'customRef',
'isProxy',
'isReactive',
'isReadonly',
'isRef',
'markRaw',
'proxyRefs',
'reactive',
'readonly',
'ref',
'shallowReactive',
'shallowReadonly',
'shallowRef',
'toRaw',
'toRef',
'toRefs',
'triggerRef',
'unref',
'watch',
'watchEffect',
'watchPostEffect',
'watchSyncEffect',
'isShallow',
// effect
'effect',
'effectScope',
'getCurrentScope',
'onScopeDispose',
// Component
'defineComponent',
'defineAsyncComponent',
'resolveComponent',
'getCurrentInstance',
'h',
'inject',
'hasInjectionContext',
'nextTick',
'provide',
'defineModel',
'defineOptions',
'defineSlots',
'mergeModels',
'toValue',
'useModel',
'useAttrs',
'useCssModule',
'useCssVars',
'useSlots',
'useTransitionState',
],
})
const vueTypesPreset = defineUnimportPreset({
from: 'vue',
type: true,
imports: [
'Component',
'ComponentPublicInstance',
'ComputedRef',
'ExtractPropTypes',
'ExtractPublicPropTypes',
'InjectionKey',
'PropType',
'Ref',
'MaybeRef',
'MaybeRefOrGetter',
'VNode',
],
})
export const defaultPresets: InlinePreset[] = [
...commonPresets,
...granularAppPresets,
routerPreset,
vuePreset,
vueTypesPreset,
]
``` | /content/code_sandbox/packages/nuxt/src/imports/presets.ts | xml | 2016-10-26T11:18:47 | 2024-08-16T19:32:46 | nuxt | nuxt/nuxt | 53,705 | 1,640 |
```xml
import { Route, Routes, useLocation } from "react-router-dom";
import React from "react";
import Settings from "./configs/general/containers/Settings";
import asyncComponent from "@erxes/ui/src/components/AsyncComponent";
import queryString from "query-string";
const VoucherCampaigns = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./configs/voucherCampaign/containers/List"
)
);
const LotteryCampaigns = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./configs/lotteryCampaign/containers/List"
)
);
const SpinCampaigns = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./configs/spinCampaign/containers/List"
)
);
const DonateCampaigns = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./configs/donateCampaign/containers/List"
)
);
const AssignmentCampaigns = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./configs/assignmentCampaign/containers/List"
)
);
const AssignmentCampaignsCreate = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./configs/assignmentCampaign/containers/CreateForm"
)
);
const AssignmentCampaignsEdit = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./configs/assignmentCampaign/containers/EditForm"
)
);
const Vouchers = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./loyalties/vouchers/containers/List"
)
);
const Lotteries = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./loyalties/lotteries/containers/List"
)
);
const Spins = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./loyalties/spins/containers/List"
)
);
const Donates = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./loyalties/donates/containers/List"
)
);
const ScoreLogs = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./loyalties/scorelogs/containers/List"
)
);
const Award = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./loyalties/lotteries/containers/Award"
)
);
const Assignments = asyncComponent(
() =>
import(
/* webpackChunkName: "KnowledgeBase" */ "./loyalties/assignments/containers/List"
)
);
const VoucherCampaignList = () => {
const location = useLocation();
return <VoucherCampaigns queryParams={queryString.parse(location.search)} />;
};
const LotteryCampaignList = () => {
const location = useLocation();
return <LotteryCampaigns queryParams={queryString.parse(location.search)} />;
};
const SpinCampaignList = () => {
const location = useLocation();
return <SpinCampaigns queryParams={queryString.parse(location.search)} />;
};
const DonateCampaignList = () => {
const location = useLocation();
return <DonateCampaigns queryParams={queryString.parse(location.search)} />;
};
const AssignmentCampaignList = () => {
const location = useLocation();
return (
<AssignmentCampaigns queryParams={queryString.parse(location.search)} />
);
};
const AssignmentCampaignCreate = () => {
const location = useLocation();
return (
<AssignmentCampaignsCreate
queryParams={queryString.parse(location.search)}
/>
);
};
const AssignmentCampaignEdit = () => {
const location = useLocation();
return (
<AssignmentCampaignsEdit queryParams={queryString.parse(location.search)} />
);
};
const VouchersComponent = () => {
const location = useLocation();
return <Vouchers queryParams={queryString.parse(location.search)} />;
};
const LotteriesComponent = () => {
const location = useLocation();
return <Lotteries queryParams={queryString.parse(location.search)} />;
};
const SpinsComponent = () => {
const location = useLocation();
return <Spins queryParams={queryString.parse(location.search)} />;
};
const DonatesComponent = () => {
const location = useLocation();
return <Donates queryParams={queryString.parse(location.search)} />;
};
const AwardComponent = () => {
const location = useLocation();
return <Award queryParams={queryString.parse(location.search)} />;
};
const Scorelogs = () => {
const location = useLocation();
return <ScoreLogs queryParams={queryString.parse(location.search)} />;
};
const AssignmentsComponent = () => {
const location = useLocation();
return <Assignments queryParams={queryString.parse(location.search)} />;
};
const routes = () => {
return (
<Routes>
<Route
path="/erxes-plugin-loyalty/settings/general"
element={<Settings />}
/>
<Route
path="/erxes-plugin-loyalty/settings/voucher"
element={<VoucherCampaignList />}
/>
<Route
path="/erxes-plugin-loyalty/settings/lottery"
element={<LotteryCampaignList />}
/>
<Route
path="/erxes-plugin-loyalty/settings/spin"
element={<SpinCampaignList />}
/>
<Route
path="/erxes-plugin-loyalty/settings/donate"
element={<DonateCampaignList />}
/>
<Route
path="/erxes-plugin-loyalty/settings/assignment"
element={<AssignmentCampaignList />}
/>
<Route
path="/erxes-plugin-loyalty/settings/assignment/create"
element={<AssignmentCampaignCreate />}
/>
<Route
path="/erxes-plugin-loyalty/settings/assignment/edit"
element={<AssignmentCampaignEdit />}
/>
<Route path="/lotteryAward" element={<AwardComponent />} />
<Route path="/vouchers" element={<VouchersComponent />} />
<Route path="/lotteries" element={<LotteriesComponent />} />
<Route path="/spins" element={<SpinsComponent />} />
<Route path="/donates" element={<DonatesComponent />} />
<Route path="/score" element={<Scorelogs />} />
<Route path="/assignments" element={<AssignmentsComponent />} />
</Routes>
);
};
export default routes;
``` | /content/code_sandbox/packages/plugin-loyalties-ui/src/routes.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,350 |
```xml
import { inject, injectable, } from 'inversify';
import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
import type { LogicalOperator } from 'estree';
import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory';
import { TStatement } from '../../types/node/TStatement';
import { ICustomCodeHelperFormatter } from '../../interfaces/custom-code-helpers/ICustomCodeHelperFormatter';
import { IOptions } from '../../interfaces/options/IOptions';
import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
import { AbstractCustomNode } from '../AbstractCustomNode';
import { NodeFactory } from '../../node/NodeFactory';
import { NodeUtils } from '../../node/NodeUtils';
@injectable()
export class LogicalExpressionFunctionNode extends AbstractCustomNode {
/**
* @type {LogicalOperator}
*/
private operator!: LogicalOperator;
/**
* @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory
* @param {ICustomCodeHelperFormatter} customCodeHelperFormatter
* @param {IRandomGenerator} randomGenerator
* @param {IOptions} options
*/
public constructor (
@inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator)
identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory,
@inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter,
@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
@inject(ServiceIdentifiers.IOptions) options: IOptions
) {
super(
identifierNamesGeneratorFactory,
customCodeHelperFormatter,
randomGenerator,
options
);
}
/**
* @param {LogicalOperator} operator
*/
public initialize (operator: LogicalOperator): void {
this.operator = operator;
}
/**
* @returns {TStatement[]}
*/
protected getNodeStructure (): TStatement[] {
const structure: TStatement = NodeFactory.expressionStatementNode(
NodeFactory.functionExpressionNode(
[
NodeFactory.identifierNode('x'),
NodeFactory.identifierNode('y')
],
NodeFactory.blockStatementNode([
NodeFactory.returnStatementNode(
NodeFactory.logicalExpressionNode(
this.operator,
NodeFactory.identifierNode('x'),
NodeFactory.identifierNode('y')
)
)
])
)
);
NodeUtils.parentizeAst(structure);
return [structure];
}
}
``` | /content/code_sandbox/src/custom-nodes/control-flow-flattening-nodes/LogicalExpressionFunctionNode.ts | xml | 2016-05-09T08:16:53 | 2024-08-16T19:43:07 | javascript-obfuscator | javascript-obfuscator/javascript-obfuscator | 13,358 | 525 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/Gatos/Gatos.csproj | xml | 2016-06-13T07:28:49 | 2024-08-16T11:02:59 | linux-tracing-workshop | goldshtn/linux-tracing-workshop | 1,262 | 121 |
```xml
<schemalist>
<schema id='org.gtk.test.schema'>
<key name='test' type='i'>
<range min='22' max='27'/>
<default>21</default>
</key>
</schema>
</schemalist>
``` | /content/code_sandbox/utilities/glib/gio/tests/schema-tests/range-low-default.gschema.xml | xml | 2016-10-27T09:31:28 | 2024-08-16T19:00:35 | nexmon | seemoo-lab/nexmon | 2,381 | 59 |
```xml
<UserControl x:Class="Dopamine.Views.FullPlayer.Collection.Collection"
x:Name="This"
xmlns="path_to_url"
xmlns:d="path_to_url"
xmlns:x="path_to_url"
xmlns:mc="path_to_url"
xmlns:prism="path_to_url"
xmlns:commonviews="clr-namespace:Dopamine.Views.Common"
xmlns:cp="clr-namespace:Dopamine.Core.Prism;assembly=Dopamine.Core"
xmlns:controls="clr-namespace:Dopamine.Controls"
xmlns:prismMvvm="clr-namespace:Prism.Mvvm;assembly=Prism.Wpf"
SizeChanged="UserControl_SizeChanged"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Background="{DynamicResource Brush_MainWindowBackground}"
prismMvvm:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="80"/>
</Grid.RowDefinitions>
<controls:TransitioningContentControl Grid.Row="0" Panel.ZIndex="0" Margin="0,0,0,-6"
FadeIn="True" FadeInTimeout="0.5" SlideIn="True" SlideInTimeout="0.5"
SlideInFrom="{Binding SlideInFrom}" SlideInTo="0" x:Name="CollectionRegion"
prism:RegionManager.RegionName="{x:Static cp:RegionNames.CollectionRegion}"/>
<Grid Grid.Row="1" Panel.ZIndex="1" DockPanel.Dock="Bottom">
<Border Panel.ZIndex="0" Background="{DynamicResource Brush_WindowHeaderBackground}"
HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Height="70"/>
<commonviews:SpectrumAnalyzerControl x:Name="SpectrumAnalyzer" Panel.ZIndex="1" VerticalAlignment="Bottom" HorizontalAlignment="Left" SizeChanged="SpectrumAnalyzer_SizeChanged"/>
<commonviews:CollectionPlaybackControls Panel.ZIndex="2" Foreground="{DynamicResource Brush_PrimaryText}"/>
</Grid>
</Grid>
</UserControl>
``` | /content/code_sandbox/Dopamine/Views/FullPlayer/Collection/Collection.xaml | xml | 2016-07-13T21:34:42 | 2024-08-15T03:30:43 | dopamine-windows | digimezzo/dopamine-windows | 1,786 | 458 |
```xml
/*
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { utils } from '@liskhq/lisk-cryptography';
import { SupportedNFTsStore } from '../../../../../src/modules/nft/stores/supported_nfts';
import { PrefixedStateReadWriter } from '../../../../../src/state_machine/prefixed_state_read_writer';
import { InMemoryPrefixedStateDB } from '../../../../../src/testing';
import { createStoreGetter } from '../../../../../src/testing/utils';
import { LENGTH_CHAIN_ID, LENGTH_COLLECTION_ID } from '../../../../../src/modules/nft/constants';
import { Modules } from '../../../../../src';
describe('NFTStore', () => {
let store: SupportedNFTsStore;
let context: Modules.StoreGetter;
beforeEach(() => {
store = new SupportedNFTsStore('NFT', 5);
const db = new InMemoryPrefixedStateDB();
const stateStore = new PrefixedStateReadWriter(db);
context = createStoreGetter(stateStore);
});
describe('save', () => {
it('should order supported NFT collection of a chain', async () => {
const chainID = Buffer.alloc(Modules.Interoperability.CHAIN_ID_LENGTH, 0);
const unsortedSupportedCollections = [
{
collectionID: Buffer.alloc(LENGTH_COLLECTION_ID, 1),
},
{
collectionID: Buffer.alloc(LENGTH_COLLECTION_ID, 0),
},
{
collectionID: Buffer.from([0, 1, 1, 0]),
},
];
const sortedSupportedCollections = unsortedSupportedCollections.sort((a, b) =>
a.collectionID.compare(b.collectionID),
);
const data = {
supportedCollectionIDArray: unsortedSupportedCollections,
};
await store.save(context, chainID, data);
await expect(store.get(context, chainID)).resolves.toEqual({
supportedCollectionIDArray: sortedSupportedCollections,
});
});
});
describe('getAll', () => {
it('should retrieve all NFTs with key between 0 and maximum value for Buffer of length LENGTH_CHAIN_ID', async () => {
await store.save(context, Buffer.alloc(LENGTH_CHAIN_ID, 0), {
supportedCollectionIDArray: [],
});
await store.save(context, Buffer.alloc(LENGTH_CHAIN_ID, 1), {
supportedCollectionIDArray: [],
});
await store.save(context, utils.getRandomBytes(LENGTH_CHAIN_ID), {
supportedCollectionIDArray: [],
});
const allSupportedNFTs = await store.getAll(context);
expect([...allSupportedNFTs.keys()]).toHaveLength(3);
});
});
});
``` | /content/code_sandbox/framework/test/unit/modules/nft/stores/supported_nfts.spec.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 641 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>ApplePS2Controller</string>
<key>CFBundleGetInfoString</key>
<key>CFBundleIdentifier</key>
<string>com.apple.driver.ApplePS2Controller</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Apple PS/2 Controller</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>1.1.5</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.1.5</string>
<key>IOKitPersonalities</key>
<dict>
<key>ApplePS2Controller</key>
<dict>
<key>CFBundleIdentifier</key>
<string>com.apple.driver.ApplePS2Controller</string>
<key>IOClass</key>
<string>ApplePS2Controller</string>
<key>IONameMatch</key>
<string>ps2controller</string>
<key>IOProviderClass</key>
<string>IOPlatformDevice</string>
</dict>
</dict>
<key>OSBundleCompatibleVersion</key>
<string>1.1.0</string>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.kpi.bsd</key>
<string>9.0.0</string>
<key>com.apple.kpi.iokit</key>
<string>9.0.0</string>
<key>com.apple.kpi.libkern</key>
<string>9.0.0</string>
<key>com.apple.kpi.mach</key>
<string>9.0.0</string>
<key>com.apple.kpi.unsupported</key>
<string>9.0.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Console</string>
</dict>
</plist>
``` | /content/code_sandbox/Clover-Configs/Acer/E5-572G/CLOVER/kexts/10.10/ApplePS2Controller.kext/Contents/Info.plist | xml | 2016-11-05T04:22:54 | 2024-08-12T19:25:53 | Hackintosh-Installer-University | huangyz0918/Hackintosh-Installer-University | 3,937 | 568 |
```xml
import { QueryResultSet } from './query-result-set';
import { AttributeJoinedData } from '../attributes/attribute-joined-data';
import { Model } from './model';
import ModelQuery from './query';
// TODO: Make mutator methods QueryResultSet.join(), QueryResultSet.clip...
export class MutableQueryResultSet<T extends Model> extends QueryResultSet<T> {
immutableClone() {
const set = new QueryResultSet({
_ids: [...this._ids],
_modelsHash: { ...this._modelsHash },
_query: this._query,
_offset: this._offset,
});
Object.freeze(set._ids);
Object.freeze(set._modelsHash);
return set;
}
clipToRange(range) {
if (range.isInfinite()) {
return;
}
if (range.offset > this._offset) {
this._ids = this._ids.slice(range.offset - this._offset);
this._offset = range.offset;
}
const rangeEnd = range.offset + range.limit;
const selfEnd = this._offset + this._ids.length;
if (rangeEnd < selfEnd) {
this._ids.length = Math.max(0, rangeEnd - this._offset);
}
const models = this.models();
this._modelsHash = {};
this._idToIndexHash = null;
models.forEach(m => this.updateModel(m));
}
addModelsInRange(rangeModels: T[], range) {
this.addIdsInRange(rangeModels.map(m => m.id), range);
rangeModels.forEach(m => this.updateModel(m));
}
addIdsInRange(rangeIds: string[], range) {
if (this._offset === null || range.isInfinite()) {
this._ids = rangeIds;
this._idToIndexHash = null;
this._offset = range.offset;
} else {
const currentEnd = this._offset + this._ids.length;
const rangeIdsEnd = range.offset + rangeIds.length;
if (rangeIdsEnd < this._offset) {
throw new Error(
`addIdsInRange: You can only add adjacent values (${rangeIdsEnd} < ${this._offset})`
);
}
if (range.offset > currentEnd) {
throw new Error(
`addIdsInRange: You can only add adjacent values (${range.offset} > ${currentEnd})`
);
}
let existingBefore = [];
if (range.offset > this._offset) {
existingBefore = this._ids.slice(0, range.offset - this._offset);
}
let existingAfter = [];
if (rangeIds.length === range.limit && currentEnd > rangeIdsEnd) {
existingAfter = this._ids.slice(rangeIdsEnd - this._offset);
}
this._ids = [].concat(existingBefore, rangeIds, existingAfter);
this._idToIndexHash = null;
this._offset = Math.min(this._offset, range.offset);
}
}
updateModel(item: T) {
if (!item) {
return;
}
// Sometimes the new copy of `item` doesn't contain the joined data present
// in the old one, since it's not provided by default and may not have changed.
// Make sure we never drop joined data by pulling it over.
const existing = this._modelsHash[item.id];
if (existing) {
const attrs = existing.constructor.attributes;
for (const key of Object.keys(attrs)) {
const attr = attrs[key];
if (attr instanceof AttributeJoinedData && item[attr.modelKey] === undefined) {
item[attr.modelKey] = existing[attr.modelKey];
}
}
}
this._modelsHash[item.id] = item;
}
removeModelAtOffset(item: T, offset) {
const idx = offset - this._offset;
delete this._modelsHash[item.id];
this._ids.splice(idx, 1);
this._idToIndexHash = null;
}
setQuery(query: ModelQuery<T> | ModelQuery<T[]>) {
this._query = query.clone();
this._query.finalize();
}
}
``` | /content/code_sandbox/app/src/flux/models/mutable-query-result-set.ts | xml | 2016-10-13T06:45:50 | 2024-08-16T18:14:37 | Mailspring | Foundry376/Mailspring | 15,331 | 877 |
```xml
import { Action, Name } from "../../styles";
import {
Alert,
Button,
DropdownToggle,
Icon,
MainStyleInfoWrapper as InfoWrapper,
ModalTrigger,
Sidebar,
__,
confirm,
} from "@erxes/ui/src";
import Attachment from "@erxes/ui/src/components/Attachment";
import CarForm from "../../containers/CarForm";
import DetailInfo from "./DetailInfo";
import Dropdown from "@erxes/ui/src/components/Dropdown";
import { IAttachment } from "@erxes/ui/src/types";
import { ICar } from "../../types";
import React from "react";
type Props = {
car: ICar;
remove: () => void;
};
const { Section } = Sidebar;
const BasicInfoSection = (props: Props) => {
const { car, remove } = props;
const renderImage = (item?: IAttachment) => {
if (!item) {
return null;
}
return <Attachment attachment={item} />;
};
const renderAction = () => {
const onDelete = () =>
confirm()
.then(() => remove())
.catch((error) => {
Alert.error(error.message);
});
const carForm = (props) => <CarForm {...props} car={car} />;
const menuItems = [
{
title: "Edit basic info",
trigger: <a href="#edit">{__("Edit")}</a>,
content: carForm,
additionalModalProps: { size: "lg" },
},
];
return (
<Action>
<Dropdown
as={DropdownToggle}
toggleComponent={
<Button btnStyle="simple" size="medium">
{__("Action")}
<Icon icon="angle-down" />
</Button>
}
modalMenuItems={menuItems}
>
<li>
<a href="#delete" onClick={onDelete}>
{__("Delete")}
</a>
</li>
</Dropdown>
</Action>
);
};
return (
<Sidebar.Section>
<InfoWrapper>
<Name>{car.plateNumber}</Name>
{renderAction()}
</InfoWrapper>
{renderImage(car.attachment)}
<Section>
<DetailInfo car={car} />
</Section>
</Sidebar.Section>
);
};
export default BasicInfoSection;
``` | /content/code_sandbox/packages/plugin-cars-ui/src/components/common/BasicInfoSection.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 498 |
```xml
import React, { FunctionComponent } from "react";
export interface OptGroupProps {
label: string;
children?: React.ReactNode;
}
const OptionGroup: FunctionComponent<OptGroupProps> = (props) => {
return <optgroup {...props} />;
};
export default OptionGroup;
``` | /content/code_sandbox/client/src/core/client/ui/components/v2/SelectField/OptGroup.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 61 |
```xml
/* tslint:disable */
export default {
color: [
'#523e85',
'#8b4f8f',
'#b96595',
'#e0829a',
'#ffa3a2',
'#f9b8a3',
'#f1ccb1',
'#ebddc8',
],
backgroundColor: 'transparent',
textStyle: {},
title: {
textStyle: {
color: '#aaaaaa',
},
subtextStyle: {
color: '#aaaaaa',
},
},
tree: {
itemStyle: {
color: '#ffa3a2',
borderColor: '#523e85',
},
},
line: {
itemStyle: {
normal: {
borderWidth: '2',
},
},
lineStyle: {
normal: {
width: '2',
},
},
symbolSize: '6',
symbol: 'emptyCircle',
smooth: true,
},
radar: {
itemStyle: {
normal: {
borderWidth: '2',
},
},
lineStyle: {
normal: {
width: '2',
},
},
symbolSize: '6',
symbol: 'emptyCircle',
smooth: true,
},
bar: {
itemStyle: {
normal: {
barBorderWidth: 0,
barBorderColor: '#ccc',
},
emphasis: {
barBorderWidth: 0,
barBorderColor: '#ccc',
},
},
},
pie: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
emphasis: {
borderWidth: 0,
borderColor: '#ccc',
},
},
},
scatter: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
emphasis: {
borderWidth: 0,
borderColor: '#ccc',
},
},
},
boxplot: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
emphasis: {
borderWidth: 0,
borderColor: '#ccc',
},
},
},
parallel: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
emphasis: {
borderWidth: 0,
borderColor: '#ccc',
},
},
},
sankey: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
emphasis: {
borderWidth: 0,
borderColor: '#ccc',
},
},
},
funnel: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
emphasis: {
borderWidth: 0,
borderColor: '#ccc',
},
},
},
gauge: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
emphasis: {
borderWidth: 0,
borderColor: '#ccc',
},
},
},
candlestick: {
itemStyle: {
normal: {
color: '#8b4f8f',
color0: '#ffa3a2',
borderColor: '#8b4f8f',
borderColor0: '#ffa3a2',
borderWidth: '2',
},
},
},
graph: {
itemStyle: {
normal: {
borderWidth: 0,
borderColor: '#ccc',
},
},
lineStyle: {
normal: {
width: 1,
color: '#aaaaaa',
},
},
symbolSize: '6',
symbol: 'emptyCircle',
smooth: true,
color: [
'#523e85',
'#8b4f8f',
'#b96595',
'#e0829a',
'#ffa3a2',
'#f9b8a3',
'#f1ccb1',
'#ebddc8',
],
label: {
normal: {
textStyle: {
color: '#ffffff',
},
},
},
},
map: {
itemStyle: {
normal: {
areaColor: '#f3f3f3',
borderColor: '#999999',
borderWidth: 0.5,
},
emphasis: {
areaColor: 'rgba(255,178,72,1)',
borderColor: '#eb8146',
borderWidth: 1,
},
},
label: {
normal: {
textStyle: {
color: '#523e85',
},
},
emphasis: {
textStyle: {
color: 'rgb(82,62,133)',
},
},
},
},
geo: {
itemStyle: {
normal: {
areaColor: '#f3f3f3',
borderColor: '#999999',
borderWidth: 0.5,
},
emphasis: {
areaColor: 'rgba(255,178,72,1)',
borderColor: '#eb8146',
borderWidth: 1,
},
},
label: {
normal: {
textStyle: {
color: '#523e85',
},
},
emphasis: {
textStyle: {
color: 'rgb(82,62,133)',
},
},
},
},
categoryAxis: {
axisLine: {
show: true,
lineStyle: {
color: '#aaaaaa',
},
},
axisTick: {
show: false,
lineStyle: {
color: '#333',
},
},
axisLabel: {
show: true,
textStyle: {
color: '#999999',
},
},
splitLine: {
show: true,
lineStyle: {
color: ['#e6e6e6'],
},
},
splitArea: {
show: false,
areaStyle: {
color: ['rgba(250,250,250,0.05)', 'rgba(200,200,200,0.02)'],
},
},
},
valueAxis: {
axisLine: {
show: true,
lineStyle: {
color: '#aaaaaa',
},
},
axisTick: {
show: false,
lineStyle: {
color: '#333',
},
},
axisLabel: {
show: true,
textStyle: {
color: '#999999',
},
},
splitLine: {
show: true,
lineStyle: {
color: ['#e6e6e6'],
},
},
splitArea: {
show: false,
areaStyle: {
color: ['rgba(250,250,250,0.05)', 'rgba(200,200,200,0.02)'],
},
},
},
logAxis: {
axisLine: {
show: true,
lineStyle: {
color: '#aaaaaa',
},
},
axisTick: {
show: false,
lineStyle: {
color: '#333',
},
},
axisLabel: {
show: true,
textStyle: {
color: '#999999',
},
},
splitLine: {
show: true,
lineStyle: {
color: ['#e6e6e6'],
},
},
splitArea: {
show: false,
areaStyle: {
color: ['rgba(250,250,250,0.05)', 'rgba(200,200,200,0.02)'],
},
},
},
timeAxis: {
axisLine: {
show: true,
lineStyle: {
color: '#aaaaaa',
},
},
axisTick: {
show: false,
lineStyle: {
color: '#333',
},
},
axisLabel: {
show: true,
textStyle: {
color: '#999999',
},
},
splitLine: {
show: true,
lineStyle: {
color: ['#e6e6e6'],
},
},
splitArea: {
show: false,
areaStyle: {
color: ['rgba(250,250,250,0.05)', 'rgba(200,200,200,0.02)'],
},
},
},
toolbox: {
iconStyle: {
normal: {
borderColor: '#999999',
},
emphasis: {
borderColor: '#666666',
},
},
},
legend: {
textStyle: {
color: '#000000',
},
},
tooltip: {
axisPointer: {
lineStyle: {
color: '#cccccc',
width: 1,
},
crossStyle: {
color: '#cccccc',
width: 1,
},
},
},
timeline: {
lineStyle: {
color: '#523e85',
width: 1,
},
itemStyle: {
normal: {
color: '#523e85',
borderWidth: 1,
},
emphasis: {
color: '#ffb248',
},
},
controlStyle: {
normal: {
color: '#523e85',
borderColor: '#523e85',
borderWidth: 0.5,
},
emphasis: {
color: '#523e85',
borderColor: '#523e85',
borderWidth: 0.5,
},
},
checkpointStyle: {
color: '#eb8146',
borderColor: 'rgba(255,178,72,0.41)',
},
label: {
normal: {
textStyle: {
color: '#523e85',
},
},
emphasis: {
textStyle: {
color: '#523e85',
},
},
},
},
visualMap: {
color: [
'#523e85',
'#8b4f8f',
'#b96595',
'#e0829a',
'#ffa3a2',
'#f9b8a3',
'#f1ccb1',
'#ebddc8',
],
},
dataZoom: {
backgroundColor: 'rgba(255,255,255,0)',
dataBackgroundColor: 'rgba(255,178,72,0.5)',
fillerColor: 'rgba(255,178,72,0.15)',
handleColor: '#ffb248',
handleSize: '100%',
textStyle: {
color: '#aaaaaa',
},
},
markPoint: {
label: {
normal: {
textStyle: {
color: '#ffffff',
},
},
emphasis: {
textStyle: {
color: '#ffffff',
},
},
},
},
};
``` | /content/code_sandbox/libs/angular-echarts/base/src/themes/razzleberry-pie.ts | xml | 2016-07-11T23:30:52 | 2024-08-15T15:20:45 | covalent | Teradata/covalent | 2,228 | 2,336 |
```xml
import { fs } from "apollo-codegen-core/lib/localfs";
import path from "path";
import { GraphQLSchema, DocumentNode, print } from "graphql";
import URI from "vscode-uri";
import {
compileToIR,
CompilerContext,
CompilerOptions,
} from "apollo-codegen-core/lib/compiler";
import {
compileToLegacyIR,
CompilerOptions as LegacyCompilerOptions,
} from "apollo-codegen-core/lib/compiler/legacyIR";
import serializeToJSON from "apollo-codegen-core/lib/serializeToJSON";
import { BasicGeneratedFile } from "apollo-codegen-core/lib/utilities/CodeGenerator";
import { generateSource as generateSwiftSource } from "apollo-codegen-swift";
import { generateSource as generateFlowSource } from "apollo-codegen-flow";
import {
generateLocalSource as generateTypescriptLocalSource,
generateGlobalSource as generateTypescriptGlobalSource,
} from "apollo-codegen-typescript";
import { generateSource as generateScalaSource } from "apollo-codegen-scala";
import { FlowCompilerOptions } from "../../apollo-codegen-flow/lib/language";
import { validateQueryDocument } from "apollo-language-server/lib/errors/validation";
import { DEFAULT_FILE_EXTENSION as TYPESCRIPT_DEFAULT_FILE_EXTENSION } from "apollo-codegen-typescript/lib/helpers";
export type TargetType =
| "json"
| "json-modern"
| "swift"
| "scala"
| "flow"
| "typescript"
| "ts";
export type GenerationOptions = CompilerOptions &
LegacyCompilerOptions &
FlowCompilerOptions & {
globalTypesFile?: string;
tsFileExtension?: string;
rootPath?: string;
};
function toPath(uri: string): string {
return URI.parse(uri).fsPath;
}
export default function generate(
document: DocumentNode,
schema: GraphQLSchema,
outputPath: string,
only: string | undefined,
target: TargetType,
tagName: string,
nextToSources: boolean | string,
options: GenerationOptions
): number {
let writtenFiles = 0;
validateQueryDocument(schema, document);
const { rootPath = process.cwd() } = options;
if (outputPath.split(".").length <= 1 && !fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath);
}
if (target === "swift") {
options.addTypename = true;
const context = compileToIR(schema, document, options);
const outputIndividualFiles =
fs.existsSync(outputPath) && fs.statSync(outputPath).isDirectory();
const suppressSwiftMultilineStringLiterals = Boolean(
options.suppressSwiftMultilineStringLiterals
);
const generator = generateSwiftSource(
context,
outputIndividualFiles,
suppressSwiftMultilineStringLiterals,
only
);
if (outputIndividualFiles) {
writeGeneratedFiles(generator.generatedFiles, outputPath, "\n");
writtenFiles += Object.keys(generator.generatedFiles).length;
} else {
fs.writeFileSync(outputPath, generator.output.concat("\n"));
writtenFiles += 1;
}
if (options.generateOperationIds) {
writeOperationIdsMap(context);
writtenFiles += 1;
}
} else if (target === "flow") {
const context = compileToIR(schema, document, options);
const { generatedFiles, common } = generateFlowSource(context);
const outFiles: {
[fileName: string]: BasicGeneratedFile;
} = {};
if (nextToSources) {
generatedFiles.forEach(({ sourcePath, fileName, content }) => {
const dir = path.join(
path.dirname(path.posix.relative(rootPath, toPath(sourcePath))),
outputPath
);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
outFiles[path.join(dir, fileName)] = {
output: content.fileContents + common,
};
});
writeGeneratedFiles(outFiles, path.resolve("."));
writtenFiles += Object.keys(outFiles).length;
} else if (
fs.existsSync(outputPath) &&
fs.statSync(outputPath).isDirectory()
) {
generatedFiles.forEach(({ fileName, content }) => {
outFiles[fileName] = {
output: content.fileContents + common,
};
});
writeGeneratedFiles(outFiles, outputPath);
writtenFiles += Object.keys(outFiles).length;
} else {
fs.writeFileSync(
outputPath,
generatedFiles.map((o) => o.content.fileContents).join("\n") + common
);
writtenFiles += 1;
}
} else if (target === "typescript" || target === "ts") {
const context = compileToIR(schema, document, options);
const generatedFiles = generateTypescriptLocalSource(context);
const generatedGlobalFile = generateTypescriptGlobalSource(context);
const outFiles: {
[fileName: string]: BasicGeneratedFile;
} = {};
if (
nextToSources ||
(fs.existsSync(outputPath) && fs.statSync(outputPath).isDirectory())
) {
if (options.globalTypesFile) {
const globalTypesDir = path.dirname(options.globalTypesFile);
if (!fs.existsSync(globalTypesDir)) {
fs.mkdirSync(globalTypesDir);
}
} else if (nextToSources && !fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath);
}
const globalSourcePath =
options.globalTypesFile ||
path.join(
outputPath,
`globalTypes.${
options.tsFileExtension || TYPESCRIPT_DEFAULT_FILE_EXTENSION
}`
);
outFiles[globalSourcePath] = {
output: generatedGlobalFile.fileContents,
};
generatedFiles.forEach(({ sourcePath, fileName, content }) => {
let dir = outputPath;
if (nextToSources) {
dir = path.join(
path.dirname(path.relative(rootPath, toPath(sourcePath))),
dir
);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
}
const outFilePath = path.join(dir, fileName);
outFiles[outFilePath] = {
output: content({ outputPath: outFilePath, globalSourcePath })
.fileContents,
};
});
writeGeneratedFiles(outFiles, path.resolve("."));
writtenFiles += Object.keys(outFiles).length;
} else {
fs.writeFileSync(
outputPath,
generatedFiles.map((o) => o.content().fileContents).join("\n") +
"\n" +
generatedGlobalFile.fileContents
);
writtenFiles += 1;
}
} else {
let output;
const context = compileToLegacyIR(schema, document, {
...options,
exposeTypeNodes: target === "json-modern",
});
switch (target) {
case "json-modern":
case "json":
output = serializeToJSON(context, {
exposeTypeNodes: Boolean(options.exposeTypeNodes),
});
break;
case "scala":
output = generateScalaSource(context);
}
if (outputPath) {
fs.writeFileSync(outputPath, output);
writtenFiles += 1;
} else {
console.log(output);
}
}
return writtenFiles;
}
function writeGeneratedFiles(
generatedFiles: { [fileName: string]: BasicGeneratedFile },
outputDirectory: string,
terminator: string = ""
) {
for (const [fileName, generatedFile] of Object.entries(generatedFiles)) {
fs.writeFileSync(
path.join(outputDirectory, fileName),
generatedFile.output.concat(terminator)
);
}
}
interface OperationIdsMap {
name: string;
source: string;
}
function writeOperationIdsMap(context: CompilerContext) {
let operationIdsMap: { [id: string]: OperationIdsMap } = {};
Object.keys(context.operations)
.map((k) => context.operations[k])
.forEach((operation) => {
operationIdsMap[operation.operationId!] = {
name: operation.operationName,
source: operation.sourceWithFragments!,
};
});
fs.writeFileSync(
context.options.operationIdsPath,
JSON.stringify(operationIdsMap, null, 2)
);
}
``` | /content/code_sandbox/packages/apollo/src/generate.ts | xml | 2016-08-12T15:28:09 | 2024-08-03T08:25:34 | apollo-tooling | apollographql/apollo-tooling | 3,040 | 1,728 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="path_to_url">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{d092ad6f-cf1e-4b26-ab45-7a2b04aa64ab}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\FT_MODULES">
<UniqueIdentifier>{8839144b-d0ac-4855-8366-36bd1343a544}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{e9257cfe-7fd4-482d-aa81-a52ea9f340b6}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\external\freetype-2.4.12\src\autofit\autofit.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\bdf\bdf.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\cff\cff.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftbase.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftbitmap.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\cache\ftcache.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftfstype.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftgasp.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftglyph.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\gzip\ftgzip.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftinit.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\lzw\ftlzw.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftstroke.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftsystem.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\smooth\smooth.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftbbox.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftmm.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftpfr.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftsynth.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\fttype1.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftwinfnt.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftxf86.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftlcdfil.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftgxval.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftotval.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\base\ftpatent.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\pcf\pcf.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\pfr\pfr.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\psaux\psaux.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\pshinter\pshinter.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\psnames\psmodule.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\raster\raster.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\sfnt\sfnt.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\truetype\truetype.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\type1\type1.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\cid\type1cid.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\type42\type42.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
<ClCompile Include="..\..\external\freetype-2.4.12\src\winfonts\winfnt.c">
<Filter>Source Files\FT_MODULES</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\external\freetype-2.4.12\include\freetype\config\ftconfig.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\external\freetype-2.4.12\include\freetype\config\ftheader.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\external\freetype-2.4.12\include\freetype\config\ftmodule.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\external\freetype-2.4.12\include\freetype\config\ftoption.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\external\freetype-2.4.12\include\freetype\config\ftstdlib.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\external\freetype-2.4.12\include\ft2build.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
``` | /content/code_sandbox/extensions/android/ringlibsdl/project/jni/SDL2_ttf/VisualC-WinRT/WinRT80_VS2012/freetype-WinRT80.vcxproj.filters | xml | 2016-03-24T10:29:27 | 2024-08-16T12:53:07 | ring | ring-lang/ring | 1,262 | 2,088 |
```xml
export default function Page() {
return <p>app-edge-ssr</p>
}
export const runtime = 'edge'
export const maxDuration = 4
``` | /content/code_sandbox/test/e2e/app-dir/with-exported-function-config/app/app-ssr-edge/page.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 36 |
```xml
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnApplicationShutdown,
} from '@nestjs/common';
import { EntitiesService } from '../../entities/entities.service';
import { ConfigService } from '../../config/config.service';
import { OmronD6tConfig } from './omron-d6t.config';
import i2cBus, { PromisifiedBus } from 'i2c-bus';
import { Interval } from '@nestjs/schedule';
import * as math from 'mathjs';
import { Sensor } from '../../entities/sensor';
import { Entity } from '../../entities/entity.dto';
import { I2CError } from './i2c.error';
import { SensorConfig } from '../home-assistant/sensor-config';
import { ThermopileOccupancyService } from '../../integration-support/thermopile/thermopile-occupancy.service';
import { Camera } from '../../entities/camera';
import { Mutex } from 'async-mutex';
const TEMPERATURE_COMMAND = 0x4c;
@Injectable()
export class OmronD6tService
extends ThermopileOccupancyService
implements OnApplicationBootstrap, OnApplicationShutdown {
private readonly config: OmronD6tConfig;
private i2cBus: PromisifiedBus;
private sensor: Entity;
private camera: Camera;
private readonly heatmapMutex = new Mutex();
private readonly logger: Logger;
constructor(
private readonly entitiesService: EntitiesService,
private readonly configService: ConfigService
) {
super();
this.config = this.configService.get('omronD6t');
this.logger = new Logger(OmronD6tService.name);
}
/**
* Lifecycle hook, called once the application has started.
*/
async onApplicationBootstrap(): Promise<void> {
this.logger.log(`Opening i2c bus ${this.config.busNumber}`);
this.i2cBus = await i2cBus.openPromisified(this.config.busNumber);
this.sensor = this.createSensor();
if (this.config.heatmap.enabled) {
if (this.isHeatmapAvailable()) {
this.camera = this.createHeatmapCamera();
} else {
this.logger.error(
"Heatmaps cannot be rendered since the required dependencies aren't available. More info: path_to_url#requirements"
);
}
}
}
/**
* Lifecycle hook, called once the application is shutting down.
*/
async onApplicationShutdown(): Promise<void> {
this.logger.log(`Closing i2c bus ${this.config.busNumber}`);
return this.i2cBus.close();
}
/**
* Updates the state of the entities that this integration manages.
*/
@Interval(250)
async updateState(): Promise<void> {
try {
const temperatures = await this.getPixelTemperatures();
const coordinates = await this.getCoordinates(
temperatures,
this.config.deltaThreshold
);
this.sensor.state = coordinates.length;
this.sensor.attributes.coordinates = coordinates;
if (this.camera != undefined && !this.heatmapMutex.isLocked()) {
await this.heatmapMutex.runExclusive(async () => {
this.camera.state = await this.generateHeatmap(
temperatures,
this.config.heatmap
);
});
}
} catch (e) {
if (e instanceof I2CError) {
this.logger.debug(`Error during I2C communication: ${e.message}`);
} else {
this.logger.error(
`Retrieving the state from D6T sensor failed: ${e.message}`,
e.stack
);
}
}
}
/**
* Gets the temperatures of all sensor pixels.
*
* @returns 4x4 matrix of temperatures
*/
async getPixelTemperatures(): Promise<number[][]> {
const commandBuffer = Buffer.alloc(1);
const resultBuffer = Buffer.alloc(35);
commandBuffer.writeUInt8(TEMPERATURE_COMMAND, 0);
await this.i2cBus.i2cWrite(
this.config.address,
commandBuffer.length,
commandBuffer
);
await this.i2cBus.i2cRead(
this.config.address,
resultBuffer.length,
resultBuffer
);
if (!this.checkPEC(resultBuffer, 34)) {
throw new I2CError('PEC check for the message failed');
}
const pixelTemperatures = [];
for (let i = 2; i < resultBuffer.length - 1; i += 2) {
const temperature =
(256 * resultBuffer.readUInt8(i + 1) + resultBuffer.readUInt8(i)) / 10;
pixelTemperatures.push(temperature);
}
return math.reshape(pixelTemperatures, [4, 4]) as number[][];
}
/**
* Performs a packet error check on the message.
*
* @param buffer - Message to be checked
* @param pecIndex - Index of the PEC value in the message
* @returns Message is valid or not
*/
checkPEC(buffer: Buffer, pecIndex: number): boolean {
let crc = this.calculateCRC(0x15);
for (let i = 0; i < pecIndex; i++) {
crc = this.calculateCRC(buffer.readUInt8(i) ^ crc);
}
return crc === buffer.readUInt8(pecIndex);
}
/**
* Calculates a cyclic redundancy check value.
*
* @param data - Number to calculate the value for
* @returns Check value
*/
calculateCRC(data: number): number {
const crc = new Uint8Array([data]);
for (let i = 0; i < 8; i++) {
const temp = crc[0];
crc[0] = crc[0] << 1;
if (temp & 0x80) {
crc[0] = crc[0] ^ 0x07;
}
}
return crc[0];
}
/**
* Creates and registers a new occupancy count sensor.
*
* @returns Registered sensor
*/
protected createSensor(): Sensor {
const customizations = [
{
for: SensorConfig,
overrides: {
icon: 'mdi:account',
unitOfMeasurement: 'person',
},
},
];
return this.entitiesService.add(
new Sensor('d6t_occupancy_count', 'D6T Occupancy Count'),
customizations
) as Sensor;
}
/**
* Creates and registers a new heatmap camera entity.
*
* @returns Registered camera
*/
protected createHeatmapCamera(): Camera {
return this.entitiesService.add(
new Camera('d6t_heatmap', 'D6T Heatmap')
) as Camera;
}
}
``` | /content/code_sandbox/src/integrations/omron-d6t/omron-d6t.service.ts | xml | 2016-08-18T18:50:21 | 2024-08-12T16:12:05 | room-assistant | mKeRix/room-assistant | 1,255 | 1,450 |
```xml
<clickhouse>
<encryption_codecs>
<aes_128_gcm_siv>
<key_hex>a32902703dab1cedd7ff7287067787ca</key_hex>
</aes_128_gcm_siv>
<aes_256_gcm_siv>
<key_hex>your_sha256_hash</key_hex>
</aes_256_gcm_siv>
</encryption_codecs>
</clickhouse>
``` | /content/code_sandbox/tests/config/config.d/encryption.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 98 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/// <reference types="@stdlib/types"/>
import { ArrayLike, Collection } from '@stdlib/types/array';
import { Mode } from '@stdlib/types/ndarray';
/**
* Input nested array.
*/
type NestedArray<T> = ArrayLike<Collection<T>>;
/**
* Output array when operating along the first dimension.
*/
type OutputArrayDim0<T> = Array<Collection<T>>;
/**
* Output array when operating along the second dimension.
*/
type OutputArrayDim1<T> = Array<Array<T>>;
/**
* Takes elements from a two-dimensional nested array.
*
* ## Notes
*
* - The function does **not** deep copy nested array elements.
*
* @param x - input nested array
* @param indices - list of indices
* @param dimension - dimension along which to take elements
* @param mode - index mode specifying how to handle an index which is out-of-bounds
* @returns output array
*
* @example
* var x = [ [ 1, 2 ], [ 3, 4 ] ];
* var indices = [ 1, -2 ];
*
* var y = take2d( x, indices, 0, 'normalize' );
* // returns [ [ 3, 4 ], [ 1, 2 ] ]
*/
declare function take2d<T = unknown>( x: NestedArray<T>, indices: Collection<number>, dimension: 0, mode: Mode ): OutputArrayDim0<T>;
/**
* Takes elements from a two-dimensional nested array.
*
* ## Notes
*
* - The function does **not** deep copy nested array elements.
*
* @param x - input nested array
* @param indices - list of indices
* @param dimension - dimension along which to take elements
* @param mode - index mode specifying how to handle an index which is out-of-bounds
* @returns output array
*
* @example
* var x = [ [ 1, 2 ], [ 3, 4 ] ];
* var indices = [ 1, 1, 0, 0, -1, -1 ];
*
* var y = take2d( x, indices, 1, 'normalize' );
* // returns [ [ 2, 2, 1, 1, 2, 2 ], [ 4, 4, 3, 3, 4, 4 ] ]
*/
declare function take2d<T = unknown>( x: NestedArray<T>, indices: Collection<number>, dimension: 1, mode: Mode ): OutputArrayDim1<T>;
/**
* Takes elements from a two-dimensional nested array.
*
* ## Notes
*
* - The function does **not** deep copy nested array elements.
*
* @param x - input nested array
* @param indices - list of indices
* @param dimension - dimension along which to take elements
* @param mode - index mode specifying how to handle an index which is out-of-bounds
* @returns output array
*
* @example
* var x = [ [ 1, 2 ], [ 3, 4 ] ];
* var indices = [ 1, 1, 0, 0, -1, -1 ];
*
* var y = take2d( x, indices, 1, 'normalize' );
* // returns [ [ 2, 2, 1, 1, 2, 2 ], [ 4, 4, 3, 3, 4, 4 ] ]
*/
declare function take2d<T = unknown>( x: NestedArray<T>, indices: Collection<number>, dimension: number, mode: Mode ): NestedArray<T>;
// EXPORTS //
export = take2d;
``` | /content/code_sandbox/lib/node_modules/@stdlib/array/base/take2d/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 843 |
```xml
import { Link } from 'ice';
export default function About() {
return (
<>
<h2>About Page</h2>
<Link to="/">home</Link>
</>
);
}
``` | /content/code_sandbox/examples/icestark-layout/src/pages/about.tsx | xml | 2016-11-03T06:59:15 | 2024-08-16T10:11:29 | ice | alibaba/ice | 17,815 | 44 |
```xml
import { Liquid, Drop } from '../../../src'
describe('drop/drop', function () {
let liquid: Liquid
beforeEach(() => (liquid = new Liquid()))
class CustomDrop extends Drop {
private name = 'NAME'
public getName () {
return 'GET NAME'
}
}
class CustomDropWithMethodMissing extends CustomDrop {
public liquidMethodMissing (key: string) {
return key.toUpperCase()
}
}
class PromiseDrop extends Drop {
private name = Promise.resolve('NAME')
public async getName () {
return 'GET NAME'
}
public async liquidMethodMissing (key: string) {
return key.toUpperCase()
}
}
it('should call corresponding method when output', async function () {
const html = await liquid.parseAndRender(`{{obj.getName}}`, { obj: new CustomDrop() })
expect(html).toBe('GET NAME')
})
it('should call corresponding method when expression evaluates', async function () {
const html = await liquid.parseAndRender(`{% if obj.getName == "GET NAME" %}true{% endif %}`, { obj: new CustomDrop() })
expect(html).toBe('true')
})
it('should read corresponding property', async function () {
const html = await liquid.parseAndRender(`{{obj.name}}`, { obj: new CustomDrop() })
expect(html).toBe('NAME')
})
it('should output empty string if not exist', async function () {
const html = await liquid.parseAndRender(`{{obj.foo}}`, { obj: new CustomDrop() })
expect(html).toBe('')
})
it('should respect liquidMethodMissing', async function () {
const html = await liquid.parseAndRender(`{{obj.foo}}`, { obj: new CustomDropWithMethodMissing() })
expect(html).toBe('FOO')
})
it('should call corresponding promise method', async function () {
const html = await liquid.parseAndRender(`{{obj.getName}}`, { obj: new PromiseDrop() })
expect(html).toBe('GET NAME')
})
it('should read corresponding promise property', async function () {
const html = await liquid.parseAndRender(`{{obj.name}}`, { obj: new PromiseDrop() })
expect(html).toBe('NAME')
})
it('should resolve before calling filters', async function () {
const html = await liquid.parseAndRender(`{{obj.name | downcase}}`, { obj: new PromiseDrop() })
expect(html).toBe('name')
})
it('should support promise returned by liquidMethodMissing', async function () {
const html = await liquid.parseAndRender(`{{obj.foo}}`, { obj: new PromiseDrop() })
expect(html).toBe('FOO')
})
it('should respect valueOf', async () => {
class CustomDrop extends Drop {
prop = 'not enumerable'
valueOf () {
return ['foo', 'bar']
}
}
const tpl = '{{drop}}: {% for field in drop %}{{ field }};{% endfor %}'
const html = await liquid.parseAndRender(tpl, { drop: new CustomDrop() })
expect(html).toBe('foobar: foo;bar;')
})
it('should support valueOf in == expression', async () => {
class AddressDrop extends Drop {
valueOf () {
return 'test'
}
}
const address = new AddressDrop()
const customer = { default_address: new AddressDrop() }
const tpl = `{% if address == customer.default_address %}{{address}}{% endif %}`
const html = await liquid.parseAndRender(tpl, { address, customer })
expect(html).toBe('test')
})
it('should correctly evaluate custom Drop objects with equals function without full Comparable implementation', async () => {
class TestDrop extends Drop {
value: string;
constructor () {
super()
this.value = 'test'
}
equals (rhs: string): boolean {
return this.valueOf() === rhs
}
valueOf (): string {
return this.value
}
}
const address = new TestDrop()
const customer = { default_address: new TestDrop() }
const tpl = `{{ address >= customer.default_address }}`
const html = await liquid.parseAndRender(tpl, { address, customer })
expect(html).toBe('true')
})
it('should support returning supported value types from liquidMethodMissing', async function () {
class DynamicTypeDrop extends Drop {
liquidMethodMissing (key: string) {
switch (key) {
case 'number': return 42
case 'string': return 'foo'
case 'boolean': return true
case 'array': return [1, 2, 3]
case 'object': return { foo: 'bar' }
case 'drop': return new CustomDrop()
}
}
}
const html = await liquid.parseAndRender(`{{obj.number}} {{obj.string}} {{obj.boolean}} {{obj.array | first}} {{obj.object.foo}} {{obj.drop.getName}}`, { obj: new DynamicTypeDrop() })
expect(html).toBe('42 foo true 1 bar GET NAME')
})
})
``` | /content/code_sandbox/test/integration/drop/drop.spec.ts | xml | 2016-06-13T07:39:30 | 2024-08-16T16:56:50 | liquidjs | harttle/liquidjs | 1,485 | 1,116 |
```xml
/*
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import { QSpinBox } from "@nodegui/nodegui";
import { ApplyWidgetOptions, WidgetOptions } from "./Widget.js";
export interface SpinBoxOptions extends WidgetOptions {
minimum?: number;
maximum?: number;
prefix?: string;
suffix?: string;
value?: number;
onValueChanged?: (value: number) => void;
}
export function SpinBox(options: SpinBoxOptions): QSpinBox {
const { prefix, maximum, minimum, suffix, value, onValueChanged } = options;
const spinBox = new QSpinBox();
ApplyWidgetOptions(spinBox, options);
if (minimum !== undefined) {
spinBox.setMinimum(minimum);
}
if (maximum !== undefined) {
spinBox.setMaximum(maximum);
}
if (prefix !== undefined) {
spinBox.setPrefix(prefix);
}
if (suffix !== undefined) {
spinBox.setSuffix(suffix);
}
if (value !== undefined) {
spinBox.setValue(value);
}
if (onValueChanged !== undefined) {
spinBox.addEventListener("valueChanged", onValueChanged);
}
return spinBox;
}
``` | /content/code_sandbox/packages/qt-construct/src/SpinBox.ts | xml | 2016-03-04T12:39:59 | 2024-08-16T18:44:37 | extraterm | sedwards2009/extraterm | 2,501 | 259 |
```xml
import React, { Component, Fragment } from 'react';
import { join } from 'lodash';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import { Autocomplete } from 'react-polymorph/lib/components/Autocomplete';
import { Input } from 'react-polymorph/lib/components/Input';
import { defineMessages, FormattedHTMLMessage, intlShape } from 'react-intl';
import vjf from 'mobx-react-form/lib/validators/VJF';
import SVGInline from 'react-svg-inline';
import { PopOver } from 'react-polymorph/lib/components/PopOver';
import { PasswordInput } from '../widgets/forms/PasswordInput';
import RadioSet from '../widgets/RadioSet';
import ReactToolboxMobxForm, {
handleFormErrors,
} from '../../utils/ReactToolboxMobxForm';
import DialogCloseButton from '../widgets/DialogCloseButton';
import Dialog from '../widgets/Dialog';
import {
isValidRepeatPassword,
isValidSpendingPassword,
isValidWalletName,
validateMnemonics,
} from '../../utils/validations';
import globalMessages from '../../i18n/global-messages';
import LocalizableError from '../../i18n/LocalizableError';
import { FORM_VALIDATION_DEBOUNCE_WAIT } from '../../config/timingConfig';
import styles from './WalletRestoreDialog.scss';
import { submitOnEnter } from '../../utils/form';
import {
RECOVERY_PHRASE_WORD_COUNT_OPTIONS,
WALLET_RESTORE_TYPES,
} from '../../config/walletsConfig';
import {
LEGACY_WALLET_RECOVERY_PHRASE_WORD_COUNT,
WALLET_RECOVERY_PHRASE_WORD_COUNT,
YOROI_WALLET_RECOVERY_PHRASE_WORD_COUNT,
} from '../../config/cryptoConfig';
import infoIconInline from '../../assets/images/info-icon.inline.svg';
import LoadingSpinner from '../widgets/LoadingSpinner';
import { MnemonicInput } from './mnemonic-input';
const messages = defineMessages({
title: {
id: 'wallet.restore.dialog.title.label',
defaultMessage: '!!!Restore a wallet',
description: 'Label "Restore wallet" on the wallet restore dialog.',
},
walletNameInputLabel: {
id: 'wallet.restore.dialog.wallet.name.input.label',
defaultMessage: '!!!Wallet name',
description:
'Label for the wallet name input on the wallet restore dialog.',
},
walletNameInputHint: {
id: 'wallet.restore.dialog.wallet.name.input.hint',
defaultMessage: '!!!Name the wallet you are restoring',
description:
'Hint "Name the wallet you are restoring" for the wallet name input on the wallet restore dialog.',
},
recoveryPhraseTypeLabel: {
id: 'wallet.restore.dialog.recovery.phrase.type.options.label',
defaultMessage: '!!!Number of words in the recovery phrase',
description:
'Label for the recovery phrase type options on the wallet restore dialog.',
},
recoveryPhraseTypeOptionWord: {
id: 'wallet.restore.dialog.recovery.phrase.type.word',
defaultMessage: '!!! words',
description:
'Word for the recovery phrase type on the wallet restore dialog.',
},
recoveryPhraseType15WordOption: {
id: 'wallet.restore.dialog.recovery.phrase.type.15word.option',
defaultMessage: '!!!Rewards wallet',
description:
'Label for the recovery phrase type 15-word option on the wallet restore dialog.',
},
recoveryPhraseType12WordOption: {
id: 'wallet.restore.dialog.recovery.phrase.type.12word.option',
defaultMessage: '!!!Balance wallet',
description:
'Label for the recovery phrase type 12-word option on the wallet restore dialog.',
},
recoveryPhraseInputLabel: {
id: 'wallet.restore.dialog.recovery.phrase.input.label',
defaultMessage: '!!!Recovery phrase',
description:
'Label for the recovery phrase input on the wallet restore dialog.',
},
newLabel: {
id: 'wallet.restore.dialog.recovery.phrase.newLabel',
defaultMessage: '!!!New',
description: 'Label "new" on the wallet restore dialog.',
},
importButtonLabel: {
id: 'wallet.restore.dialog.restore.wallet.button.label',
defaultMessage: '!!!Restore wallet',
description:
'Label for the "Restore wallet" button on the wallet restore dialog.',
},
invalidRecoveryPhrase: {
id: 'wallet.restore.dialog.form.errors.invalidRecoveryPhrase',
defaultMessage: '!!!Invalid recovery phrase',
description:
'Error message shown when invalid recovery phrase was entered.',
},
passwordSectionLabel: {
id: 'wallet.restore.dialog.passwordSectionLabel',
defaultMessage: '!!!Spending password',
description: 'Password creation label.',
},
passwordSectionDescription: {
id: 'wallet.restore.dialog.passwordSectionDescription',
defaultMessage:
'!!!Keep your wallet secure by setting the spending password',
description: 'Password creation description.',
},
spendingPasswordLabel: {
id: 'wallet.restore.dialog.spendingPasswordLabel',
defaultMessage: '!!!Enter password',
description:
'Label for the "Wallet password" input in the wallet restore dialog.',
},
repeatPasswordLabel: {
id: 'wallet.restore.dialog.repeatPasswordLabel',
defaultMessage: '!!!Repeat password',
description:
'Label for the "Repeat password" input in the wallet restore dialog.',
},
passwordFieldPlaceholder: {
id: 'wallet.restore.dialog.passwordFieldPlaceholder',
defaultMessage: '!!!Password',
description:
'Placeholder for the "Password" inputs in the wallet restore dialog.',
},
recoveryPhraseTabTitle: {
id: 'wallet.restore.dialog.tab.title.recoveryPhrase',
defaultMessage: '!!!Daedalus wallet',
description: 'Tab title "Daedalus wallet" in the wallet restore dialog.',
},
certificateTabTitle: {
id: 'wallet.restore.dialog.tab.title.certificate',
defaultMessage: '!!!Daedalus paper wallet',
description:
'Tab title "Daedalus paper wallet" in the wallet restore dialog.',
},
yoroiTabTitle: {
id: 'wallet.restore.dialog.tab.title.yoroi',
defaultMessage: '!!!Yoroi wallet',
description: 'Tab title "Yoroi wallet" in the wallet restore dialog.',
},
shieldedRecoveryPhraseInputLabel: {
id: 'wallet.restore.dialog.shielded.recovery.phrase.input.label',
defaultMessage: '!!!27-word paper wallet recovery phrase',
description:
'Label for the shielded recovery phrase input on the wallet restore dialog.',
},
restorePaperWalletButtonLabel: {
id: 'wallet.restore.dialog.paper.wallet.button.label',
defaultMessage: '!!!Restore paper wallet',
description:
'Label for the "Restore paper wallet" button on the wallet restore dialog.',
},
passwordTooltip: {
id: 'wallet.dialog.passwordTooltip',
defaultMessage:
'We recommend using a password manager app to manage and store your spending password. Generate a unique password using a password manager and paste it here. Passwords should never be reused.',
description: 'Tooltip for the password input in the wallet dialog.',
},
});
messages.fieldIsRequired = globalMessages.fieldIsRequired;
type Props = {
onSubmit: (...args: Array<any>) => any;
onCancel: (...args: Array<any>) => any;
isSubmitting: boolean;
mnemonicValidator: (...args: Array<any>) => any;
error?: LocalizableError | null | undefined;
suggestedMnemonics: Array<string>;
onChoiceChange: ((...args: Array<any>) => any) | null | undefined;
};
type State = {
walletType: string;
};
interface FormFields {
repeatPassword: string;
spendingPassword: string;
recoveryPhrase: string;
walletName: string;
}
@observer
class WalletRestoreDialog extends Component<Props, State> {
static contextTypes = {
intl: intlShape.isRequired,
};
static defaultProps = {
error: null,
};
state = {
walletType: WALLET_RESTORE_TYPES.LEGACY, // regular | certificate | legacy | yoroi
};
recoveryPhraseAutocomplete: Autocomplete;
componentDidUpdate() {
if (this.props.error) {
handleFormErrors('.WalletRestoreDialog_error');
}
}
form = new ReactToolboxMobxForm<FormFields>(
{
fields: {
walletName: {
label: this.context.intl.formatMessage(messages.walletNameInputLabel),
placeholder: this.context.intl.formatMessage(
messages.walletNameInputHint
),
value: '',
validators: [
({ field }) => [
isValidWalletName(field.value),
this.context.intl.formatMessage(globalMessages.invalidWalletName),
],
],
},
recoveryPhrase: {
value: [],
validators: ({ field }) => {
const expectedWordCount =
RECOVERY_PHRASE_WORD_COUNT_OPTIONS[this.state.walletType];
return validateMnemonics({
requiredWords: expectedWordCount,
providedWords: field.value,
validator: (providedWords) => [
// TODO: we should also validate paper wallets mnemonics here!
!this.isCertificate()
? this.props.mnemonicValidator(
providedWords,
expectedWordCount
)
: true,
this.context.intl.formatMessage(messages.invalidRecoveryPhrase),
],
});
},
},
spendingPassword: {
type: 'password',
label: this.context.intl.formatMessage(
messages.spendingPasswordLabel
),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldPlaceholder
),
value: '',
validators: [
({ field, form }) => {
const repeatPasswordField = form.$('repeatPassword');
if (repeatPasswordField.value.length > 0) {
repeatPasswordField.validate({
showErrors: true,
});
}
return [
isValidSpendingPassword(field.value),
this.context.intl.formatMessage(
globalMessages.invalidSpendingPassword
),
];
},
],
},
repeatPassword: {
type: 'password',
label: this.context.intl.formatMessage(messages.repeatPasswordLabel),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldPlaceholder
),
value: '',
validators: [
({ field, form }) => {
const spendingPassword = form.$('spendingPassword').value;
if (spendingPassword.length === 0) return [true];
return [
isValidRepeatPassword(spendingPassword, field.value),
this.context.intl.formatMessage(
globalMessages.invalidRepeatPassword
),
];
},
],
},
},
},
{
plugins: {
vjf: vjf(),
},
options: {
validateOnChange: true,
showErrorsOnChange: false,
validationDebounceWait: FORM_VALIDATION_DEBOUNCE_WAIT,
},
}
);
submit = () => {
this.form.submit({
onSuccess: (form) => {
const { onSubmit } = this.props;
const { recoveryPhrase, walletName, spendingPassword } = form.values();
const walletData: Record<string, any> = {
recoveryPhrase: join(recoveryPhrase, ' '),
walletName,
spendingPassword,
};
walletData.type = this.state.walletType;
onSubmit(walletData);
},
onError: () =>
handleFormErrors('.SimpleFormField_error', {
focusElement: true,
}),
});
};
handleSubmitOnEnter = submitOnEnter.bind(this, this.submit);
resetForm = () => {
const { form } = this;
// Cancel all debounced field validations
form.each((field) => {
field.debouncedValidation.cancel();
});
form.reset();
form.showErrors(false);
};
resetMnemonics = () => {
const recoveryPhraseField = this.form.$('recoveryPhrase');
recoveryPhraseField.debouncedValidation.cancel();
recoveryPhraseField.reset();
recoveryPhraseField.showErrors(false);
};
render() {
const { intl } = this.context;
const { form } = this;
const { walletType } = this.state;
const { suggestedMnemonics, isSubmitting, error, onCancel } = this.props;
const dialogClasses = classnames([styles.component, 'WalletRestoreDialog']);
const walletNameFieldClasses = classnames([
'walletName',
styles.walletName,
]);
const walletNameField = form.$('walletName');
const recoveryPhraseField = form.$('recoveryPhrase');
const spendingPasswordField = form.$('spendingPassword');
const repeatedPasswordField = form.$('repeatPassword');
const label = this.isCertificate()
? this.context.intl.formatMessage(messages.restorePaperWalletButtonLabel)
: this.context.intl.formatMessage(messages.importButtonLabel);
const buttonLabel = !isSubmitting ? label : <LoadingSpinner />;
const actions = [
{
label: buttonLabel,
primary: true,
disabled: isSubmitting,
onClick: this.submit,
},
];
const regularTabClasses = classnames([
'regularTab',
this.isRegular() || this.isLegacy() ? styles.activeButton : '',
]);
const certificateTabClasses = classnames([
'certificateTab',
this.isCertificate() ? styles.activeButton : '',
]);
const yoroiTabClasses = classnames([
'yoroiTab',
this.isYoroi() ? styles.activeButton : '',
]);
const { reset, ...mnemonicInputProps } = recoveryPhraseField.bind();
return (
<Dialog
className={dialogClasses}
title={intl.formatMessage(messages.title)}
actions={actions}
closeOnOverlayClick
onClose={onCancel}
closeButton={<DialogCloseButton />}
>
<div className={styles.restoreTypeChoice}>
<button
className={regularTabClasses}
onClick={() =>
this.onSelectWalletType(WALLET_RESTORE_TYPES.LEGACY, true)
}
>
{intl.formatMessage(messages.recoveryPhraseTabTitle)}
</button>
<button
className={certificateTabClasses}
onClick={() =>
this.onSelectWalletType(WALLET_RESTORE_TYPES.CERTIFICATE, true)
}
>
{intl.formatMessage(messages.certificateTabTitle)}
</button>
<button
className={yoroiTabClasses}
onClick={() =>
this.onSelectWalletType(WALLET_RESTORE_TYPES.YOROI_LEGACY, true)
}
>
{intl.formatMessage(messages.yoroiTabTitle)}
</button>
</div>
<Input
className={walletNameFieldClasses}
onKeyPress={this.handleSubmitOnEnter}
{...walletNameField.bind()}
error={walletNameField.error}
/>
{(this.isRegular() || this.isLegacy()) && (
<RadioSet
label={intl.formatMessage(messages.recoveryPhraseTypeLabel)}
items={[
{
key: WALLET_RESTORE_TYPES.LEGACY,
label: (
<Fragment>
{LEGACY_WALLET_RECOVERY_PHRASE_WORD_COUNT}
{intl.formatMessage(
messages.recoveryPhraseTypeOptionWord
)}{' '}
<span>
(
{intl.formatMessage(
messages.recoveryPhraseType12WordOption
)}
)
</span>
</Fragment>
),
selected: this.isLegacy(),
onChange: () =>
this.onSelectWalletType(WALLET_RESTORE_TYPES.LEGACY),
},
{
key: WALLET_RESTORE_TYPES.REGULAR,
label: (
<Fragment>
{WALLET_RECOVERY_PHRASE_WORD_COUNT}
{intl.formatMessage(
messages.recoveryPhraseTypeOptionWord
)}{' '}
<span>
(
{intl.formatMessage(
messages.recoveryPhraseType15WordOption
)}
)
</span>
<span className={styles.newLabel}>
{intl.formatMessage(messages.newLabel)}
</span>
</Fragment>
),
selected: !this.isLegacy(),
onChange: () =>
this.onSelectWalletType(WALLET_RESTORE_TYPES.REGULAR),
},
]}
/>
)}
{this.isYoroi() && (
<RadioSet
label={intl.formatMessage(messages.recoveryPhraseTypeLabel)}
items={[
{
key: WALLET_RESTORE_TYPES.YOROI_LEGACY,
label: (
<Fragment>
{YOROI_WALLET_RECOVERY_PHRASE_WORD_COUNT}
{intl.formatMessage(
messages.recoveryPhraseTypeOptionWord
)}{' '}
<span>
(
{intl.formatMessage(
messages.recoveryPhraseType12WordOption
)}
)
</span>
</Fragment>
),
selected: this.isYoroiLegacy(),
onChange: () =>
this.onSelectWalletType(WALLET_RESTORE_TYPES.YOROI_LEGACY),
},
{
key: WALLET_RESTORE_TYPES.YOROI_REGULAR,
label: (
<Fragment>
{YOROI_WALLET_RECOVERY_PHRASE_WORD_COUNT}
{intl.formatMessage(
messages.recoveryPhraseTypeOptionWord
)}{' '}
<span>
(
{intl.formatMessage(
messages.recoveryPhraseType15WordOption
)}
)
</span>
<span className={styles.newLabel}>
{intl.formatMessage(messages.newLabel)}
</span>
</Fragment>
),
selected: this.isYoroiRegular(),
onChange: () =>
this.onSelectWalletType(WALLET_RESTORE_TYPES.YOROI_REGULAR),
},
]}
/>
)}
<MnemonicInput
{...mnemonicInputProps}
label={
this.isCertificate()
? intl.formatMessage(messages.shieldedRecoveryPhraseInputLabel)
: intl.formatMessage(messages.recoveryPhraseInputLabel)
}
availableWords={suggestedMnemonics}
wordCount={RECOVERY_PHRASE_WORD_COUNT_OPTIONS[walletType]}
error={recoveryPhraseField.error}
reset={form.resetting}
/>
<div className={styles.spendingPasswordWrapper}>
<div className={styles.passwordSectionLabel}>
{intl.formatMessage(messages.passwordSectionLabel)}
</div>
<div className={styles.passwordSectionDescription}>
{intl.formatMessage(messages.passwordSectionDescription)}
</div>
<div className={styles.spendingPasswordFields}>
<div className={styles.spendingPasswordField}>
<PasswordInput
className="spendingPassword"
onKeyPress={this.handleSubmitOnEnter}
{...spendingPasswordField.bind()}
/>
<PopOver
content={<FormattedHTMLMessage {...messages.passwordTooltip} />}
key="tooltip"
>
<SVGInline svg={infoIconInline} className={styles.infoIcon} />
</PopOver>
</div>
<div className={styles.spendingPasswordField}>
<PasswordInput
className="repeatedPassword"
onKeyPress={this.handleSubmitOnEnter}
{...repeatedPasswordField.bind()}
repeatPassword={spendingPasswordField.value}
isPasswordRepeat
/>
</div>
</div>
<p className={styles.passwordInstructions}>
<FormattedHTMLMessage {...globalMessages.passwordInstructions} />
</p>
</div>
{error && <p className={styles.error}>{intl.formatMessage(error)}</p>}
</Dialog>
);
}
isRegular() {
return this.state.walletType === WALLET_RESTORE_TYPES.REGULAR;
}
isCertificate() {
return this.state.walletType === WALLET_RESTORE_TYPES.CERTIFICATE;
}
isLegacy() {
return this.state.walletType === WALLET_RESTORE_TYPES.LEGACY;
}
isYoroiLegacy() {
return this.state.walletType === WALLET_RESTORE_TYPES.YOROI_LEGACY;
}
isYoroiRegular() {
return this.state.walletType === WALLET_RESTORE_TYPES.YOROI_REGULAR;
}
isYoroi() {
return this.isYoroiLegacy() || this.isYoroiRegular();
}
onSelectWalletType = (walletType: string, shouldResetForm?: boolean) => {
const { onChoiceChange, isSubmitting } = this.props;
if (isSubmitting) return;
this.setState({
walletType,
});
if (shouldResetForm) this.resetForm();
this.resetMnemonics();
if (onChoiceChange) onChoiceChange();
};
}
export default WalletRestoreDialog;
``` | /content/code_sandbox/source/renderer/app/components/wallet/WalletRestoreDialog.tsx | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 4,369 |
```xml
import {MetadataTypes, Type} from "@tsed/core";
import {JsonMapperMethods} from "../interfaces/JsonMapperMethods.js";
import {JsonMapperGlobalOptions} from "./JsonMapperGlobalOptions.js";
export interface JsonSerializerOptions<T = any, C = any> extends MetadataTypes<T, C>, Pick<JsonMapperGlobalOptions, "strictGroups"> {
/**
* Types used to map complex types (Symbol, Number, String, etc...)
*/
types?: Map<Type<any> | Symbol | string, JsonMapperMethods>;
/**
* useAlias mapping
*/
useAlias?: boolean;
[key: string]: any;
}
``` | /content/code_sandbox/packages/specs/json-mapper/src/domain/JsonSerializerOptions.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 137 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>10K549</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>AppleIntelE1000e</string>
<key>CFBundleIdentifier</key>
<string>com.insanelymac.driver.AppleIntelE1000e</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>AppleIntelE1000e</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>3.3.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>3.3.1</string>
<key>DTCompiler</key>
<string></string>
<key>DTPlatformBuild</key>
<string>10M2518</string>
<key>DTPlatformVersion</key>
<string>PG</string>
<key>DTSDKBuild</key>
<string>10M2518</string>
<key>DTSDKName</key>
<string>macosx10.6</string>
<key>DTXcode</key>
<string>0400</string>
<key>DTXcodeBuild</key>
<string>10M2518</string>
<key>IOKitPersonalities</key>
<dict>
<key>e1000e</key>
<dict>
<key>CFBundleIdentifier</key>
<string>com.insanelymac.driver.AppleIntelE1000e</string>
<key>E1000_CTRL_TFCE</key>
<true/>
<key>E1000_DEFAULT_RXD</key>
<integer>256</integer>
<key>E1000_DEFAULT_TXD</key>
<integer>256</integer>
<key>IOClass</key>
<string>AppleIntelE1000e</string>
<key>IOPCIMatch</key>
<string>0x153b8086 0x15598086 0x155a8086 0x15a08086 0x15a18086 0x15a28086 0x15a38086 0x10968086 0x10988086 0x10ba8086 0x10bb8086 0x10cc8086 0x10cd8086 0x10ce8086 0x10de8086 0x10df8086 0x15258086 0x15018086 0x10498086 0x104a8086 0x104b8086 0x104c8086 0x104d8086 0x10c48086 0x10c58086 0x10bd8086 0x10bf8086 0x10c08086 0x10c28086 0x10c38086 0x10cb8086 0x10e58086 0x10f58086 0x294c8086 0x105e8086 0x105f8086 0x10608086 0x10a48086 0x10a58086 0x10bc8086 0x10d58086 0x10d98086 0x10da8086 0x107d8086 0x107e8086 0x107f8086 0x10b98086 0x108b8086 0x108c8086 0x109a8086 0x10d38086 0x10ea8086 0x10eb8086 0x10ef8086 0x10f08086 0x15028086 0x15038086 0x150c8086 0x156f8086 0x15708086 0x15b78086 0x15b88086 0x15b98086</string>
<key>IOProviderClass</key>
<string>IOPCIDevice</string>
<key>NETIF_F_TSO</key>
<false/>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.iokit.IONetworkingFamily</key>
<string>1.5.0</string>
<key>com.apple.iokit.IOPCIFamily</key>
<string>1.7</string>
<key>com.apple.kpi.bsd</key>
<string>8.10.0</string>
<key>com.apple.kpi.iokit</key>
<string>8.10.0</string>
<key>com.apple.kpi.libkern</key>
<string>8.10.0</string>
<key>com.apple.kpi.mach</key>
<string>8.10.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Network-Root</string>
</dict>
</plist>
``` | /content/code_sandbox/Clover-Configs/XiaoMi/13.3-without-fingerprint/CLOVER/kexts/Other/AppleIntelE1000e.kext/Contents/Info.plist | xml | 2016-11-05T04:22:54 | 2024-08-12T19:25:53 | Hackintosh-Installer-University | huangyz0918/Hackintosh-Installer-University | 3,937 | 1,241 |
```xml
/**
* @license
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {MDCComponent} from '../../mdc-base/component';
import {MDCFoundation} from '../../mdc-base/foundation';
import {emitEvent} from '../../../testing/dom/events';
class FakeComponent extends MDCComponent<MDCFoundation> {
initializeArgs!: unknown[];
initializeComesBeforeFoundation!: boolean;
synced!: boolean;
override getDefaultFoundation() {
const defaultFoundation = {
isDefaultFoundation: true,
init: jasmine.createSpy('init'),
rootElementAtTimeOfCall: this.root,
} as any;
return defaultFoundation;
}
override initialize(...args: unknown[]) {
this.initializeArgs = args;
this.initializeComesBeforeFoundation = !this.foundation;
}
override initialSyncWithDOM() {
this.synced = true;
}
}
describe('MDCComponent', () => {
it('provides a static attachTo() method that returns a basic instance with the specified root',
() => {
const root = document.createElement('div');
const b = MDCComponent.attachTo(root);
expect(b instanceof MDCComponent).toBeTruthy();
});
it('takes a root node constructor param and assigns it to the "root" property',
() => {
const root = document.createElement('div');
const f = new FakeComponent(root);
expect(f['root']).toEqual(root);
});
it('takes an optional foundation constructor param and assigns it to the "foundation" property',
() => {
const root = document.createElement('div');
const foundation = {init: () => {}} as any;
const f = new FakeComponent(root, foundation);
expect(f['foundation']).toEqual(foundation);
});
it('assigns the result of "getDefaultFoundation()" to "foundation" by default',
() => {
const root = document.createElement('div');
const f = new FakeComponent(root);
expect((f['foundation'] as any).isDefaultFoundation).toBeTruthy();
});
it('calls the foundation\'s init() method within the constructor', () => {
const root = document.createElement('div');
const foundation = {init: jasmine.createSpy('init')};
// Testing side effects of constructor
// eslint-disable-next-line no-new
new FakeComponent(root, foundation as any);
expect(foundation.init).toHaveBeenCalled();
});
it('throws an error if getDefaultFoundation() is not overridden', () => {
const root = document.createElement('div');
expect(() => new MDCComponent(root)).toThrow();
});
it('calls initialSyncWithDOM() when initialized', () => {
const root = document.createElement('div');
const f = new FakeComponent(root);
expect(f.synced).toBeTruthy();
});
it('provides a default initialSyncWithDOM() no-op if none provided by subclass',
() => {
expect(MDCComponent.prototype.initialSyncWithDOM.bind({})).not.toThrow();
});
it('provides a default destroy() method which calls the foundation\'s destroy() method',
() => {
const root = document.createElement('div');
const foundation = {
init: jasmine.createSpy('init'),
destroy: jasmine.createSpy('destroy')
};
const f = new FakeComponent(root, foundation as any);
f.destroy();
expect(foundation.destroy).toHaveBeenCalled();
});
it('#initialize is called within constructor and passed any additional positional component args',
() => {
const f = new FakeComponent(
document.createElement('div'), /* foundation */ undefined, 'foo',
42);
expect(f.initializeArgs).toEqual(['foo', 42]);
});
it('#initialize is called before getDefaultFoundation()', () => {
const f = new FakeComponent(document.createElement('div'));
expect(f.initializeComesBeforeFoundation).toBeTruthy();
});
it('#listen adds an event listener to the root element', () => {
const root = document.createElement('div');
const f = new FakeComponent(root);
const handler = jasmine.createSpy('eventHandler');
f.listen('FakeComponent:customEvent', handler);
emitEvent(root, 'FakeComponent:customEvent');
expect(handler).toHaveBeenCalledWith(jasmine.anything());
});
it('#unlisten removes an event listener from the root element', () => {
const root = document.createElement('div');
const f = new FakeComponent(root);
const handler = jasmine.createSpy('eventHandler');
root.addEventListener('FakeComponent:customEvent', handler);
f.unlisten('FakeComponent:customEvent', handler);
emitEvent(root, 'FakeComponent:customEvent');
expect(handler).not.toHaveBeenCalledWith(jasmine.anything());
});
it('#emit dispatches a custom event with the supplied data', () => {
const root = document.createElement('div');
const f = new FakeComponent(root);
const handler = jasmine.createSpy('eventHandler');
let event: any = null;
handler.withArgs(jasmine.any(Object)).and.callFake((e: any) => {
event = e;
});
const data = {eventData: true};
const type = 'customeventtype';
root.addEventListener(type, handler);
f.emit(type, data);
expect(event !== null).toBeTruthy();
// assertion above ensures non-null event, but compiler doesn't know this
// tslint:disable:no-unnecessary-type-assertion
expect(event!.type).toEqual(type);
expect(event!.detail).toEqual(data);
// tslint:enable:no-unnecessary-type-assertion
});
it('#emit dispatches a custom event with the supplied data where custom events aren\'t available',
() => {
const root = document.createElement('div');
const f = new FakeComponent(root);
const handler = jasmine.createSpy('eventHandler');
let event: any = null;
handler.withArgs(jasmine.any(Object)).and.callFake((e: any) => {
event = e;
});
const data = {eventData: true};
const type = 'customeventtype';
root.addEventListener(type, handler);
const {CustomEvent} = (window as any);
(window as any).CustomEvent = undefined;
try {
f.emit(type, data);
} finally {
(window as any).CustomEvent = CustomEvent;
}
expect(event !== null).toBeTruthy();
// assertion above ensures non-null event, but compiler doesn't know this
// tslint:disable:no-unnecessary-type-assertion
expect(event!.type).toEqual(type);
expect(event!.detail).toEqual(data);
// tslint:enable:no-unnecessary-type-assertion
});
it('(regression) ensures that this.root is available for use within getDefaultFoundation()',
() => {
const root = document.createElement('div');
const f = new FakeComponent(root);
expect((f['foundation'] as any).rootElementAtTimeOfCall).toEqual(root);
});
});
``` | /content/code_sandbox/packages/mdc-base/test/component.test.ts | xml | 2016-12-05T16:04:09 | 2024-08-16T15:42:22 | material-components-web | material-components/material-components-web | 17,119 | 1,697 |
```xml
import Button from "@erxes/ui/src/components/Button";
import { Footer } from "../styles";
import FormControl from "@erxes/ui/src/components/form/Control";
import FormGroup from "@erxes/ui/src/components/form/Group";
import { IConfigColumn } from "../types";
import React from "react";
import { ScrollWrapper } from "@erxes/ui/src/styles/main";
import SortableList from "@erxes/ui/src/components/SortableList";
import { __ } from "@erxes/ui/src/utils";
import { colors } from "@erxes/ui/src/styles";
import styled from "styled-components";
const Header = styled.div`
display: flex;
justify-content: space-between;
background: ${colors.bgActive};
border: 1px solid ${colors.borderPrimary};
border-radius: 2px;
margin-bottom: 10px;
> span {
text-transform: uppercase;
padding: 5px 20px 5px 30px;
font-weight: bold;
}
`;
const Child = styled.div`
width: 100%;
label {
float: right;
}
`;
type Props = {
columns: IConfigColumn[];
save: (columnsConfig: IConfigColumn[], importType?: string) => void;
closeModal: () => void;
contentType: string;
type: string;
};
type State = {
columns: IConfigColumn[];
importType: string;
searchValue: string;
};
class ManageColumns extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
if (props.columns.findIndex((c) => c._id === "#") === -1) {
props.columns.unshift({
_id: "#",
name: "#",
label: "Numerical index",
order: 0,
checked: false,
});
}
this.state = {
columns: props.columns,
importType: "csv",
searchValue: "",
};
}
onSubmit = (e) => {
e.preventDefault();
const columnsConfig: IConfigColumn[] = [];
const { importType } = this.state;
this.state.columns.forEach((col, index) => {
const element = document.getElementById(col._id) as HTMLInputElement;
columnsConfig.push({
_id: col._id,
order: index,
checked: element.checked,
name: col.name,
label: col.label,
group: col.group,
});
});
this.props.save(columnsConfig, importType);
this.props.closeModal();
};
onChangeColumns = (columns) => {
this.setState({ columns });
};
search = (e) => {
const searchValue = e.target.value;
this.setState({ searchValue });
};
render() {
const { type, contentType } = this.props;
const child = (col) => {
return (
<Child>
<span>{col.label}</span>
<FormControl
id={String(col._id)}
defaultChecked={col.checked}
componentclass="checkbox"
/>
</Child>
);
};
const onclickCsv = (e) => {
this.setState({ importType: "csv" }, () => {
this.onSubmit(e);
});
};
return (
<form onSubmit={this.onSubmit}>
<FormGroup>
<FormControl
type="text"
placeholder={__("Type to search")}
onChange={this.search}
value={this.state.searchValue}
/>
</FormGroup>
<Header>
<span>{__("Column name")}</span>
<span>{__("Visible")}</span>
</Header>
<ScrollWrapper calcHeight="320">
<SortableList
fields={this.state.columns}
child={child}
onChangeFields={this.onChangeColumns}
isModal={true}
searchValue={this.state.searchValue}
/>
</ScrollWrapper>
<Footer>
<Button
type="button"
btnStyle="simple"
onClick={this.props.closeModal}
>
Cancel
</Button>
{type && type === "import" ? (
<Button type="submit" onClick={onclickCsv}>
Download csv
</Button>
) : null}
{type && type === "export" ? (
<Button type="submit" onClick={this.onSubmit}>
Export {contentType}
</Button>
) : null}
{!["export", "import"].includes(type) ? (
<Button type="submit" onClick={this.onSubmit}>
Save
</Button>
) : null}
</Footer>
</form>
);
}
}
export default ManageColumns;
``` | /content/code_sandbox/packages/ui-forms/src/settings/properties/components/ManageColumns.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 990 |
```xml
import { BatteryState } from './Battery.types';
declare const _default: {
readonly isSupported: boolean;
getBatteryLevelAsync(): Promise<number>;
getBatteryStateAsync(): Promise<BatteryState>;
startObserving(): Promise<void>;
stopObserving(): Promise<void>;
};
export default _default;
//# sourceMappingURL=ExpoBattery.web.d.ts.map
``` | /content/code_sandbox/packages/expo-battery/build/ExpoBattery.web.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 76 |
```xml
import { ITxHistoryApiResponse } from '@services/ApiService/History';
import { ITxHistoryState, ITxMetaTypes } from '@store/txHistory.slice';
import {
ITxData,
ITxGasLimit,
ITxGasPrice,
ITxHash,
ITxNonce,
ITxStatus,
ITxType,
ITxValue,
TAddress
} from '@types';
export const fTxHistoryAPI: ITxHistoryApiResponse = {
to: '0x7a250d5630b4cf539739df2c5dacb4c659f2488d' as TAddress,
from: '0xfE5443FaC29fA621cFc33D41D1927fd0f5E0bB7c' as TAddress,
value: '0x1f399b1438a10000' as ITxValue,
blockNumber: '0xa2db5e',
timestamp: 1597606012,
gasLimit: '0x0286ca' as ITxGasLimit,
gasUsed: '0x01e815',
gasPrice: '0x1836e21000' as ITxGasPrice,
status: ITxStatus.SUCCESS,
nonce: '0xf4' as ITxNonce,
erc20Transfers: [
{
from: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' as TAddress,
to: '0x8878Df9E1A7c87dcBf6d3999D997f262C05D8C70' as TAddress,
contractAddress: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' as TAddress,
amount: '0x1f399b1438a10000'
},
{
from: '0x8878Df9E1A7c87dcBf6d3999D997f262C05D8C70' as TAddress,
to: '0x5197B5b062288Bbf29008C92B08010a92Dd677CD' as TAddress,
contractAddress: '0xbbbbca6a901c926f240b89eacb641d8aec7aeafd' as TAddress,
amount: '0x0110a6c6c43733b70d4b'
}
],
recipientAddress: '0x7a250d5630b4cf539739df2c5dacb4c659f2488d' as TAddress,
hash: your_sha256_hash40' as ITxHash,
txType: 'UNISWAP_V2_EXCHANGE' as ITxType,
data: your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hash8aec7aeafd' as ITxData
};
export const fTxTypeMetas: ITxMetaTypes = {
'1INCH_EXCHANGE': {
protocol: '1INCH',
type: 'EXCHANGE'
},
ERC_20_APPROVE: {
protocol: 'ERC_20',
type: 'APPROVE'
},
ERC_20_MINT: {
protocol: 'ERC_20',
type: 'MINT'
},
ERC_20_TRANSFER: {
protocol: 'ERC_20',
type: 'TRANSFER'
},
UNISWAP_V2_EXCHANGE: {
protocol: 'UNISWAP_V2',
type: 'EXCHANGE'
}
};
export const fTxHistory: ITxHistoryState = {
history: [],
txTypeMeta: fTxTypeMetas,
error: ''
};
``` | /content/code_sandbox/jest_config/__fixtures__/txHistory.ts | xml | 2016-12-04T01:35:27 | 2024-08-14T21:41:58 | MyCrypto | MyCryptoHQ/MyCrypto | 1,347 | 848 |
```xml
import React, { Component } from 'react';
// @ts-ignore ts-migrate(2724) FIXME: '"react"' has no exported member named 'Element'. ... Remove this comment to see the full error message
import type { Element } from 'react';
import { observer } from 'mobx-react';
// @ts-ignore ts-migrate(2307) FIXME: Cannot find module './WalletRecoveryInstructions.s... Remove this comment to see the full error message
import styles from './WalletRecoveryInstructions.scss';
type Props = {
instructionsText: string | Element<any>;
};
@observer
class WalletRecoveryInstructions extends Component<Props> {
render() {
const { instructionsText } = this.props;
return <div className={styles.component}>{instructionsText}</div>;
}
}
export default WalletRecoveryInstructions;
``` | /content/code_sandbox/source/renderer/app/components/wallet/backup-recovery/WalletRecoveryInstructions.tsx | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 172 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
// EXPORTS //
/**
* Returns a Number object.
*
* ## Notes
*
* - This constructor should be used sparingly. Always prefer number primitives.
*/
export = Number;
``` | /content/code_sandbox/lib/node_modules/@stdlib/number/ctor/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 97 |
```xml
import * as React from 'react';
import { ReactNode, useCallback } from 'react';
import { styled } from '@mui/material/styles';
import clsx from 'clsx';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import { lighten } from '@mui/material/styles';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import { useTranslate, sanitizeListRestProps, useListContext } from 'ra-core';
import TopToolbar from '../layout/TopToolbar';
export const BulkActionsToolbar = (props: BulkActionsToolbarProps) => {
const {
label = 'ra.action.bulk_actions',
children,
className,
...rest
} = props;
const { selectedIds = [], onUnselectItems } = useListContext();
const translate = useTranslate();
const handleUnselectAllClick = useCallback(() => {
onUnselectItems();
}, [onUnselectItems]);
return (
<Root className={className}>
<Toolbar
data-test="bulk-actions-toolbar"
className={clsx(BulkActionsToolbarClasses.toolbar, {
[BulkActionsToolbarClasses.collapsed]:
selectedIds.length === 0,
})}
{...sanitizeListRestProps(rest)}
>
<div className={BulkActionsToolbarClasses.title}>
<IconButton
className={BulkActionsToolbarClasses.icon}
aria-label={translate('ra.action.unselect')}
title={translate('ra.action.unselect')}
onClick={handleUnselectAllClick}
size="small"
>
<CloseIcon fontSize="small" />
</IconButton>
<Typography color="inherit" variant="subtitle1">
{translate(label, {
_: label,
smart_count: selectedIds.length,
})}
</Typography>
</div>
<TopToolbar className={BulkActionsToolbarClasses.topToolbar}>
{children}
</TopToolbar>
</Toolbar>
</Root>
);
};
export interface BulkActionsToolbarProps {
children?: ReactNode;
label?: string;
className?: string;
}
const PREFIX = 'RaBulkActionsToolbar';
export const BulkActionsToolbarClasses = {
toolbar: `${PREFIX}-toolbar`,
topToolbar: `${PREFIX}-topToolbar`,
buttons: `${PREFIX}-buttons`,
collapsed: `${PREFIX}-collapsed`,
title: `${PREFIX}-title`,
icon: `${PREFIX}-icon`,
};
const Root = styled('div', {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme }) => ({
position: 'relative',
[`& .${BulkActionsToolbarClasses.toolbar}`]: {
position: 'absolute',
left: 0,
right: 0,
zIndex: 3,
color:
theme.palette.mode === 'light'
? theme.palette.primary.main
: theme.palette.text.primary,
justifyContent: 'space-between',
backgroundColor:
theme.palette.mode === 'light'
? lighten(theme.palette.primary.light, 0.8)
: theme.palette.primary.dark,
minHeight: theme.spacing(6),
height: theme.spacing(6),
transform: `translateY(-${theme.spacing(6)})`,
transition: `${theme.transitions.create(
'height'
)}, ${theme.transitions.create(
'min-height'
)}, ${theme.transitions.create('transform')}`,
borderTopLeftRadius: theme.shape.borderRadius,
borderTopRightRadius: theme.shape.borderRadius,
},
[`& .${BulkActionsToolbarClasses.topToolbar}`]: {
paddingBottom: theme.spacing(1),
minHeight: 'auto',
[theme.breakpoints.down('sm')]: {
backgroundColor: 'transparent',
},
},
[`& .${BulkActionsToolbarClasses.buttons}`]: {},
[`& .${BulkActionsToolbarClasses.collapsed}`]: {
minHeight: 0,
height: 0,
transform: `translateY(0)`,
overflowY: 'hidden',
},
[`& .${BulkActionsToolbarClasses.title}`]: {
display: 'flex',
flex: '0 0 auto',
},
[`& .${BulkActionsToolbarClasses.icon}`]: {
marginLeft: '-0.5em',
marginRight: '0.5em',
},
}));
``` | /content/code_sandbox/packages/ra-ui-materialui/src/list/BulkActionsToolbar.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 905 |
```xml
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { EditProjectQuotasComponent } from './edit-project-quotas.component';
import { EditQuotaQuotaInterface } from '../../../../../shared/services';
import { SharedTestingModule } from '../../../../../shared/shared.module';
describe('EditProjectQuotasComponent', () => {
let component: EditProjectQuotasComponent;
let fixture: ComponentFixture<EditProjectQuotasComponent>;
const mockedEditQuota: EditQuotaQuotaInterface = {
editQuota: 'Edit Default Project Quotas',
setQuota: 'Set the default project quotas when creating new projects',
storageQuota: 'Default storage consumption',
quotaHardLimitValue: { storageLimit: -1, storageUnit: 'Byte' },
isSystemDefaultQuota: true,
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [SharedTestingModule],
declarations: [EditProjectQuotasComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(EditProjectQuotasComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
``` | /content/code_sandbox/src/portal/src/app/base/left-side-nav/project-quotas/project-quotas/edit-project-quotas/edit-project-quotas.component.spec.ts | xml | 2016-01-28T21:10:28 | 2024-08-16T15:28:34 | harbor | goharbor/harbor | 23,335 | 250 |
```xml
import React from 'react';
import { render, screen } from '@testing-library/react';
import Checkbox from '../Checkbox';
import { toRGB, itChrome } from '@test/utils';
import '../styles/index.less';
describe('Checkbox styles', () => {
itChrome('Should render the correct border', () => {
render(<Checkbox />);
const inner = screen.getByTestId('checkbox-control-inner');
expect(window.getComputedStyle(inner, '::before').border).to.equal(
`1px solid ${toRGB('#d9d9d9')}`
);
});
it('Should render the correct size', () => {
render(<Checkbox />);
expect(screen.getByRole('checkbox')).to.have.style('width', '36px');
expect(screen.getByRole('checkbox')).to.have.style('height', '36px');
});
});
``` | /content/code_sandbox/src/Checkbox/test/CheckboxStylesSpec.tsx | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 176 |
```xml
import {
ContentProjectionService,
LocalizationParam,
PROJECTION_STRATEGY,
Strict,
} from '@abp/ng.core';
import { ComponentRef, Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';
import { ToastContainerComponent } from '../components/toast-container/toast-container.component';
import { Toaster } from '../models';
@Injectable({
providedIn: 'root',
})
export class ToasterService implements ToasterContract {
private toasts$ = new ReplaySubject<Toaster.Toast[]>(1);
private lastId = -1;
private toasts = [] as Toaster.Toast[];
private containerComponentRef!: ComponentRef<ToastContainerComponent>;
constructor(private contentProjectionService: ContentProjectionService) {}
private setContainer() {
this.containerComponentRef = this.contentProjectionService.projectContent(
PROJECTION_STRATEGY.AppendComponentToBody(ToastContainerComponent, {
toasts$: this.toasts$,
remove: this.remove,
}),
);
this.containerComponentRef.changeDetectorRef.detectChanges();
}
/**
* Creates an info toast with given parameters.
* @param message Content of the toast
* @param title Title of the toast
* @param options Spesific style or structural options for individual toast
*/
info(
message: LocalizationParam,
title?: LocalizationParam,
options?: Partial<Toaster.ToastOptions>,
): Toaster.ToasterId {
return this.show(message, title, 'info', options);
}
/**
* Creates a success toast with given parameters.
* @param message Content of the toast
* @param title Title of the toast
* @param options Spesific style or structural options for individual toast
*/
success(
message: LocalizationParam,
title?: LocalizationParam,
options?: Partial<Toaster.ToastOptions>,
): Toaster.ToasterId {
return this.show(message, title, 'success', options);
}
/**
* Creates a warning toast with given parameters.
* @param message Content of the toast
* @param title Title of the toast
* @param options Spesific style or structural options for individual toast
*/
warn(
message: LocalizationParam,
title?: LocalizationParam,
options?: Partial<Toaster.ToastOptions>,
): Toaster.ToasterId {
return this.show(message, title, 'warning', options);
}
/**
* Creates an error toast with given parameters.
* @param message Content of the toast
* @param title Title of the toast
* @param options Spesific style or structural options for individual toast
*/
error(
message: LocalizationParam,
title?: LocalizationParam,
options?: Partial<Toaster.ToastOptions>,
): Toaster.ToasterId {
return this.show(message, title, 'error', options);
}
/**
* Creates a toast with given parameters.
* @param message Content of the toast
* @param title Title of the toast
* @param severity Sets color of the toast. "success", "warning" etc.
* @param options Spesific style or structural options for individual toast
*/
show(
message: LocalizationParam,
title: LocalizationParam | undefined = undefined,
severity: Toaster.Severity = 'neutral',
options = {} as Partial<Toaster.ToastOptions>,
): Toaster.ToasterId {
if (!this.containerComponentRef) this.setContainer();
const id = ++this.lastId;
this.toasts.push({
message,
title,
severity,
options: { closable: true, id, ...options },
});
this.toasts$.next(this.toasts);
return id;
}
/**
* Removes the toast with given id.
* @param id ID of the toast to be removed.
*/
remove = (id: number) => {
this.toasts = this.toasts.filter(toast => toast.options?.id !== id);
this.toasts$.next(this.toasts);
};
/**
* Removes all open toasts at once.
*/
clear(containerKey?: string): void {
this.toasts = !containerKey
? []
: this.toasts.filter(toast => toast.options?.containerKey !== containerKey);
this.toasts$.next(this.toasts);
}
}
export type ToasterContract = Strict<ToasterService, Toaster.Service>;
``` | /content/code_sandbox/npm/ng-packs/packages/theme-shared/src/lib/services/toaster.service.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 948 |
```xml
// See LICENSE in the project root for license information.
import * as path from 'path';
import { RushConfiguration } from '../../api/RushConfiguration';
import { Git } from '../Git';
import { PublishGit } from '../PublishGit';
import { PublishUtilities } from '../PublishUtilities';
describe('PublishGit Test', () => {
let gitPath: string;
let execCommand: jest.SpyInstance;
let publishGit: PublishGit;
beforeAll(() => {
gitPath = '/usr/bin/git';
process.env.RUSH_GIT_BINARY_PATH = gitPath;
});
beforeEach(() => {
execCommand = jest.spyOn(PublishUtilities, 'execCommandAsync').mockImplementation(async () => {
/* no-op */
});
const rushFilename: string = path.resolve(__dirname, '../../api/test/repo/rush-npm.json');
const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(rushFilename);
const git: Git = new Git(rushConfiguration);
publishGit = new PublishGit(git, 'test');
});
afterEach(() => {
execCommand.mockClear();
});
it('Test git with no command line arg tag', async () => {
await publishGit.addTagAsync(
false,
'project1',
'2',
undefined,
undefined // This is undefined to simulate `rush publish ...` without --prerelease-name
);
expect(execCommand).toBeCalledTimes(1);
expect(execCommand).toBeCalledWith(false, gitPath, ['tag', '-a', `project1_v2`, '-m', 'project1 v2']);
});
it('Test git with command line arg tag', async () => {
await publishGit.addTagAsync(
false,
'project1',
'2',
undefined,
'new_version_prerelease' // Simulates `rush publish ... --prerelease-name new_version_prerelease`
);
expect(execCommand).toBeCalledTimes(1);
expect(execCommand).toBeCalledWith(false, gitPath, [
'tag',
'-a',
`project1_v2-new_version_prerelease`,
'-m',
'project1 v2-new_version_prerelease'
]);
});
});
``` | /content/code_sandbox/libraries/rush-lib/src/logic/test/PublishGit.test.ts | xml | 2016-09-30T00:28:20 | 2024-08-16T18:54:35 | rushstack | microsoft/rushstack | 5,790 | 479 |
```xml
import { localized, WorkspaceStore, Actions } from 'mailspring-exports';
import { RetinaImg } from 'mailspring-component-kit';
import React from 'react';
export default class ModeToggle extends React.Component<
Record<string, unknown>,
{ hidden: boolean }
> {
static displayName = 'ModeToggle';
_mounted = false;
_unsubscriber: () => void;
column = WorkspaceStore.Location.MessageListSidebar;
constructor(props) {
super(props);
this.state = this._getStateFromStores();
}
componentDidMount() {
this._unsubscriber = WorkspaceStore.listen(this._onStateChanged);
this._mounted = true;
}
componentWillUnmount() {
this._mounted = false;
if (this._unsubscriber) {
this._unsubscriber();
}
}
_getStateFromStores() {
return {
hidden: WorkspaceStore.isLocationHidden(this.column),
};
}
_onStateChanged = () => {
// We need to keep track of this because our parent unmounts us in the same
// event listener cycle that we receive the event in. ie:
//
// for listener in listeners
// # 1. workspaceView remove left column
// # ---- Mode toggle unmounts, listeners array mutated in place
// # 2. ModeToggle update
if (!this._mounted) {
return;
}
this.setState(this._getStateFromStores());
};
_onToggleMode = () => {
Actions.toggleWorkspaceLocationHidden(this.column);
};
render() {
return (
<button
className={`btn btn-toolbar mode-toggle mode-${this.state.hidden}`}
style={{ order: 500 }}
title={this.state.hidden ? localized('Show Sidebar') : localized('Hide Sidebar')}
onClick={this._onToggleMode}
>
<RetinaImg name="toolbar-person-sidebar.png" mode={RetinaImg.Mode.ContentIsMask} />
</button>
);
}
}
``` | /content/code_sandbox/app/internal_packages/mode-switch/lib/mode-toggle.tsx | xml | 2016-10-13T06:45:50 | 2024-08-16T18:14:37 | Mailspring | Foundry376/Mailspring | 15,331 | 426 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="path_to_url">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{5F357488-8DEF-4E95-874E-FC526D92DE29}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Myrtille.Services</RootNamespace>
<AssemblyName>Myrtille.Services</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>bin\Debug\Myrtille.Services.exe.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>bin\Release\Myrtille.Services.exe.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>myrtille.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Cassia, Version=2.0.0.60, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Cassia.2.0.0.60\lib\2.0\Cassia.dll</HintPath>
</Reference>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework.SqlServerCompact, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.SqlServerCompact.6.2.0\lib\net45\EntityFramework.SqlServerCompact.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.8\lib\net45-full\log4net.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.SqlServer.Compact.4.0.8876.1\lib\net40\System.Data.SqlServerCe.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Security" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ConnectionBroker\ConnectionBrokerDbContext.cs" />
<Compile Include="ConnectionBroker\SessionType.cs" />
<Compile Include="ConnectionBroker\SessionState.cs" />
<Compile Include="ConnectionBroker\Server.cs" />
<Compile Include="ConnectionBroker\Session.cs" />
<Compile Include="ConnectionBroker\Target.cs" />
<Compile Include="ConnectionBroker\TargetIp.cs" />
<Compile Include="ConnectionBroker\TargetProperty.cs" />
<Compile Include="ConnectionBroker\User.cs" />
<Compile Include="EnterpriseService.cs" />
<Compile Include="FileStorage.cs" />
<Compile Include="MFAAuthentication.cs" />
<Compile Include="ApplicationPoolService.cs" />
<Compile Include="PrinterService.cs" />
<Compile Include="Program.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RemoteSessionProcess.cs" />
<Compile Include="ServicesInstaller.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="app.config">
<SubType>Designer</SubType>
</None>
<Content Include="Myrtille.Services.Install.ps1">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Myrtille.Services.Uninstall.ps1">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Include="packages.config" />
<Content Include="Password51.ps1">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="RDPSetup.reg">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 %28x86 et x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Myrtille.Common\Myrtille.Common.csproj">
<Project>{37630774-1321-4E6A-8661-4430A8946E9E}</Project>
<Name>Myrtille.Common</Name>
</ProjectReference>
<ProjectReference Include="..\Myrtille.Enterprise\Myrtille.Enterprise.csproj">
<Project>{9e4bf7c3-8ea3-428c-bea3-06cc3afcaeb4}</Project>
<Name>Myrtille.Enterprise</Name>
</ProjectReference>
<ProjectReference Include="..\Myrtille.MFAProviders\Myrtille.MFAProviders.csproj">
<Project>{3573c84d-5fd3-4bac-bf96-20b9fd0709ff}</Project>
<Name>Myrtille.MFAProviders</Name>
</ProjectReference>
<ProjectReference Include="..\Myrtille.Services.Contracts\Myrtille.Services.Contracts.csproj">
<Project>{010E1702-3045-4B13-BFB6-06FFC60B5CBB}</Project>
<Name>Myrtille.Services.Contracts</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="myrtille.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>
if not exist "$(TargetDir)x86" md "$(TargetDir)x86"
xcopy /s /y "$(SolutionDir)packages\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\x86\*.*" "$(TargetDir)x86"
if not exist "$(TargetDir)amd64" md "$(TargetDir)amd64"
xcopy /s /y "$(SolutionDir)packages\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\amd64\*.*" "$(TargetDir)amd64"</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
``` | /content/code_sandbox/Myrtille.Services/Myrtille.Services.csproj | xml | 2016-03-10T11:30:37 | 2024-08-16T11:10:12 | myrtille | cedrozor/myrtille | 1,778 | 2,836 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="path_to_url">
<item android:state_enabled="true" android:state_pressed="true">
<shape>
<solid android:color="@color/lightGray" />
<corners android:radius="@dimen/radius_8" />
</shape>
</item>
<item>
<shape>
<solid android:color="@color/white" />
<corners android:radius="@dimen/radius_8" />
</shape>
</item>
</selector>
``` | /content/code_sandbox/lib/common/src/main/res/drawable/common_button_bg.xml | xml | 2016-07-30T18:18:32 | 2024-08-16T01:37:59 | AndroidUtilCode | Blankj/AndroidUtilCode | 33,178 | 129 |
```xml
import { type FC, type ReactNode } from 'react';
import { Form, type FormikErrors, FormikProvider, useFormik } from 'formik';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Collapsible, CollapsibleContent, CollapsibleHeader, Icon, useNotifications } from '@proton/components/index';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { FieldsetCluster } from '@proton/pass/components/Form/Field/Layout/FieldsetCluster';
import { TextField } from '@proton/pass/components/Form/Field/TextField';
import { SidebarModal } from '@proton/pass/components/Layout/Modal/SidebarModal';
import { Panel } from '@proton/pass/components/Layout/Panel/Panel';
import { PanelHeader } from '@proton/pass/components/Layout/Panel/PanelHeader';
import { useRequest } from '@proton/pass/hooks/useActionRequest';
import { useCountdown } from '@proton/pass/hooks/useCountdown';
import { PassErrorCode } from '@proton/pass/lib/api/errors';
import type { AddressType, MonitorAddress } from '@proton/pass/lib/monitor/types';
import { resendVerificationCode, verifyCustomAddress } from '@proton/pass/store/actions';
import type { Maybe } from '@proton/pass/types';
import { getEpoch } from '@proton/pass/utils/time/epoch';
import { isNumber } from '@proton/shared/lib/helpers/validators';
export const FORM_ID = 'custom-address-verify';
type Props = { onClose: () => void; sentAt?: number } & MonitorAddress<AddressType.CUSTOM>;
type FormValues = { code: string };
const SECONDS_BEFORE_RESEND = 60;
const getInitialCountdown = (sentAt?: number): Maybe<number> => {
const now = getEpoch();
if (!sentAt || now - sentAt >= SECONDS_BEFORE_RESEND) return;
return Math.max(0, SECONDS_BEFORE_RESEND - (now - sentAt));
};
export const CustomAddressVerifyModal: FC<Props> = ({ onClose, email, addressId, sentAt }) => {
const [remaining, countdown] = useCountdown(getInitialCountdown(sentAt));
const { createNotification } = useNotifications();
const verify = useRequest(verifyCustomAddress, {
onSuccess: onClose,
onFailure: ({ data }) => {
if (data.code === PassErrorCode.NOT_ALLOWED) onClose();
},
});
const resend = useRequest(resendVerificationCode, {
onSuccess: () => {
createNotification({ text: c('Info').t`Verification code sent.`, type: 'success' });
countdown.start(SECONDS_BEFORE_RESEND);
},
onFailure: () => countdown.cancel(),
});
const form = useFormik<FormValues>({
initialValues: { code: '' },
validateOnChange: true,
validateOnMount: false,
validate: ({ code }) => {
let errors: FormikErrors<FormValues> = {};
if (!code) errors.code = c('Warning').t`Verification code is required`;
if (!isNumber(code)) errors.code = c('Warning').t`Invalid code`;
return errors;
},
onSubmit: ({ code }) => verify.dispatch({ addressId, code }),
});
return (
<SidebarModal onClose={onClose} open>
{(didEnter): ReactNode => (
<Panel
loading={verify.loading}
className="pass-panel--full"
header={
<PanelHeader
actions={[
<Button
key="cancel-button"
icon
pill
shape="solid"
color="weak"
onClick={onClose}
title={c('Action').t`Cancel`}
>
<Icon name="cross" alt={c('Action').t`Cancel`} />
</Button>,
<Button
color="norm"
disabled={verify.loading || !form.isValid}
form={FORM_ID}
key="modal-submit-button"
loading={verify.loading}
pill
type="submit"
>
{c('Action').t`Confirm`}
</Button>,
]}
/>
}
>
<h2 className="text-xl text-bold mb-3">{c('Title').t`Confirm your email`}</h2>
<p>{c('Info').t`Weve sent a verification code to ${email}. Please enter it below:`}</p>
<FormikProvider value={form}>
<Form id={FORM_ID}>
<FieldsetCluster>
<Field
name="code"
component={TextField}
label={c('Label').t`Code`}
type="number"
placeholder="123456"
autoFocus={didEnter}
dense
key={`custom-address-verify-${didEnter}`}
/>
</FieldsetCluster>
</Form>
</FormikProvider>
<div className="mt-2">
<Collapsible>
<CollapsibleHeader>
<Button color="norm" size="small" shape="underline">
{c('Info').t`Didn't receive the code?`}
</Button>
</CollapsibleHeader>
<CollapsibleContent className="text-sm py-2">
<span className="color-weak">
{c('Info').t`Please check your spam folder or try resending the code.`}
</span>
<Button
color="norm"
size="small"
disabled={resend.loading || remaining > 0}
loading={resend.loading}
onClick={() => resend.dispatch(addressId)}
shape="underline"
className="block"
>
{remaining > 0
? // translator: example usage: Resend code (in 30s)
c('Action').t`Resend code (in ${remaining}s)`
: c('Action').t`Resend code`}
</Button>
</CollapsibleContent>
</Collapsible>
</div>
</Panel>
)}
</SidebarModal>
);
};
``` | /content/code_sandbox/packages/pass/components/Monitor/Address/CustomAddressVerifyModal.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,280 |
```xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:immersive">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
</resources>
``` | /content/code_sandbox/CameraX/app/src/main/res/values/styles.xml | xml | 2016-02-25T11:06:48 | 2024-08-07T21:41:59 | android-examples | nisrulz/android-examples | 1,747 | 95 |
```xml
/*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import {
EMPTY,
Observable,
Subject,
catchError,
combineLatestWith,
concat,
debounceTime,
distinctUntilChanged,
distinctUntilKeyChanged,
endWith,
fromEvent,
ignoreElements,
map,
merge,
of,
share,
switchMap,
tap,
withLatestFrom
} from "rxjs"
import { configuration, feature } from "~/_"
import {
Viewport,
getElements,
getLocation,
getOptionalElement,
requestHTML,
setLocation,
setLocationHash
} from "~/browser"
import { getComponentElement } from "~/components"
import { Sitemap, fetchSitemap } from "../sitemap"
/* your_sha256_hash------------
* Helper types
* your_sha256_hash--------- */
/**
* Setup options
*/
interface SetupOptions {
location$: Subject<URL> // Location subject
viewport$: Observable<Viewport> // Viewport observable
progress$: Subject<number> // Progress subject
}
/* your_sha256_hash------------
* Helper functions
* your_sha256_hash--------- */
/**
* Handle clicks on internal URLs while skipping external URLs
*
* @param ev - Mouse event
* @param sitemap - Sitemap
*
* @returns URL observable
*/
function handle(
ev: MouseEvent, sitemap: Sitemap
): Observable<URL> {
if (!(ev.target instanceof Element))
return EMPTY
// Skip, as target is not within a link - clicks on non-link elements are
// also captured, which we need to exclude from processing
const el = ev.target.closest("a")
if (el === null)
return EMPTY
// Skip, as link opens in new window - we now know we have captured a click
// on a link, but the link either has a `target` property defined, or the
// user pressed the `meta` or `ctrl` key to open it in a new window. Thus,
// we need to filter this event as well.
if (el.target || ev.metaKey || ev.ctrlKey)
return EMPTY
// Next, we must check if the URL is relevant for us, i.e., if it's an
// internal link to a page that is managed by MkDocs. Only then we can be
// sure that the structure of the page to be loaded adheres to the current
// document structure and can subsequently be injected into it without doing
// a full reload. For this reason, we must canonicalize the URL by removing
// all search parameters and hash fragments.
const url = new URL(el.href)
url.search = url.hash = ""
// Skip, if URL is not included in the sitemap - this could be the case when
// linking between versions or languages, or to another page that the author
// included as part of the build, but that is not managed by MkDocs. In that
// case we must not continue with instant navigation.
if (!sitemap.has(`${url}`))
return EMPTY
// We now know that we have a link to an internal page, so we prevent the
// browser from navigation and emit the URL for instant navigation. Note that
// this also includes anchor links, which means we need to implement anchor
// positioning ourselves. The reason for this is that if we wouldn't manage
// anchor links as well, scroll restoration will not work correctly (e.g.
// following an anchor link and scrolling).
ev.preventDefault()
return of(new URL(el.href))
}
/**
* Create a map of head elements for lookup and replacement
*
* @param document - Document
*
* @returns Tag map
*/
function head(document: Document): Map<string, HTMLElement> {
const tags = new Map<string, HTMLElement>()
for (const el of getElements(":scope > *", document.head))
tags.set(el.outerHTML, el)
// Return tag map
return tags
}
/**
* Resolve relative URLs in the given document
*
* This function resolves relative `href` and `src` attributes, which can belong
* to all sorts of tags, like meta tags, links, images, scripts and more.
*
* @param document - Document
*
* @returns Document observable
*/
function resolve(document: Document): Observable<Document> {
for (const el of getElements("[href], [src]", document))
for (const key of ["href", "src"]) {
const value = el.getAttribute(key)
if (value && !/^(?:[a-z]+:)?\/\//i.test(value)) {
// @ts-expect-error - trick: self-assign to resolve URL
el[key] = el[key]
break
}
}
// Return document observable
return of(document)
}
/**
* Inject the contents of a document into the current one
*
* @param next - Next document
*
* @returns Document observable
*/
function inject(next: Document): Observable<Document> {
for (const selector of [
"[data-md-component=announce]",
"[data-md-component=container]",
"[data-md-component=header-topic]",
"[data-md-component=outdated]",
"[data-md-component=logo]",
"[data-md-component=skip]",
...feature("navigation.tabs.sticky")
? ["[data-md-component=tabs]"]
: []
]) {
const source = getOptionalElement(selector)
const target = getOptionalElement(selector, next)
if (
typeof source !== "undefined" &&
typeof target !== "undefined"
) {
source.replaceWith(target)
}
}
// Update meta tags
const tags = head(document)
for (const [html, el] of head(next))
if (tags.has(html))
tags.delete(html)
else
document.head.appendChild(el)
// Remove meta tags that are not present in the new document
for (const el of tags.values()) {
const name = el.getAttribute("name")
// @todo - find a better way to handle attributes we add dynamically in
// other components without mounting components on every navigation, as
// this might impact overall performance - see path_to_url
if (name !== "theme-color" && name !== "color-scheme")
el.remove()
}
// After components and meta tags were replaced, re-evaluate scripts
// that were provided by the author as part of Markdown files
const container = getComponentElement("container")
return concat(getElements("script", container))
.pipe(
switchMap(el => {
const script = next.createElement("script")
if (el.src) {
for (const name of el.getAttributeNames())
script.setAttribute(name, el.getAttribute(name)!)
el.replaceWith(script)
// Complete when script is loaded
return new Observable(observer => {
script.onload = () => observer.complete()
})
// Complete immediately
} else {
script.textContent = el.textContent
el.replaceWith(script)
return EMPTY
}
}),
ignoreElements(),
endWith(document)
)
}
/* your_sha256_hash------------
* Functions
* your_sha256_hash--------- */
/**
* Set up instant navigation
*
* This is a heavily orchestrated operation - see inline comments to learn how
* this works with Material for MkDocs, and how you can hook into it.
*
* @param options - Options
*
* @returns Document observable
*/
export function setupInstantNavigation(
{ location$, viewport$, progress$ }: SetupOptions
): Observable<Document> {
const config = configuration()
if (location.protocol === "file:")
return EMPTY
// Load sitemap immediately, so we have it available when the user initiates
// the first navigation request without any perceivable delay
const sitemap$ = fetchSitemap(config.base)
// Since we might be on a slow connection, the user might trigger multiple
// instant navigation events that overlap. MkDocs produces relative URLs for
// all internal links, which becomes a problem in this case, because we need
// to change the base URL the moment the user clicks a link that should be
// intercepted in order to be consistent with popstate, which means that the
// base URL would now be incorrect when resolving another relative link from
// the same site. For this reason we always resolve all relative links to
// absolute links, so we can be sure this never happens.
of(document)
.subscribe(resolve)
// your_sha256_hash----------
// Navigation interception
// your_sha256_hash----------
// Intercept navigation - to keep the number of event listeners down we use
// the fact that uncaptured events bubble up to the body. This has the nice
// property that we don't need to detach and then re-attach event listeners
// when the document is replaced after a navigation event.
const instant$ =
fromEvent<MouseEvent>(document.body, "click")
.pipe(
combineLatestWith(sitemap$),
switchMap(([ev, sitemap]) => handle(ev, sitemap)),
share()
)
// Intercept history change events, e.g. when the user uses the browser's
// back or forward buttons, and emit new location for fetching and parsing
const history$ =
fromEvent<PopStateEvent>(window, "popstate")
.pipe(
map(getLocation),
share()
)
// While it would be better UX to defer navigation events until the document
// is fully fetched and parsed, we must schedule it here to synchronize with
// popstate events, as they are emitted immediately. Moreover we need to
// store the current viewport offset for scroll restoration later on.
instant$.pipe(withLatestFrom(viewport$))
.subscribe(([url, { offset }]) => {
history.replaceState(offset, "")
history.pushState(null, "", url)
})
// Emit URLs that should be fetched via instant navigation on location subject
// which was passed into this function. The state of instant navigation can be
// intercepted by other parts of the application, which can synchronously back
// up or restore state before or after instant navigation happens.
merge(instant$, history$)
.subscribe(location$)
// your_sha256_hash----------
// Fetching and parsing
// your_sha256_hash----------
// Fetch document - we deduplicate requests to the same location, so we don't
// end up with multiple requests for the same page. We use `switchMap`, since
// we want to cancel the previous request when a new one is triggered, which
// is automatically handled by the observable returned by `request`. This is
// essential to ensure a good user experience, as we don't want to load pages
// that are not needed anymore, e.g., when the user clicks multiple links in
// quick succession or on slow connections. If the request fails for some
// reason, we fall back and use regular navigation, forcing a reload.
const document$ =
location$.pipe(
distinctUntilKeyChanged("pathname"),
switchMap(url => requestHTML(url, { progress$ })
.pipe(
catchError(() => {
setLocation(url, true)
return EMPTY
})
)
),
// The document was successfully fetched and parsed, so we can inject its
// contents into the currently active document
switchMap(resolve),
switchMap(inject),
share()
)
// your_sha256_hash----------
// Scroll restoration
// your_sha256_hash----------
// Handle scroll restoration - we must restore the viewport offset after the
// document has been fetched and injected, and every time the user clicks an
// anchor that leads to an element on the same page, which might also happen
// when the user uses the back or forward button.
merge(
document$.pipe(withLatestFrom(location$, (_, url) => url)),
// Handle instant navigation events that are triggered by the user clicking
// on an anchor link with a hash fragment different from the current one, as
// well as from popstate events, which are emitted when the user navigates
// back and forth between pages. We use a two-layered subscription to scope
// the scroll restoration to the current page, as we don't need to restore
// the viewport offset when the user navigates to a different page, as this
// is already handled by the previous observable.
document$.pipe(
switchMap(() => location$),
distinctUntilKeyChanged("pathname"),
switchMap(() => location$),
distinctUntilKeyChanged("hash")
),
// Handle instant navigation events that are triggered by the user clicking
// on an anchor link with the same hash fragment as the current one in the
// URL. It is essential that we only intercept those from instant navigation
// events and not from history change events, or we'll end up in and endless
// loop. The top-level history entry must be removed, as it will be replaced
// with a new one, which would otherwise lead to a duplicate entry.
location$.pipe(
distinctUntilChanged((a, b) => (
a.pathname === b.pathname &&
a.hash === b.hash
)),
switchMap(() => instant$),
tap(() => history.back())
)
)
.subscribe(url => {
// Check if the current history entry has a state, which happens when the
// user presses the back or forward button to visit a page we've already
// seen. If there's no state, it means a new page was visited and we must
// scroll to the top, unless an anchor is given.
if (history.state !== null || !url.hash) {
window.scrollTo(0, history.state?.y ?? 0)
} else {
history.scrollRestoration = "auto"
setLocationHash(url.hash)
history.scrollRestoration = "manual"
}
})
// Disable scroll restoration when an instant navigation event occurs, so the
// browser does not immediately set the viewport offset to the prior history
// entry, scrolling to the position on the same page, which would look odd.
// Instead, we manually restore the position once the page has loaded.
location$.subscribe(() => {
history.scrollRestoration = "manual"
})
// Enable scroll restoration before window unloads - this is essential to
// ensure that full reloads (F5) restore the viewport offset correctly. If
// only popstate events wouldn't reset the viewport offset prior to their
// emission, we could just reset this in popstate. Meh.
fromEvent(window, "beforeunload")
.subscribe(() => {
history.scrollRestoration = "auto"
})
// Track viewport offset, so we can restore it when the user navigates back
// and forth between pages. Note that this must be debounced and cannot be
// done in popstate, as popstate has already removed the entry from the
// history, which means it is too late.
viewport$.pipe(
distinctUntilKeyChanged("offset"),
debounceTime(100)
)
.subscribe(({ offset }) => {
history.replaceState(offset, "")
})
// Return document observable
return document$
}
``` | /content/code_sandbox/src/templates/assets/javascripts/integrations/instant/index.ts | xml | 2016-01-28T22:09:23 | 2024-08-16T17:55:06 | mkdocs-material | squidfunk/mkdocs-material | 19,629 | 3,493 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<cobra document="path_to_url">
<name value=""/>
<language value="php"/>
<match mode="function-param-controllable"><![CDATA[include|include_once|require|require_once|parsekit_compile_file|php_check_syntax|runkit_import|virtual]]></match>
<level value="7"/>
<test>
<case assert="true"><![CDATA[include($_GET['file']);]]></case>
<case assert="true"><![CDATA[require_once($_GET['file']);]]></case>
</test>
<solution>
##
LFI/FRI(/)
###
###
##
1.
2. ()
```php
<?php
$file = $_GET['file'];
//Whitelisting possible values
switch ($file) {
case 'main':
case 'foo':
case 'bar':
include '/home/wwwroot/include/'.$file.'.php';
break;
default:
include '/home/wwwroot/include/main.php';
}
?>
```
</solution>
<status value="on"/>
<author name="Feei" email="feei@feei.cn"/>
</cobra>
``` | /content/code_sandbox/rules/CVI-170002.xml | xml | 2016-04-15T08:41:15 | 2024-08-16T10:33:17 | Cobra | FeeiCN/Cobra | 3,133 | 275 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="path_to_url" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_AWS1_KNS_SCENARIO</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Kinesis Code Example Scenario</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
<WITH_UNIT_TESTS>X</WITH_UNIT_TESTS>
</VSEOCLASS>
<DESCRIPTIONS>
<SEOCOMPOTX>
<CMPNAME>GETTING_STARTED_WITH_KNS</CMPNAME>
<LANGU>E</LANGU>
<DESCRIPT>Getting started with Kinesis</DESCRIPT>
</SEOCOMPOTX>
</DESCRIPTIONS>
</asx:values>
</asx:abap>
</abapGit>
``` | /content/code_sandbox/sap-abap/services/kinesis/zcl_aws1_kns_scenario.clas.xml | xml | 2016-08-18T19:06:57 | 2024-08-16T18:59:44 | aws-doc-sdk-examples | awsdocs/aws-doc-sdk-examples | 9,298 | 260 |
```xml
import StockData from '../StockData';
import CandlestickFinder from './CandlestickFinder';
export default class TweezerBottom extends CandlestickFinder {
constructor();
logic(data: StockData): boolean;
downwardTrend(data: StockData): boolean;
}
export declare function tweezerbottom(data: StockData): any;
``` | /content/code_sandbox/declarations/candlestick/TweezerBottom.d.ts | xml | 2016-05-02T19:16:32 | 2024-08-15T14:25:09 | technicalindicators | anandanand84/technicalindicators | 2,137 | 69 |
```xml
import Setting, { SettingType } from "../../../lib/Setting";
import Store, { StateBuilder } from "../../flux/Store";
import { ChartType } from "../../../lib/Database/Chart";
import { QueryType } from "../../../lib/Database/Query";
import { DataSourceType } from "../DataSource/DataSourceStore";
export interface QueryState {
setting: SettingType;
queries: QueryType[];
dataSources: DataSourceType[];
charts: ChartType[];
selectedQueryId: number | null;
editor: {
height: number | null;
line: number | null;
};
}
export default class QueryStore extends Store<QueryState> {
constructor() {
super();
this.state = {
setting: Setting.getDefault(),
queries: [],
dataSources: [],
charts: [],
selectedQueryId: null,
editor: {
height: null,
line: null,
},
};
}
override reduce(type: string, payload: any): StateBuilder<QueryState> {
switch (type) {
case "initialize": {
return this.merge("setting", payload.setting)
.mergeList("queries", payload.queries)
.mergeList("charts", payload.charts)
.mergeList("dataSources", payload.dataSources);
}
case "selectQuery": {
const idx = this.findQueryIndex(payload.id);
return this.set("selectedQueryId", payload.id).set("editor.line", null).merge(`queries.${idx}`, payload.query);
}
case "addNewQuery": {
return this.set("selectedQueryId", payload.query.id).set("editor.line", null).prepend("queries", payload.query);
}
case "updateQuery": {
const idx = this.findQueryIndex(payload.id);
return this.merge(`queries.${idx}`, payload.params);
}
case "deleteQuery": {
const idx = this.findQueryIndex(payload.id);
return this.set("selectedQueryId", null).set("editor.line", null).del(`queries.${idx}`);
}
case "updateEditor": {
return this.merge("editor", payload);
}
case "selectResultTab": {
const idx = this.findQueryIndex(payload.id);
return this.set(`queries.${idx}.selectedTab`, payload.name);
}
case "addChart": {
return this.append("charts", payload.chart);
}
case "updateChart": {
const idx = this.findChartIndex(payload.id);
return this.merge(`charts.${idx}`, payload.params);
}
default: {
throw new Error("Invalid type");
}
}
}
findQueryIndex(id: number): number {
const idx = this.state.queries.findIndex((q) => q.id === id);
if (idx === -1) {
throw new Error(`query id:${id} not found`);
}
return idx;
}
findChartIndex(id: number): number {
const idx = this.state.charts.findIndex((c) => c.id === id);
if (idx === -1) {
throw new Error(`chart id:${id} not found`);
}
return idx;
}
}
const { store, dispatch } = Store.create<QueryState>(QueryStore);
export { store, dispatch };
``` | /content/code_sandbox/src/renderer/pages/Query/QueryStore.ts | xml | 2016-08-23T12:20:03 | 2024-08-14T08:26:34 | bdash | bdash-app/bdash | 1,488 | 694 |
```xml
import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react'
import { useEffectOnce } from 'react-use'
import { SerializedDocWithSupplemental } from '../../../../cloud/interfaces/db/doc'
import { SerializedRevision } from '../../../../cloud/interfaces/db/revision'
import { getAllRevisionsFromDoc } from '../../../../cloud/api/teams/docs/revisions'
import { usePage } from '../../../../cloud/lib/stores/pageStore'
import { mdiBackupRestore } from '@mdi/js'
import { useSettings } from '../../../../cloud/lib/stores/settings'
import {
useDialog,
DialogIconTypes,
} from '../../../../design/lib/stores/dialog'
import styled from '../../../../design/lib/styled'
import { compareDateString } from '../../../../cloud/lib/date'
import { trackEvent } from '../../../../cloud/api/track'
import { MixpanelActionTrackTypes } from '../../../../cloud/interfaces/analytics/mixpanel'
import { useModal } from '../../../../design/lib/stores/modal'
import ModalContainer from './atoms/ModalContainer'
import RevisionModalNavigator from '../../../../cloud/components/Modal/contents/Doc/RevisionsModal/RevisionModalNavigator'
import Spinner from '../../../../design/components/atoms/Spinner'
import ErrorBlock from '../../../../cloud/components/ErrorBlock'
import Button from '../../../../design/components/atoms/Button'
import RevisionModalDetail from '../../../../cloud/components/Modal/contents/Doc/RevisionsModal/RevisionModalDetail'
import { focusFirstChildFromElement } from '../../../../design/lib/dom'
import Icon from '../../../../design/components/atoms/Icon'
import { createPatch } from 'diff'
interface MobileDocRevisionsModalProps {
currentDoc: SerializedDocWithSupplemental
restoreRevision?: (revisionContent: string) => void
}
const MobileDocRevisionsModal = ({
currentDoc,
restoreRevision,
}: MobileDocRevisionsModalProps) => {
const [fetching, setFetching] = useState<boolean>(false)
const contentSideRef = useRef<HTMLDivElement>(null)
const menuRef = useRef<HTMLDivElement>(null)
const [revisionsMap, setRevisionsMap] = useState<
Map<number, SerializedRevision>
>(new Map())
const [error, setError] = useState<unknown>()
const { subscription, currentUserPermissions } = usePage()
const { closeLastModal: closeModal } = useModal()
const { openSettingsTab } = useSettings()
const [revisionIndex, setRevisionIndex] = useState<number>()
const { messageBox } = useDialog()
const [currentPage, setCurrentPage] = useState<number>(1)
const [totalPages, setTotalPages] = useState<number>(1)
const onRestoreClick = useCallback(
async (revisionContent: string) => {
if (restoreRevision == null) {
return
}
messageBox({
title: `Restore this revision?`,
message: `Are you sure to restore this revision?`,
iconType: DialogIconTypes.Warning,
buttons: [
{
variant: 'secondary',
label: 'Cancel',
cancelButton: true,
defaultButton: true,
},
{
variant: 'primary',
label: 'Restore',
onClick: async () => {
restoreRevision(revisionContent)
closeModal()
return
},
},
],
})
},
[messageBox, restoreRevision, closeModal]
)
const updateRevisionsMap = useCallback(
(...mappedRevisions: [number, SerializedRevision][]) =>
setRevisionsMap((prevMap) => {
return new Map([...prevMap, ...mappedRevisions])
}),
[]
)
const fetchRevisions = useCallback(
async (nextPage: number) => {
if (fetching) {
return
}
setFetching(true)
try {
const { revisions, page, totalPages } = await getAllRevisionsFromDoc(
currentDoc.teamId,
currentDoc.id,
nextPage
)
const mappedRevisions = revisions.reduce((acc, val) => {
acc.set(val.id, val)
return acc
}, new Map<number, SerializedRevision>())
setCurrentPage(page)
setTotalPages(totalPages)
updateRevisionsMap(...mappedRevisions)
if (page === 1 && revisions.length > 0) {
focusFirstChildFromElement(menuRef.current)
setRevisionIndex(revisions[0].id)
}
} catch (error) {
setError(error)
}
setFetching(false)
},
[fetching, currentDoc.teamId, currentDoc.id, updateRevisionsMap]
)
useEffectOnce(() => {
trackEvent(MixpanelActionTrackTypes.DocFeatureRevision)
fetchRevisions(currentPage)
})
const preview = useMemo(() => {
if (revisionIndex == null) {
return null
}
const revisions: SerializedRevision[] = [...revisionsMap.values()]
const revisionIds: number[] = [...revisionsMap.values()].map(
(rev) => rev.id
)
const currentRevisionIndex = revisionIds.indexOf(revisionIndex)
const previousRevisionIndex = currentRevisionIndex + 1
if (previousRevisionIndex > revisions.length || previousRevisionIndex < 0) {
return null
}
try {
const currentRevision = revisions[currentRevisionIndex]!
const previousRevision = revisions[previousRevisionIndex]!
if (previousRevision == null) {
const currentDocumentRevisionDiff = currentRevision.content
.split('\n')
.map((line) => ` ${line}`)
.join('\n')
return (
<RevisionModalDetail
revisionDiff={currentDocumentRevisionDiff}
revisionContent={currentRevision.content}
revisionCreatedAt={currentRevision.created}
revisionCreators={currentRevision.creators}
onRestoreClick={onRestoreClick}
/>
)
}
const numberOfRevisionLines = previousRevision.content.split('\n').length
const revisionDiff = createPatch(
currentRevision.doc != null
? currentRevision.doc.title
: 'Revision Diff',
previousRevision.content,
currentRevision.content,
undefined,
undefined,
{
context: numberOfRevisionLines,
}
)
.split('\n')
.filter((line) => !line.startsWith('\\ No newline at end of file'))
.slice(5) // removes headers from diff (revision title, number of deletions and additions)
.join('\n')
return (
<RevisionModalDetail
revisionContent={currentRevision.content}
revisionCreatedAt={currentRevision.created}
revisionCreators={currentRevision.creators}
revisionDiff={revisionDiff}
onRestoreClick={onRestoreClick}
/>
)
} catch (err) {
return null
}
}, [revisionsMap, revisionIndex, onRestoreClick])
const rightSideContent = useMemo(() => {
if (error != null) {
return (
<div>
<ErrorBlock error={error} style={{ marginBottom: 20 }} />
<Button
variant='secondary'
disabled={fetching}
onClick={() => fetchRevisions(currentPage)}
>
{fetching ? <Spinner /> : 'Try again'}
</Button>
</div>
)
}
if (subscription == null && currentUserPermissions != null) {
return (
<div>
<Icon path={mdiBackupRestore} size={50} className='backup_icon' />
<p>
Let's upgrade to the Pro plan now and protect your shared
documents with a password.
<br /> You can try a two-week trial for free!
</p>
<Button
variant='primary'
onClick={() => {
openSettingsTab('teamUpgrade')
closeModal()
}}
>
Start Free Trial
</Button>
</div>
)
}
return <StyledContent>{preview}</StyledContent>
}, [
currentUserPermissions,
error,
subscription,
closeModal,
openSettingsTab,
preview,
fetching,
fetchRevisions,
currentPage,
])
const orderedRevisions = useMemo(() => {
return [...revisionsMap.values()].sort((a, b) => {
return compareDateString(b.created, a.created)
})
}, [revisionsMap])
useEffect(() => {
if (orderedRevisions.length === 0) {
setRevisionIndex(undefined)
return
}
focusFirstChildFromElement(menuRef.current)
setRevisionIndex(orderedRevisions[0].id)
}, [orderedRevisions, menuRef])
return (
<ModalContainer title={'Revisions'}>
<RevisionModalNavigator
revisions={orderedRevisions}
menuRef={menuRef}
fetching={fetching}
revisionIndex={
revisionIndex == null
? undefined
: { type: 'cloud', id: revisionIndex }
}
subscription={subscription}
setRevisionIndex={({ id }) => setRevisionIndex(id as number)}
currentPage={currentPage}
totalPages={totalPages}
fetchRevisions={fetchRevisions}
currentUserPermissions={currentUserPermissions}
/>
<div className='right' ref={contentSideRef}>
{rightSideContent}
</div>
</ModalContainer>
)
}
export default MobileDocRevisionsModal
const StyledContent = styled.div`
color: ${({ theme }) => theme.colors.text.primary};
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
.backup_icon {
margin-bottom: 20px;
}
`
``` | /content/code_sandbox/src/mobile/components/organisms/modals/MobileDocRevisionsModal.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 2,020 |
```xml
import { NativeModule } from 'expo';
import ImageManipulatorContext from './web/ImageManipulatorContext.web';
import ImageManipulatorImageRef from './web/ImageManipulatorImageRef.web';
import { loadImageAsync } from './web/utils.web';
class ImageManipulator extends NativeModule {
Context = ImageManipulatorContext;
Image = ImageManipulatorImageRef;
manipulate(uri: string): ImageManipulatorContext {
return new ImageManipulatorContext(() => loadImageAsync(uri));
}
}
export default new ImageManipulator();
``` | /content/code_sandbox/packages/expo-image-manipulator/src/ExpoImageManipulator.web.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 110 |
```xml
import { useEffect, useMemo, useState } from 'react';
import { FormikErrors } from 'formik';
import { useEnvironmentId } from '@/react/hooks/useEnvironmentId';
import {
useIngressControllers,
useIngresses,
} from '@/react/kubernetes/ingresses/queries';
import { FormSection } from '@@/form-components/FormSection';
import { ServiceFormValues, ServiceTypeOption, ServiceType } from './types';
import { generateUniqueName } from './utils';
import { ClusterIpServicesForm } from './cluster-ip/ClusterIpServicesForm';
import { ServiceTabs } from './components/ServiceTabs';
import { NodePortServicesForm } from './node-port/NodePortServicesForm';
import { LoadBalancerServicesForm } from './load-balancer/LoadBalancerServicesForm';
import { ServiceTabLabel } from './components/ServiceTabLabel';
import { PublishingExplaination } from './PublishingExplaination';
interface Props {
values: ServiceFormValues[];
onChange: (services: ServiceFormValues[]) => void;
errors?: FormikErrors<ServiceFormValues[]>;
appName: string;
selector: Record<string, string>;
isEditMode: boolean;
namespace?: string;
}
export function KubeServicesForm({
values: services,
onChange,
errors,
appName,
selector,
isEditMode,
namespace,
}: Props) {
const [selectedServiceType, setSelectedServiceType] =
useState<ServiceType>('ClusterIP');
// start loading ingresses and controllers early to reduce perceived loading time
const environmentId = useEnvironmentId();
useIngresses(environmentId, namespace ? [namespace] : []);
useIngressControllers(environmentId, namespace);
// when the appName changes, update the names for each service
// and the serviceNames for each service port
const newServiceNames = useMemo(
() => getUniqNames(appName, services),
[appName, services]
);
useEffect(() => {
if (!isEditMode) {
const newServices = services.map((service, index) => {
const newServiceName = newServiceNames[index];
const newServicePorts = service.Ports.map((port) => ({
...port,
serviceName: newServiceName,
}));
return { ...service, Name: newServiceName, Ports: newServicePorts };
});
onChange(newServices);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [appName]);
const serviceTypeCounts = useMemo(
() => getServiceTypeCounts(services),
[services]
);
const serviceTypeHasErrors = useMemo(
() => getServiceTypeHasErrors(services, errors),
[services, errors]
);
const serviceTypeOptions: ServiceTypeOption[] = [
{
value: 'ClusterIP',
label: (
<ServiceTabLabel
serviceTypeLabel="ClusterIP services"
serviceTypeCount={serviceTypeCounts.ClusterIP}
serviceTypeHasErrors={serviceTypeHasErrors.ClusterIP}
/>
),
},
{
value: 'NodePort',
label: (
<ServiceTabLabel
serviceTypeLabel="NodePort services"
serviceTypeCount={serviceTypeCounts.NodePort}
serviceTypeHasErrors={serviceTypeHasErrors.NodePort}
/>
),
},
{
value: 'LoadBalancer',
label: (
<ServiceTabLabel
serviceTypeLabel="LoadBalancer services"
serviceTypeCount={serviceTypeCounts.LoadBalancer}
serviceTypeHasErrors={serviceTypeHasErrors.LoadBalancer}
/>
),
},
];
return (
<div className="flex flex-col">
<FormSection title="Publishing the application" />
<PublishingExplaination />
<ServiceTabs
serviceTypeOptions={serviceTypeOptions}
selectedServiceType={selectedServiceType}
setSelectedServiceType={setSelectedServiceType}
/>
{selectedServiceType === 'ClusterIP' && (
<ClusterIpServicesForm
services={services}
onChangeService={onChange}
errors={errors}
appName={appName}
selector={selector}
namespace={namespace}
isEditMode={isEditMode}
/>
)}
{selectedServiceType === 'NodePort' && (
<NodePortServicesForm
services={services}
onChangeService={onChange}
errors={errors}
appName={appName}
selector={selector}
namespace={namespace}
isEditMode={isEditMode}
/>
)}
{selectedServiceType === 'LoadBalancer' && (
<LoadBalancerServicesForm
services={services}
onChangeService={onChange}
errors={errors}
appName={appName}
selector={selector}
namespace={namespace}
isEditMode={isEditMode}
/>
)}
</div>
);
}
function getUniqNames(appName: string, services: ServiceFormValues[]) {
const sortedServices = [...services].sort((a, b) =>
a.Name && b.Name ? a.Name.localeCompare(b.Name) : 0
);
const uniqueNames = sortedServices.reduce(
(acc: string[]) => {
const newIndex =
acc.findIndex((existingName) => existingName === appName) + 1;
const uniqName = acc.includes(appName)
? generateUniqueName(appName, newIndex, services)
: appName;
return [...acc, uniqName];
},
[appName]
);
return uniqueNames;
}
/**
* getServiceTypeCounts returns a map of service types to the number of services of that type
*/
function getServiceTypeCounts(
services: ServiceFormValues[]
): Record<ServiceType, number> {
return services.reduce(
(acc, service) => {
const type = service.Type;
const count = acc[type];
return {
...acc,
[type]: count ? count + 1 : 1,
};
},
{} as Record<ServiceType, number>
);
}
/**
* getServiceTypeHasErrors returns a map of service types to whether or not they have errors
*/
function getServiceTypeHasErrors(
services: ServiceFormValues[],
errors: FormikErrors<ServiceFormValues[] | undefined>
): Record<ServiceType, boolean> {
return services.reduce(
(acc, service, index) => {
const type = service.Type;
const serviceHasErrors = !!errors?.[index];
// if the service type already has an error, don't overwrite it
if (acc[type] === true) return acc;
// otherwise, set the error to the value of serviceHasErrors
return {
...acc,
[type]: serviceHasErrors,
};
},
{} as Record<ServiceType, boolean>
);
}
``` | /content/code_sandbox/app/react/kubernetes/applications/CreateView/application-services/KubeServicesForm.tsx | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 1,426 |
```xml
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M120,720Q87,720 63.5,696.5Q40,673 40,640Q40,607 63.5,583.5Q87,560 120,560Q126,560 130.5,560Q135,560 140,562L322,380Q320,375 320,370.5Q320,366 320,360Q320,327 343.5,303.5Q367,280 400,280Q433,280 456.5,303.5Q480,327 480,360Q480,362 478,380L580,482Q585,480 589.5,480Q594,480 600,480Q606,480 610.5,480Q615,480 620,482L762,340Q760,335 760,330.5Q760,326 760,320Q760,287 783.5,263.5Q807,240 840,240Q873,240 896.5,263.5Q920,287 920,320Q920,353 896.5,376.5Q873,400 840,400Q834,400 829.5,400Q825,400 820,398L678,540Q680,545 680,549.5Q680,554 680,560Q680,593 656.5,616.5Q633,640 600,640Q567,640 543.5,616.5Q520,593 520,560Q520,554 520,549.5Q520,545 522,540L420,438Q415,440 410.5,440Q406,440 400,440Q398,440 380,438L198,620Q200,625 200,629.5Q200,634 200,640Q200,673 176.5,696.5Q153,720 120,720Z"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_timeline_24.xml | xml | 2016-08-15T19:10:31 | 2024-08-16T19:34:19 | Aegis | beemdevelopment/Aegis | 8,651 | 502 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="path_to_url"
android:id="@+id/activity_play"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<com.example.gsyvideoplayer.video.SmartPickVideo
android:id="@+id/video_player"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
</RelativeLayout>
``` | /content/code_sandbox/app/src/main/res/layout/activity_play_pick.xml | xml | 2016-11-13T12:34:31 | 2024-08-16T15:39:12 | GSYVideoPlayer | CarGuo/GSYVideoPlayer | 19,994 | 115 |
```xml
<project xmlns="path_to_url" xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zheng</groupId>
<artifactId>zheng-api</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>zheng-api-server</artifactId>
<packaging>war</packaging>
<name>zheng-api-server Maven Webapp</name>
<url>path_to_url
<dependencies>
<dependency>
<groupId>com.zheng</groupId>
<artifactId>zheng-api-rpc-api</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.zheng</groupId>
<artifactId>zheng-admin</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- zheng-upms-client -->
<dependency>
<groupId>com.zheng</groupId>
<artifactId>zheng-upms-client</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<build>
<finalName>zheng-api-server</finalName>
<filters>
<filter>src/main/resources/profiles/${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!-- jetty -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<!--<version>9.0.0.v20130308</version>-->
<version>9.2.7.v20150116</version>
<configuration>
<scanIntervalSeconds>3</scanIntervalSeconds>
<webApp>
<contextPath>/</contextPath>
</webApp>
<httpConnector>
<port>6666</port>
</httpConnector>
<reload>automatic</reload>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<skipTests>true</skipTests>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
``` | /content/code_sandbox/zheng-api/zheng-api-server/pom.xml | xml | 2016-10-04T10:07:06 | 2024-08-16T07:00:44 | zheng | shuzheng/zheng | 16,660 | 829 |
```xml
export * from './FieldTypeInput';
export * from './FieldViewsInput';
``` | /content/code_sandbox/packages/ra-no-code/src/ResourceConfiguration/FieldConfiguration/index.ts | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.