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 { IChoiceGroupOption } from '@fluentui/react/lib/ChoiceGroup';
import { IPropertyFieldListPickerPropsInternal } from './IPropertyFieldListPicker';
import { ISPLists } from './IPropertyFieldListPickerHost';
/**
* PropertyFieldListPickerHost properties interface
*/
export interface IPropertyFieldListMultiPickerHostProps extends IPropertyFieldListPickerPropsInternal {
onChange: (targetProperty?: string, newValue?: any) => void; // eslint-disable-line @typescript-eslint/no-explicit-any
}
/**
* PropertyFieldSPListMultiplePickerHost state interface
*/
export interface IPropertyFieldListMultiPickerHostState {
loadedLists: ISPLists;
results: IChoiceGroupOption[];
selectedKeys: string[];
loaded: boolean;
errorMessage?: string;
}
``` | /content/code_sandbox/samples/react-kanban-board/src/webparts/kanbanBoard/components/PropertyListPicker/IPropertyFieldListMultiPickerHost.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 166 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="DebugStatic|Win32">
<Configuration>DebugStatic</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseStatic|Win32">
<Configuration>ReleaseStatic</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="DebugDLL|Win32">
<Configuration>DebugDLL</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDLL|Win32">
<Configuration>ReleaseDLL</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{B6995F32-4579-BC41-A170-5D2F22742841}</ProjectGuid>
<RootNamespace>tutorial_1_1</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\debugstatic\vs2013\tutorial_1_1\x32\</IntDir>
<TargetName>tutorial_1_1_debugstatic_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\releasestatic\vs2013\tutorial_1_1\x32\</IntDir>
<TargetName>tutorial_1_1_releasestatic_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\debugdll\vs2013\tutorial_1_1\x32\</IntDir>
<TargetName>tutorial_1_1_debugdll_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\releasedll\vs2013\tutorial_1_1\x32\</IntDir>
<TargetName>tutorial_1_1_releasedll_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj %(AdditionalOptions)</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<SmallerTypeCheck>true</SmallerTypeCheck>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<ProgramDataBaseFileName>$(OutDir)tutorial_1_1_debugstatic_win32_vs2013.pdb</ProgramDataBaseFileName>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<OutputFile>$(OutDir)tutorial_1_1_debugstatic_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj /Ox /Oi /Ob1 /Ot %(AdditionalOptions)</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat></DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<OutputFile>$(OutDir)tutorial_1_1_releasestatic_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj %(AdditionalOptions)</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<SmallerTypeCheck>true</SmallerTypeCheck>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<ProgramDataBaseFileName>$(OutDir)tutorial_1_1_debugdll_win32_vs2013.pdb</ProgramDataBaseFileName>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<OutputFile>$(OutDir)tutorial_1_1_debugdll_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj /Ox /Oi /Ob1 /Ot %(AdditionalOptions)</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat></DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<OutputFile>$(OutDir)tutorial_1_1_releasedll_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\behaviac_types.h" />
<ClInclude Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\internal\behaviac_agent_headers.h" />
<ClInclude Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\internal\behaviac_agent_member_visitor.h" />
<ClInclude Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\internal\behaviac_agent_meta.h" />
<ClInclude Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\internal\behaviac_headers.h" />
<ClInclude Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\internal\FirstAgent.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\tutorials\tutorial_1_1\cpp\tutorial_1_1.cpp">
</ClCompile>
<ClCompile Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\internal\behaviac_agent_meta.cpp">
</ClCompile>
<ClCompile Include="..\..\tutorials\tutorial_1_1\cpp\behaviac_generated\types\internal\FirstAgent.cpp">
</ClCompile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="behaviac.vcxproj">
<Project>{332CEEDC-7568-D84C-B9C6-B710915836ED}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
``` | /content/code_sandbox/projects/vs2013/tutorial_1_1.vcxproj | xml | 2016-11-21T05:08:08 | 2024-08-16T07:18:30 | behaviac | Tencent/behaviac | 2,831 | 3,474 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<!DOCTYPE configuration>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- example of logging a single mapper method...
<logger name="examples.animal.data.AnimalDataMapper.insertSelect" level="debug" />
-->
<root level="warn">
<appender-ref ref="STDOUT" />
</root>
</configuration>
``` | /content/code_sandbox/src/test/resources/logback.xml | xml | 2016-11-11T15:22:00 | 2024-08-15T19:57:41 | mybatis-dynamic-sql | mybatis/mybatis-dynamic-sql | 1,082 | 166 |
```xml
import {
Component,
Input,
ChangeDetectionStrategy,
ChangeDetectorRef,
Optional,
} from '@angular/core';
import { Dir } from '@angular/cdk/bidi';
import { tdCollapseAnimation } from './collapse.animation';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'td-json-formatter',
styleUrls: ['./json-formatter.component.scss'],
templateUrl: './json-formatter.component.html',
animations: [tdCollapseAnimation],
})
export class TdJsonFormatterComponent {
/**
* Max length for property names. Any names bigger than this get trunctated.
*/
private static KEY_MAX_LENGTH = 30;
/**
* Max length for preview string. Any names bigger than this get trunctated.
*/
private static PREVIEW_STRING_MAX_LENGTH = 80;
/**
* Max tooltip preview elements.
*/
private static PREVIEW_LIMIT = 5;
private _key?: string;
private _data!: Record<string, any>;
private _children?: string[];
private _open = false;
private _levelsOpen = 0;
/**
* levelsOpen?: number
* Levels opened by default when JS object is formatted and rendered.
*/
@Input()
set levelsOpen(levelsOpen: number) {
if (!Number.isInteger(levelsOpen)) {
throw new Error('[levelsOpen] needs to be an integer.');
}
this._levelsOpen = levelsOpen;
this._open = levelsOpen > 0;
}
get levelsOpen(): number {
return this._levelsOpen;
}
get open(): boolean {
return this._open;
}
/**
* key?: string
* Tag to be displayed next to formatted object.
*/
@Input()
set key(key: string) {
this._key = key;
}
get key(): string {
const elipsis: string =
this._key && this._key.length > TdJsonFormatterComponent.KEY_MAX_LENGTH
? ''
: '';
return this._key
? this._key.substring(0, TdJsonFormatterComponent.KEY_MAX_LENGTH) +
elipsis
: this._key ?? '';
}
/**
* data: any
* JS object to be formatted.
*/
@Input()
set data(data: Record<string, any>) {
this._data = data;
this.parseChildren();
}
get data(): Record<string, any> {
return this._data;
}
get children(): string[] {
return this._children ?? [];
}
get isRTL(): boolean {
if (this._dir) {
return this._dir.dir === 'rtl';
}
return false;
}
constructor(
private _changeDetectorRef: ChangeDetectorRef,
@Optional() private _dir: Dir
) {}
/**
* Refreshes json-formatter and rerenders [data]
*/
refresh(): void {
this._changeDetectorRef.markForCheck();
}
/**
* Toggles collapse/expanded state of component.
*/
toggle(): void {
this._open = !this._open;
}
isObject(): boolean {
return this.getType(this._data) === 'object';
}
isArray(): boolean {
return Array.isArray(this._data);
}
hasChildren(): boolean {
return (this._children && this._children.length > 0) ?? false;
}
/**
* Gets parsed value depending on value type.
*/
getValue(value: any): string {
const type: string = this.getType(value);
if (type === 'undefined' || type === 'null') {
return type;
} else if (type === 'date') {
value = new Date(value).toString();
} else if (type === 'string') {
value = '"' + value + '"';
} else if (type === 'function') {
// Remove content of the function
return (
value
.toString()
.replace(/[\r\n]/g, '')
.replace(/\{.*\}/, '') + '{}'
);
} else if (Array.isArray(value)) {
return this.getObjectName() + ' [' + value.length + ']';
}
return value;
}
/**
* Gets type of object.
* returns 'null' if object is null and 'date' if value is object and can be parsed to a date.
*/
getType(object: any): string {
if (typeof object === 'object') {
if (!object) {
return 'null';
}
if (Array.isArray(object)) {
return 'object';
}
const date: Date = new Date(object);
if (
Object.prototype.toString.call(date) === '[object Date]' &&
!Number.isNaN(date.getTime())
) {
return 'date';
}
}
return typeof object;
}
/**
* Generates string representation depending if its an object or function.
* see: path_to_url
*/
getObjectName(): string {
const object: any = this._data;
if (this.isObject() && !object.constructor) {
return 'Object';
}
const funcNameRegex = /function (.{1,})\(/;
const results = funcNameRegex.exec(object.constructor.toString());
if (results && results.length > 1) {
return results[1];
} else {
return '';
}
}
/**
* Creates preview of nodes children to render in tooltip depending if its an array or an object.
*/
getPreview(): string {
let previewData: string[];
let startChar = '{ ';
let endChar = ' }';
if (this.isArray()) {
const previewArray: any[] =
Object.entries(this._data).slice(
0,
TdJsonFormatterComponent.PREVIEW_LIMIT
) ?? [];
previewData = previewArray.map((obj: any) => {
return this.getValue(obj);
});
startChar = '[';
endChar = ']';
} else {
const previewKeys: string[] =
this._children?.slice(0, TdJsonFormatterComponent.PREVIEW_LIMIT) ?? [];
previewData = previewKeys.map((key: string) => {
return key + ': ' + this.getValue(this._data[key] ?? undefined);
});
}
const previewString: string = previewData.join(', ');
const ellipsis: string =
previewData.length >= TdJsonFormatterComponent.PREVIEW_LIMIT ||
previewString.length > TdJsonFormatterComponent.PREVIEW_STRING_MAX_LENGTH
? ''
: '';
return (
startChar +
previewString.substring(
0,
TdJsonFormatterComponent.PREVIEW_STRING_MAX_LENGTH
) +
ellipsis +
endChar
);
}
private parseChildren(): void {
if (this.isObject()) {
this._children = Object.keys(this._data ?? {});
}
}
}
``` | /content/code_sandbox/libs/angular/json-formatter/src/json-formatter.component.ts | xml | 2016-07-11T23:30:52 | 2024-08-15T15:20:45 | covalent | Teradata/covalent | 2,228 | 1,501 |
```xml
#import <wchar.h>
#import <AppKit/NSPasteboard.h>
#import "pasteboard.h"
NSString *stringFromWchar(const wchar_t *charText) {
return [[NSString alloc] initWithBytes:charText length:wcslen(charText)*sizeof(*charText) encoding:NSUTF32LittleEndianStringEncoding];
}
NSString *stringFromChar(const char *charText)
{
return [NSString stringWithUTF8String:charText];
}
void CopyToPasteboard(const char* szText) {
[[NSPasteboard generalPasteboard] clearContents];
// [[NSPasteboard generalPasteboard] setString:[NSString stringWithUTF8String:szText] forType:NSPasteboardTypeString];
[[NSPasteboard generalPasteboard] setString:stringFromChar(szText) forType:NSPasteboardTypeString];
}
void CopyToPasteboard(const wchar_t* wszText) {
[[NSPasteboard generalPasteboard] clearContents];
[[NSPasteboard generalPasteboard] setString:stringFromWchar(wszText) forType:NSPasteboardTypeString];
}
``` | /content/code_sandbox/WinPort/src/Backend/WX/Mac/pasteboard.mm | xml | 2016-08-10T20:43:58 | 2024-08-15T16:13:31 | far2l | elfmz/far2l | 1,743 | 223 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="log.context.name" value="whatsmars-zk-embed" />
<property name="log.charset" value="UTF-8" />
<property name="log.pattern" value="[%-5level] %date --%thread-- [%logger] %msg %n" />
<contextName>${log.context.name}</contextName>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder charset="${log.charset}">
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="STDOUT" />
</root>
<logger name="org.apache.zookeeper" level="INFO" />
<logger name="org.apache.curator" level="INFO" />
</configuration>
``` | /content/code_sandbox/whatsmars-zk-embed/src/main/resources/logback.xml | xml | 2016-04-01T10:33:04 | 2024-08-14T23:44:08 | whatsmars | javahongxi/whatsmars | 1,952 | 205 |
```xml
import { ThemeConfig } from 'antd/es/config-provider/context'
import baseTheme from './base'
const lightTheme: ThemeConfig = {
...baseTheme,
token: {
...baseTheme.token,
},
}
export default lightTheme
``` | /content/code_sandbox/examples/lambda-function-url/packages/ui/themes/light.ts | xml | 2016-09-13T23:29:07 | 2024-08-15T09:52:47 | serverless-express | CodeGenieApp/serverless-express | 5,117 | 51 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14490.49"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="QuoraDots" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="logo" translatesAutoresizingMaskIntoConstraints="NO" id="Wfr-VL-nO5">
<rect key="frame" x="87" y="240" width="201" height="56"/>
<constraints>
<constraint firstAttribute="width" secondItem="Wfr-VL-nO5" secondAttribute="height" multiplier="201:56" id="049-qb-Rsw"/>
<constraint firstAttribute="width" constant="201" id="8tR-Ca-c1U"/>
</constraints>
</imageView>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="dot" translatesAutoresizingMaskIntoConstraints="NO" id="s6W-lT-U40">
<rect key="frame" x="132.5" y="313" width="30" height="30"/>
<constraints>
<constraint firstAttribute="width" secondItem="s6W-lT-U40" secondAttribute="height" multiplier="1:1" id="CBd-1c-Yew"/>
<constraint firstAttribute="height" constant="30" id="qz6-lI-9kW"/>
</constraints>
</imageView>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="dot" translatesAutoresizingMaskIntoConstraints="NO" id="GgF-Wf-hy8">
<rect key="frame" x="172.5" y="313" width="30" height="30"/>
<constraints>
<constraint firstAttribute="width" secondItem="GgF-Wf-hy8" secondAttribute="height" multiplier="1:1" id="LjX-ZT-UdJ"/>
<constraint firstAttribute="height" constant="30" id="nhJ-wm-9eN"/>
</constraints>
</imageView>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="dot" translatesAutoresizingMaskIntoConstraints="NO" id="yyM-Jn-TbA">
<rect key="frame" x="212.5" y="313" width="30" height="30"/>
<constraints>
<constraint firstAttribute="height" constant="30" id="i8i-n6-M7E"/>
</constraints>
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="GgF-Wf-hy8" firstAttribute="leading" secondItem="s6W-lT-U40" secondAttribute="trailing" constant="10" id="2qr-mZ-PjP"/>
<constraint firstItem="yyM-Jn-TbA" firstAttribute="top" secondItem="GgF-Wf-hy8" secondAttribute="top" id="8WL-DR-3vq"/>
<constraint firstItem="s6W-lT-U40" firstAttribute="top" secondItem="Wfr-VL-nO5" secondAttribute="bottom" constant="17" id="SKL-23-2eq"/>
<constraint firstItem="GgF-Wf-hy8" firstAttribute="centerX" secondItem="AcL-ne-zNK" secondAttribute="centerX" id="XvY-Cv-Kgu"/>
<constraint firstItem="yyM-Jn-TbA" firstAttribute="leading" secondItem="GgF-Wf-hy8" secondAttribute="trailing" constant="10" id="Yde-0J-0XQ"/>
<constraint firstItem="yyM-Jn-TbA" firstAttribute="width" secondItem="yyM-Jn-TbA" secondAttribute="height" multiplier="1:1" id="aSf-fK-Wle"/>
<constraint firstItem="GgF-Wf-hy8" firstAttribute="top" secondItem="s6W-lT-U40" secondAttribute="top" id="bC8-tm-Qml"/>
<constraint firstItem="Wfr-VL-nO5" firstAttribute="centerX" secondItem="AcL-ne-zNK" secondAttribute="centerX" id="fWe-Fn-uAw"/>
<constraint firstItem="Wfr-VL-nO5" firstAttribute="top" secondItem="AcL-ne-zNK" secondAttribute="top" constant="220" id="xXW-9U-4AN"/>
</constraints>
<viewLayoutGuide key="safeArea" id="AcL-ne-zNK"/>
</view>
<connections>
<outlet property="dotOne" destination="s6W-lT-U40" id="S10-Zz-UFi"/>
<outlet property="dotThree" destination="yyM-Jn-TbA" id="CmU-Jh-AXW"/>
<outlet property="dotTwo" destination="GgF-Wf-hy8" id="9J5-P7-VCi"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="136.80000000000001" y="137.18140929535232"/>
</scene>
</scenes>
<resources>
<image name="dot" width="54" height="54"/>
<image name="logo" width="402" height="112"/>
</resources>
</document>
``` | /content/code_sandbox/Project 14 - QuoraDots/QuoraDots/Base.lproj/Main.storyboard | xml | 2016-02-14T20:14:21 | 2024-08-15T20:49:08 | Swift-30-Projects | soapyigu/Swift-30-Projects | 8,036 | 1,613 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="path_to_url"
android:oneshot="false">
<item
android:drawable="@drawable/app_loading0"
android:duration="150" />
<item
android:drawable="@drawable/app_loading1"
android:duration="150" />
<item
android:drawable="@drawable/app_loading2"
android:duration="150" />
<item
android:drawable="@drawable/app_loading3"
android:duration="150" />
</animation-list>
``` | /content/code_sandbox/bymvvm/src/main/res/drawable/yun_anim.xml | xml | 2016-11-20T11:59:25 | 2024-08-14T13:24:02 | CloudReader | youlookwhat/CloudReader | 4,933 | 127 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:tools="path_to_url"
xmlns:android="path_to_url">
<application tools:ignore="MissingApplicationIcon">
<service
android:name="com.x8bit.bitwarden.data.push.BitwardenFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- Disable Crashlytics for debug builds -->
<meta-data
android:name="firebase_crashlytics_collection_enabled"
android:value="false" />
</application>
</manifest>
``` | /content/code_sandbox/app/src/standardDebug/AndroidManifest.xml | xml | 2016-04-30T16:43:17 | 2024-08-16T19:45:08 | android | bitwarden/android | 6,085 | 147 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="path_to_url"
package="com.journaldev.efficientsearch">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
``` | /content/code_sandbox/Android/EfficientSearch/app/src/main/AndroidManifest.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 154 |
```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 { assert } from "chai";
import enUSLocale from "date-fns/locale/en-US";
import { mount, type ReactWrapper } from "enzyme";
import * as React from "react";
import { Day } from "react-day-picker";
import sinon from "sinon";
import { Button, Classes as CoreClasses, HTMLSelect, Menu, MenuItem } from "@blueprintjs/core";
import {
type DatePickerShortcut,
DatePickerShortcutMenu,
DateUtils,
Errors,
Months,
TimePicker,
TimePrecision,
} from "@blueprintjs/datetime";
import { assertDatesEqual } from "@blueprintjs/test-commons";
import { Classes } from "../../src/classes";
import { DatePicker3, type DatePicker3Props } from "../../src/components/date-picker3/datePicker3";
import type { DatePicker3State } from "../../src/components/date-picker3/datePicker3State";
import { assertDayDisabled, assertDayHidden } from "../common/dayPickerTestUtils";
import { loadDateFnsLocaleFake } from "../common/loadDateFnsLocaleFake";
const LOCALE_LOADER: DatePicker3Props = {
dateFnsLocaleLoader: loadDateFnsLocaleFake,
};
describe("<DatePicker3>", () => {
let testsContainerElement: HTMLElement;
let datePicker3Wrapper: ReactWrapper<DatePicker3Props, DatePicker3State>;
beforeEach(() => {
testsContainerElement = document.createElement("div");
document.body.appendChild(testsContainerElement);
});
afterEach(() => {
datePicker3Wrapper?.unmount();
datePicker3Wrapper?.detach();
testsContainerElement.remove();
});
it(`renders .${Classes.DATEPICKER}`, () => {
assert.lengthOf(wrap(<DatePicker3 {...LOCALE_LOADER} />).root.find(`.${Classes.DATEPICKER}`), 1);
});
it("no day is selected by default", () => {
const { assertSelectedDays, root } = wrap(<DatePicker3 {...LOCALE_LOADER} />);
assertSelectedDays();
assert.isNull(root.state("selectedDay"));
});
it("current day is not highlighted by default", () => {
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} />);
assert.lengthOf(root.find(`.${Classes.DATEPICKER3_HIGHLIGHT_CURRENT_DAY}`), 0);
});
it("current day should be highlighted when highlightCurrentDay={true}", () => {
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} highlightCurrentDay={true} />);
assert.lengthOf(root.find(`.${Classes.DATEPICKER3_HIGHLIGHT_CURRENT_DAY}`), 1);
});
describe("reconciliates dayPickerProps", () => {
it("shows outside days by default", () => {
const defaultValue = new Date(2017, Months.SEPTEMBER, 1);
const firstDayInView = new Date(2017, Months.AUGUST, 27, 12, 0);
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} />);
// TODO: refactor this to avoid knowing about react-day-picker's internal component names
const firstDay = root.find(Day).first();
assertDatesEqual(new Date(firstDay.prop("date")), firstDayInView);
});
it("doesn't show outside days if enableOutsideDays=false", () => {
const defaultValue = new Date(2017, Months.SEPTEMBER, 1, 12);
const { root } = wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
dayPickerProps={{ showOutsideDays: false }}
/>,
);
const days = root.find(Day);
assertDayHidden(days.at(0));
assertDayHidden(days.at(1));
assertDayHidden(days.at(2));
assertDayHidden(days.at(3));
assertDayHidden(days.at(4));
assertDayHidden(days.at(5), false);
});
it("disables days according to custom modifiers in addition to default modifiers", () => {
const defaultValue = new Date(2017, Months.SEPTEMBER, 1);
const disableFridays = { dayOfWeek: [5] };
const { getDay } = wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
maxDate={new Date(2017, Months.SEPTEMBER, 20)}
dayPickerProps={{ disabled: disableFridays }}
/>,
);
assertDayDisabled(getDay(15));
assertDayDisabled(getDay(21));
assertDayDisabled(getDay(10), false);
});
it("disables out-of-range max dates", () => {
const defaultValue = new Date(2017, Months.SEPTEMBER, 1);
const { getDay } = wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
maxDate={new Date(2017, Months.SEPTEMBER, 20)}
/>,
);
assertDayDisabled(getDay(21));
assertDayDisabled(getDay(10), false);
});
it("disables out-of-range min dates", () => {
const defaultValue = new Date(2017, Months.SEPTEMBER, 1);
const { getDay, clickPreviousMonth } = wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
minDate={new Date(2017, Months.AUGUST, 20)}
/>,
);
clickPreviousMonth();
assertDayDisabled(getDay(10));
assertDayDisabled(getDay(21), false);
});
describe("event handlers", () => {
// use a date that lets us navigate forward and backward in the same year
const defaultValue = new Date(2017, Months.SEPTEMBER, 1);
it("calls onMonthChange on button next click", () => {
const onMonthChange = sinon.spy();
const { root } = wrap(
<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} dayPickerProps={{ onMonthChange }} />,
);
root.find(`.${Classes.DATEPICKER3_NAV_BUTTON_NEXT}`).first().simulate("click");
assert.isTrue(onMonthChange.called);
});
it("calls onMonthChange on button prev click", () => {
const onMonthChange = sinon.spy();
const { root } = wrap(
<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} dayPickerProps={{ onMonthChange }} />,
);
root.find(`.${Classes.DATEPICKER3_NAV_BUTTON_PREVIOUS}`).first().simulate("click");
assert.isTrue(onMonthChange.called);
});
it("calls onMonthChange on month select change", () => {
const onMonthChange = sinon.spy();
const { root } = wrap(
<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} dayPickerProps={{ onMonthChange }} />,
);
root.find(`.${Classes.DATEPICKER_MONTH_SELECT}`).first().find("select").simulate("change");
assert.isTrue(onMonthChange.called);
});
it("calls onMonthChange on year select change", () => {
const onMonthChange = sinon.spy();
const { root } = wrap(
<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} dayPickerProps={{ onMonthChange }} />,
);
root.find(`.${Classes.DATEPICKER_YEAR_SELECT}`).first().find("select").simulate("change");
assert.isTrue(onMonthChange.called);
});
it("calls onDayClick", () => {
const onDayClick = sinon.spy();
const { getDay } = wrap(
<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} dayPickerProps={{ onDayClick }} />,
);
getDay().simulate("click");
assert.isTrue(onDayClick.called);
});
});
});
it("user-provided modifiers are applied", () => {
const ODD_CLASS = "test-odd";
const oddifier = (d: Date) => d.getDate() % 2 === 1;
const { getDay } = wrap(
<DatePicker3
{...LOCALE_LOADER}
dayPickerProps={{ modifiers: { odd: oddifier }, modifiersClassNames: { odd: ODD_CLASS } }}
/>,
);
assert.isFalse(getDay(4).hasClass(ODD_CLASS));
assert.isTrue(getDay(5).hasClass(ODD_CLASS));
});
it("renders the actions bar when showActionsBar=true", () => {
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} showActionsBar={true} />);
assert.lengthOf(root.find({ className: Classes.DATEPICKER_FOOTER }), 1);
});
describe("initially displayed month", () => {
it("is defaultValue", () => {
const defaultValue = new Date(2007, Months.APRIL, 4);
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} />);
assert.equal(root.state("displayYear"), 2007);
assert.equal(root.state("displayMonth"), Months.APRIL);
});
it("is initialMonth if set (overrides defaultValue)", () => {
const defaultValue = new Date(2007, Months.APRIL, 4);
const initialMonth = new Date(2002, Months.MARCH, 1);
const { root } = wrap(
<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} initialMonth={initialMonth} />,
);
assert.equal(root.state("displayYear"), 2002);
assert.equal(root.state("displayMonth"), Months.MARCH);
});
it("is value if set and initialMonth not set", () => {
const value = new Date(2007, Months.APRIL, 4);
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} value={value} />);
assert.equal(root.state("displayYear"), 2007);
assert.equal(root.state("displayMonth"), Months.APRIL);
});
it("is today if today is within date range", () => {
const today = new Date();
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} />);
assert.equal(root.state("displayYear"), today.getFullYear());
assert.equal(root.state("displayMonth"), today.getMonth());
});
it("is a day between minDate and maxDate if today is not in range", () => {
const maxDate = new Date(2005, Months.JANUARY);
const minDate = new Date(2000, Months.JANUARY);
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} maxDate={maxDate} minDate={minDate} />);
assert.isTrue(
DateUtils.isDayInRange(new Date(root.state("displayYear"), root.state("displayMonth")), [
minDate,
maxDate,
]),
);
});
it("selectedDay is set to the day of the value", () => {
const value = new Date(2007, Months.APRIL, 4);
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} value={value} />);
assert.strictEqual(root.state("selectedDay"), value.getDate());
});
it("selectedDay is set to the day of the defaultValue", () => {
const defaultValue = new Date(2007, Months.APRIL, 4);
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} defaultValue={defaultValue} />);
assert.strictEqual(root.state("selectedDay"), defaultValue.getDate());
});
});
describe("minDate/maxDate bounds", () => {
const MIN_DATE = new Date(2015, Months.JANUARY, 7);
const MAX_DATE = new Date(2015, Months.JANUARY, 12);
describe("validation", () => {
let consoleError: sinon.SinonStub;
before(() => (consoleError = sinon.stub(console, "error")));
afterEach(() => consoleError.resetHistory());
after(() => consoleError.restore());
it("maxDate must be later than minDate", () => {
wrap(<DatePicker3 {...LOCALE_LOADER} maxDate={MIN_DATE} minDate={MAX_DATE} />);
assert.isTrue(consoleError.calledWith(Errors.DATEPICKER_MAX_DATE_INVALID));
});
it("an error is logged if defaultValue is outside bounds", () => {
wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={new Date(2015, Months.JANUARY, 5)}
maxDate={MAX_DATE}
minDate={MIN_DATE}
/>,
);
assert.isTrue(consoleError.calledWith(Errors.DATEPICKER_DEFAULT_VALUE_INVALID));
});
it("an error is logged if value is outside bounds", () => {
wrap(
<DatePicker3
{...LOCALE_LOADER}
value={new Date(2015, Months.JANUARY, 20)}
maxDate={MAX_DATE}
minDate={MIN_DATE}
/>,
);
assert.isTrue(consoleError.calledWith(Errors.DATEPICKER_VALUE_INVALID));
});
it("an error is logged if initialMonth is outside month bounds", () => {
wrap(
<DatePicker3
{...LOCALE_LOADER}
initialMonth={new Date(2015, Months.FEBRUARY, 12)}
maxDate={MAX_DATE}
minDate={MIN_DATE}
/>,
);
assert.isTrue(consoleError.calledWith(Errors.DATEPICKER_INITIAL_MONTH_INVALID));
});
it("an error is not logged if initialMonth is outside day bounds but inside month bounds", () => {
wrap(
<DatePicker3
{...LOCALE_LOADER}
initialMonth={new Date(2015, Months.JANUARY, 12)}
minDate={MIN_DATE}
maxDate={MAX_DATE}
/>,
);
assert.isTrue(consoleError.notCalled);
});
});
describe("today button validation", () => {
const today = new Date();
const MIN_DATE_BEFORE_TODAY = MIN_DATE;
const MAX_DATE_BEFORE_TODAY = MAX_DATE;
const MIN_DATE_AFTER_TODAY = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
const MAX_DATE_AFTER_TODAY = new Date(today.getFullYear() + 2, today.getMonth(), today.getDate());
it("min/max before today has disabled button", () => {
const { getTodayButton } = wrap(
<DatePicker3
{...LOCALE_LOADER}
minDate={MIN_DATE_BEFORE_TODAY}
maxDate={MAX_DATE_BEFORE_TODAY}
showActionsBar={true}
/>,
);
assert.isTrue(getTodayButton().props().disabled);
});
it("min/max after today has disabled button", () => {
const { getTodayButton } = wrap(
<DatePicker3
{...LOCALE_LOADER}
minDate={MIN_DATE_AFTER_TODAY}
maxDate={MAX_DATE_AFTER_TODAY}
showActionsBar={true}
/>,
);
assert.isTrue(getTodayButton().props().disabled);
});
it("valid min/max today has enabled button", () => {
const { getTodayButton } = wrap(
<DatePicker3
{...LOCALE_LOADER}
minDate={MIN_DATE_BEFORE_TODAY}
maxDate={MAX_DATE_AFTER_TODAY}
showActionsBar={true}
/>,
);
assert.isFalse(getTodayButton().props().disabled);
});
});
it("only days outside bounds have disabled class", () => {
const minDate = new Date(2000, Months.JANUARY, 10);
const { getDay } = wrap(<DatePicker3 {...LOCALE_LOADER} initialMonth={minDate} minDate={minDate} />);
// 8 is before min date, 12 is after
assert.isTrue(getDay(8).hasClass(Classes.DATEPICKER3_DAY_DISABLED));
assert.isFalse(getDay(12).hasClass(Classes.DATEPICKER3_DAY_DISABLED));
});
it("onChange not fired when a day outside of bounds is clicked", () => {
const onChange = sinon.spy();
const { getDay } = wrap(
<DatePicker3 {...LOCALE_LOADER} maxDate={MAX_DATE} minDate={MIN_DATE} onChange={onChange} />,
);
assert.isTrue(onChange.notCalled);
getDay(4).simulate("click");
getDay(16).simulate("click");
assert.isTrue(onChange.notCalled);
getDay(8).simulate("click");
assert.isTrue(onChange.calledOnce);
});
it("constrains time picker when minDate is selected", () => {
const { root } = wrap(
<DatePicker3
{...LOCALE_LOADER}
maxDate={MAX_DATE}
minDate={MIN_DATE}
timePrecision={TimePrecision.MINUTE}
value={MIN_DATE}
/>,
);
const timePicker = root.find(TimePicker).first();
assert.strictEqual(timePicker.props().minTime, MIN_DATE);
});
it("constrains time picker when max date is selected", () => {
const { root } = wrap(
<DatePicker3
{...LOCALE_LOADER}
maxDate={MAX_DATE}
minDate={MIN_DATE}
timePrecision={TimePrecision.MINUTE}
value={MAX_DATE}
/>,
);
const timePicker = root.find(TimePicker).first();
assert.strictEqual(timePicker.props().maxTime, MAX_DATE);
});
});
describe("when controlled", () => {
it("value initially selects a day", () => {
const value = new Date(2010, Months.JANUARY, 1);
const { assertSelectedDays } = wrap(
<DatePicker3 {...LOCALE_LOADER} defaultValue={new Date(2010, Months.FEBRUARY, 2)} value={value} />,
);
assertSelectedDays(value.getDate());
});
it("selection does not update automatically", () => {
const { getDay, assertSelectedDays } = wrap(<DatePicker3 {...LOCALE_LOADER} value={null} />);
assertSelectedDays();
getDay().simulate("click");
assertSelectedDays();
});
it("selected day doesn't update on current month view change", () => {
const value = new Date(2010, Months.JANUARY, 2);
const { assertSelectedDays, clickPreviousMonth, months, years } = wrap(
<DatePicker3 {...LOCALE_LOADER} value={value} />,
);
clickPreviousMonth();
assertSelectedDays(2);
months.simulate("change", { target: { value: Months.JUNE } });
assertSelectedDays();
years.simulate("change", { target: { value: 2014 } });
assertSelectedDays();
});
it("onChange fired when a day is clicked", () => {
const onChange = sinon.spy();
const { getDay } = wrap(<DatePicker3 {...LOCALE_LOADER} onChange={onChange} value={null} />);
getDay().simulate("click");
assert.isTrue(onChange.calledOnce);
assert.isTrue(onChange.args[0][1]);
});
it("onChange fired when month is changed", () => {
const value = new Date(2010, Months.JANUARY, 2);
const onChange = sinon.spy();
const { months, clickPreviousMonth } = wrap(
<DatePicker3 {...LOCALE_LOADER} onChange={onChange} value={value} />,
);
clickPreviousMonth();
assert.isTrue(onChange.calledOnce, "expected onChange called");
assert.isFalse(onChange.firstCall.args[1], "expected isUserChange to be false");
months.simulate("change", { target: { value: Months.JUNE } });
assert.isTrue(onChange.calledTwice, "expected onChange called again");
assert.isFalse(onChange.secondCall.args[1], "expected isUserChange to be false again");
});
it("can change displayed date with the dropdowns in the caption", () => {
const { months, root, years } = wrap(
<DatePicker3 {...LOCALE_LOADER} initialMonth={new Date(2015, Months.MARCH, 2)} value={null} />,
);
assert.equal(root.state("displayMonth"), Months.MARCH);
assert.equal(root.state("displayYear"), 2015);
months.simulate("change", { target: { value: Months.JANUARY } });
years.simulate("change", { target: { value: 2014 } });
assert.equal(root.state("displayMonth"), Months.JANUARY);
assert.equal(root.state("displayYear"), 2014);
});
it("shortcuts fire onChange with correct values", () => {
const today = new Date();
const aWeekAgo = DateUtils.clone(today);
aWeekAgo.setDate(today.getDate() - 6);
const onChange = sinon.spy();
const { clickShortcut } = wrap(
<DatePicker3 {...LOCALE_LOADER} onChange={onChange} value={today} shortcuts={true} />,
);
clickShortcut(2);
assert.isTrue(onChange.calledOnce, "called");
const value = onChange.args[0][0];
assert.isTrue(DateUtils.isSameDay(aWeekAgo, value));
});
it("all shortcuts are displayed as inactive when none are selected", () => {
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} shortcuts={true} />);
assert.isFalse(
root.find(DatePickerShortcutMenu).find(Menu).find(MenuItem).find(`.${CoreClasses.ACTIVE}`).exists(),
);
});
it("corresponding shortcut is displayed as active when selected", () => {
const selectedShortcut = 0;
const { root } = wrap(
<DatePicker3 {...LOCALE_LOADER} shortcuts={true} selectedShortcutIndex={selectedShortcut} />,
);
assert.isTrue(
root.find(DatePickerShortcutMenu).find(Menu).find(MenuItem).find(`.${CoreClasses.ACTIVE}`).exists(),
);
assert.lengthOf(
root.find(DatePickerShortcutMenu).find(Menu).find(MenuItem).find(`.${CoreClasses.ACTIVE}`),
1,
);
assert.isTrue(root.state("selectedShortcutIndex") === selectedShortcut);
});
it("should call onShortcutChangeSpy on selecting a shortcut ", () => {
const selectedShortcut = 0;
const onShortcutChangeSpy = sinon.spy();
const onChangeSpy = sinon.spy();
const { clickShortcut } = wrap(
<DatePicker3
{...LOCALE_LOADER}
onChange={onChangeSpy}
shortcuts={true}
onShortcutChange={onShortcutChangeSpy}
/>,
);
clickShortcut(selectedShortcut);
assert.isTrue(onChangeSpy.calledOnce);
assert.isTrue(onShortcutChangeSpy.calledOnce);
assert.isTrue(onShortcutChangeSpy.lastCall.args[0].label === "Today");
assert.isTrue(onShortcutChangeSpy.lastCall.args[1] === selectedShortcut);
});
it("custom shortcuts select the correct values", () => {
const date = new Date(2015, Months.JANUARY, 1);
const onChangeSpy = sinon.spy();
const { clickShortcut, assertSelectedDays } = wrap(
<DatePicker3
{...LOCALE_LOADER}
onChange={onChangeSpy}
shortcuts={[{ label: "custom shortcut", date }]}
/>,
);
clickShortcut();
assert.isTrue(onChangeSpy.calledOnce);
const value = onChangeSpy.args[0][0];
assert.isTrue(DateUtils.isSameDay(date, value));
assertSelectedDays(date.getDate());
});
});
describe("when uncontrolled", () => {
it("defaultValue initially selects a day", () => {
const today = new Date();
const { assertSelectedDays } = wrap(<DatePicker3 {...LOCALE_LOADER} defaultValue={today} />);
assertSelectedDays(today.getDate());
});
it("onChange fired when a day is clicked", () => {
const onChange = sinon.spy();
const { getDay } = wrap(<DatePicker3 {...LOCALE_LOADER} onChange={onChange} />);
assert.isTrue(onChange.notCalled);
getDay().simulate("click");
assert.isTrue(onChange.calledOnce);
});
it("onChange fired when month is changed", () => {
const onChange = sinon.spy();
// must use an initial month otherwise clicking next month in december will fail
const { getDay, clickNextMonth } = wrap(
<DatePicker3
{...LOCALE_LOADER}
initialMonth={new Date(2015, Months.JANUARY, 12)}
onChange={onChange}
/>,
);
assert.isTrue(onChange.notCalled);
getDay().simulate("click");
assert.isTrue(onChange.calledOnce, "expected onChange called");
clickNextMonth();
assert.isTrue(onChange.calledTwice, "expected onChange called again");
});
it("selected day updates are automatic", () => {
const { assertSelectedDays, getDay } = wrap(<DatePicker3 {...LOCALE_LOADER} />);
assertSelectedDays();
getDay(3).simulate("click");
assertSelectedDays(3);
});
it("selected day is preserved when selections are changed", () => {
const initialMonth = new Date(2015, Months.JULY, 1);
const { assertSelectedDays, getDay, months } = wrap(
<DatePicker3 {...LOCALE_LOADER} initialMonth={initialMonth} />,
);
getDay(31).simulate("click");
months.simulate("change", { target: { value: Months.AUGUST } });
assertSelectedDays(31);
});
it("selected day is changed if necessary when selections are changed", () => {
const initialMonth = new Date(2015, Months.JULY, 1);
const { assertSelectedDays, getDay, clickPreviousMonth } = wrap(
<DatePicker3 {...LOCALE_LOADER} initialMonth={initialMonth} />,
);
getDay(31).simulate("click");
clickPreviousMonth();
assertSelectedDays(30);
// remembers actual date that was clicked and restores if possible
clickPreviousMonth();
assertSelectedDays(31);
});
it("selected day is changed to minDate or maxDate if selections are changed outside bounds", () => {
const initialMonth = new Date(2015, Months.JULY, 1);
const minDate = new Date(2015, Months.MARCH, 13);
const maxDate = new Date(2015, Months.NOVEMBER, 21);
const { assertSelectedDays, getDay, months } = wrap(
<DatePicker3 {...LOCALE_LOADER} initialMonth={initialMonth} minDate={minDate} maxDate={maxDate} />,
);
getDay(1).simulate("click");
months.simulate("change", { target: { value: Months.MARCH } });
assertSelectedDays(minDate.getDate());
getDay(25).simulate("click");
months.simulate("change", { target: { value: Months.NOVEMBER } });
assertSelectedDays(maxDate.getDate());
});
it("can change displayed date with the dropdowns in the caption", () => {
const { months, root, years } = wrap(
<DatePicker3 {...LOCALE_LOADER} initialMonth={new Date(2015, Months.MARCH, 2)} />,
);
assert.equal(root.state("displayMonth"), Months.MARCH);
assert.equal(root.state("displayYear"), 2015);
months.simulate("change", { target: { value: Months.JANUARY } });
years.simulate("change", { target: { value: 2014 } });
assert.equal(root.state("displayMonth"), Months.JANUARY);
assert.equal(root.state("displayYear"), 2014);
});
it("shortcuts select values", () => {
const { root, clickShortcut } = wrap(<DatePicker3 {...LOCALE_LOADER} shortcuts={true} />);
clickShortcut(2);
const today = new Date();
const aWeekAgo = DateUtils.clone(today);
aWeekAgo.setDate(today.getDate() - 6);
const value = root.state("value");
assert.isTrue(DateUtils.isSameDay(aWeekAgo, value!));
});
it("custom shortcuts select the correct values", () => {
const date = new Date(2010, Months.JANUARY, 10);
const { clickShortcut, assertSelectedDays } = wrap(
<DatePicker3 {...LOCALE_LOADER} shortcuts={[{ label: "custom shortcut", date }]} />,
);
clickShortcut();
assertSelectedDays(date.getDate());
});
});
describe("time selection", () => {
const defaultValue = new Date(2012, 2, 5, 6, 5, 40);
it("setting timePrecision shows a TimePicker", () => {
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} />);
assert.isFalse(root.find(TimePicker).exists());
root.setProps({ timePrecision: "minute" });
assert.isTrue(root.find(TimePicker).exists());
});
it("setting timePickerProps shows a TimePicker", () => {
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} timePickerProps={{}} />);
assert.isTrue(root.find(TimePicker).exists());
});
it("onChange fired when the time is changed", () => {
const onChangeSpy = sinon.spy();
const { root } = wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
onChange={onChangeSpy}
timePickerProps={{ showArrowButtons: true }}
/>,
);
assert.isTrue(onChangeSpy.notCalled);
root.find(`.${Classes.TIMEPICKER_ARROW_BUTTON}.${Classes.TIMEPICKER_HOUR}`).first().simulate("click");
assert.isTrue(onChangeSpy.calledOnce);
const cbHour = onChangeSpy.firstCall.args[0].getHours();
assert.strictEqual(cbHour, defaultValue.getHours() + 1);
});
it("changing date does not change time", () => {
const onChangeSpy = sinon.spy();
wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
onChange={onChangeSpy}
timePrecision="minute"
/>,
)
.getDay(16)
.simulate("click");
assert.isTrue(DateUtils.isSameTime(onChangeSpy.firstCall.args[0] as Date, defaultValue));
});
it("changing time does not change date", () => {
const onChangeSpy = sinon.spy();
const { setTimeInput } = wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
onChange={onChangeSpy}
timePrecision="minute"
/>,
);
setTimeInput("minute", 45);
assert.isTrue(DateUtils.isSameDay(onChangeSpy.firstCall.args[0] as Date, defaultValue));
});
it("changing time without date uses today", () => {
const onChangeSpy = sinon.spy();
// no date set via props
const { setTimeInput } = wrap(
<DatePicker3 {...LOCALE_LOADER} onChange={onChangeSpy} timePrecision="minute" />,
);
setTimeInput("minute", 45);
assert.isTrue(DateUtils.isSameDay(onChangeSpy.firstCall.args[0] as Date, new Date()));
});
it("clicking a shortcut with includeTime=true changes time", () => {
const onChangeSpy = sinon.spy();
const date = DateUtils.clone(defaultValue);
date.setHours(date.getHours() - 2);
const shortcuts: DatePickerShortcut[] = [
{
date,
includeTime: true,
label: "shortcut with time",
},
];
const { clickShortcut } = wrap(
<DatePicker3
{...LOCALE_LOADER}
defaultValue={defaultValue}
onChange={onChangeSpy}
timePrecision="minute"
shortcuts={shortcuts}
/>,
);
clickShortcut();
assert.equal(onChangeSpy.firstCall.args[0] as Date, date);
});
});
describe("clearing a selection", () => {
it("onChange correctly passes a Date and never null when canClearSelection is false", () => {
const onChange = sinon.spy();
const { getDay } = wrap(<DatePicker3 {...LOCALE_LOADER} canClearSelection={false} onChange={onChange} />);
getDay().simulate("click");
assert.isNotNull(onChange.firstCall.args[0]);
getDay().simulate("click");
assert.isNotNull(onChange.secondCall.args[0]);
});
it("onChange correctly passes a Date or null when canClearSelection is true", () => {
const onChange = sinon.spy();
const { getDay } = wrap(<DatePicker3 {...LOCALE_LOADER} canClearSelection={true} onChange={onChange} />);
getDay().simulate("click");
assert.isNotNull(onChange.firstCall.args[0]);
getDay().simulate("click");
assert.isNull(onChange.secondCall.args[0]);
});
it("Clear button disabled when canClearSelection is false", () => {
const { getClearButton } = wrap(
<DatePicker3 {...LOCALE_LOADER} canClearSelection={false} showActionsBar={true} />,
);
assert.isTrue(getClearButton().props().disabled);
});
it("Clear button enabled when canClearSelection is true", () => {
const { getClearButton } = wrap(
<DatePicker3 {...LOCALE_LOADER} canClearSelection={true} showActionsBar={true} />,
);
assert.isFalse(getClearButton().props().disabled);
});
it("selects the current day when Today is clicked", () => {
const { root } = wrap(<DatePicker3 {...LOCALE_LOADER} showActionsBar={true} />);
root.find({ className: Classes.DATEPICKER_FOOTER }).find(Button).first().simulate("click");
const today = new Date();
const value = root.state("value");
assert.isNotNull(value);
assert.equal(value!.getDate(), today.getDate());
assert.equal(value!.getMonth(), today.getMonth());
assert.equal(value!.getFullYear(), today.getFullYear());
});
it("clears the value when Clear is clicked", () => {
const { getDay, root } = wrap(<DatePicker3 {...LOCALE_LOADER} showActionsBar={true} />);
getDay().simulate("click");
root.find({ className: Classes.DATEPICKER_FOOTER }).find(Button).last().simulate("click");
assert.isNull(root.state("value"));
});
});
describe("localization", () => {
it("accept a statically-loaded date-fns locale and doesn't try to load it again", () => {
const stub = sinon.stub();
stub.callsFake(loadDateFnsLocaleFake);
wrap(<DatePicker3 dateFnsLocaleLoader={stub} locale={enUSLocale} />);
assert.isTrue(stub.notCalled, "Expected locale loader not to be called");
});
});
function wrap(datepicker: React.JSX.Element) {
const wrapper = mount<DatePicker3Props, DatePicker3State>(datepicker, { attachTo: testsContainerElement });
datePicker3Wrapper = wrapper;
return {
/** Asserts that the given days are selected. No arguments asserts that selection is empty. */
assertSelectedDays: (...days: number[]) =>
assert.sameMembers(
wrapper
.find(`.${Classes.DATEPICKER3_DAY_SELECTED}`)
.hostNodes()
.map(d => +d.text()),
days,
),
clickNextMonth: () => wrapper.find(`.${Classes.DATEPICKER3_NAV_BUTTON_NEXT}`).hostNodes().simulate("click"),
clickPreviousMonth: () =>
wrapper.find(`.${Classes.DATEPICKER3_NAV_BUTTON_PREVIOUS}`).hostNodes().simulate("click"),
clickShortcut: (index = 0) => {
wrapper.find(`.${Classes.DATERANGEPICKER_SHORTCUTS}`).hostNodes().find("a").at(index).simulate("click");
},
getClearButton: () => wrapper.find(`.${Classes.DATEPICKER_FOOTER}`).find(Button).last(),
getDay: (dayNumber = 1) =>
wrapper
.find(`.${Classes.DATEPICKER3_DAY}`)
.filterWhere(day => day.text() === "" + dayNumber && !day.hasClass(Classes.DATEPICKER3_DAY_OUTSIDE))
.hostNodes(),
getTodayButton: () => wrapper.find(`.${Classes.DATEPICKER_FOOTER}`).find(Button).first(),
months: wrapper.find(HTMLSelect).filter(`.${Classes.DATEPICKER_MONTH_SELECT}`).find("select"),
root: wrapper,
setTimeInput: (precision: TimePrecision | "hour", value: number) =>
wrapper.find(`.${Classes.TIMEPICKER}-${precision}`).simulate("blur", { target: { value } }),
years: wrapper.find(HTMLSelect).filter(`.${Classes.DATEPICKER_YEAR_SELECT}`).find("select"),
};
}
});
``` | /content/code_sandbox/packages/datetime2/test/components/datePicker3Tests.tsx | xml | 2016-10-25T21:17:50 | 2024-08-16T15:14:48 | blueprint | palantir/blueprint | 20,593 | 7,992 |
```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 `dnanmskmax`.
*/
interface Routine {
/**
* Computes the maximum value of a double-precision floating-point strided array according to a mask, ignoring `NaN` values.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param mask - mask array
* @param strideMask - `mask` stride length
* @returns maximum value
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var Uint8Array = require( '@stdlib/array/uint8' );
*
* var x = new Float64Array( [ 1.0, -2.0, 4.0, 2.0, NaN ] );
* var mask = new Uint8Array( [ 0, 0, 1, 0, 0 ] );
*
* var v = dnanmskmax( x.length, x, 1, mask, 1 );
* // returns 2.0
*/
( N: number, x: Float64Array, strideX: number, mask: Uint8Array, strideMask: number ): number;
/**
* Computes the maximum value of a double-precision floating-point strided array according to a mask, ignoring `NaN` values and using alternative indexing semantics.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param offsetX - `x` starting index
* @param mask - mask array
* @param strideMask - `mask` stride length
* @param offsetMask - `mask` starting index
* @returns maximum value
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var Uint8Array = require( '@stdlib/array/uint8' );
*
* var x = new Float64Array( [ 1.0, -2.0, 4.0, 2.0, NaN ] );
* var mask = new Uint8Array( [ 0, 0, 1, 0, 0 ] );
*
* var v = dnanmskmax.ndarray( x.length, x, 1, 0, mask, 1, 0 );
* // returns 2.0
*/
ndarray( N: number, x: Float64Array, strideX: number, offsetX: number, mask: Uint8Array, strideMask: number, offsetMask: number ): number;
}
/**
* Computes the maximum value of a double-precision floating-point strided array according to a mask, ignoring `NaN` values.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param mask - mask array
* @param strideMask - `mask` stride length
* @returns maximum value
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var Uint8Array = require( '@stdlib/array/uint8' );
*
* var x = new Float64Array( [ 1.0, -2.0, 4.0, 2.0, NaN ] );
* var mask = new Uint8Array( [ 0, 0, 1, 0, 0 ] );
*
* var v = dnanmskmax( x.length, x, 1, mask, 1 );
* // returns 2.0
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var Uint8Array = require( '@stdlib/array/uint8' );
*
* var x = new Float64Array( [ 1.0, -2.0, 4.0, 2.0, NaN ] );
* var mask = new Uint8Array( [ 0, 0, 1, 0, 0 ] );
*
* var v = dnanmskmax.ndarray( x.length, x, 1, 0, mask, 1, 0 );
* // returns 2.0
*/
declare var dnanmskmax: Routine;
// EXPORTS //
export = dnanmskmax;
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/dnanmskmax/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 1,023 |
```xml
import React from 'react';
import { Text, View, StyleSheet, SectionList, Platform } from 'react-native';
import {
createStackNavigator,
StackScreenProps,
} from '@react-navigation/stack';
import { NavigationContainer, ParamListBase } from '@react-navigation/native';
import {
GestureHandlerRootView,
RectButton,
} from 'react-native-gesture-handler';
import Draggable from './basic/draggable';
import PinchableBox from './recipes/scaleAndRotate';
import Tap from './basic/tap';
import LongPressExample from './basic/longPress';
import ManualExample from './basic/manual';
import HoverExample from './basic/hover';
interface Example {
name: string;
component: React.ComponentType;
}
interface ExamplesSection {
sectionTitle: string;
data: Example[];
}
const EXAMPLES: ExamplesSection[] = [
{
sectionTitle: 'Examples',
data: [
{ name: 'Draggable', component: Draggable },
{ name: 'Pinch & rotate', component: PinchableBox },
{ name: 'Tap', component: Tap },
{ name: 'LongPress', component: LongPressExample },
{ name: 'Manual', component: ManualExample },
{ name: 'Hover', component: HoverExample },
],
},
];
type RootStackParamList = {
Home: undefined;
} & {
[Screen: string]: undefined;
};
const Stack = createStackNavigator<RootStackParamList>();
export default function App() {
return (
<GestureHandlerRootView style={styles.root}>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
options={{ title: ' Gesture Handler Demo' }}
component={MainScreen}
/>
{EXAMPLES.flatMap(({ data }) => data).flatMap(
({ name, component }) => (
<Stack.Screen
key={name}
name={name}
getComponent={() => component}
options={{ title: name }}
/>
)
)}
</Stack.Navigator>
</NavigationContainer>
</GestureHandlerRootView>
);
}
function MainScreen({ navigation }: StackScreenProps<ParamListBase>) {
return (
<SectionList
style={styles.list}
sections={EXAMPLES}
keyExtractor={(example) => example.name}
renderItem={({ item }) => (
<MainScreenItem
name={item.name}
onPressItem={(name) => navigation.navigate(name)}
/>
)}
renderSectionHeader={({ section: { sectionTitle } }) => (
<Text style={styles.sectionTitle}>{sectionTitle}</Text>
)}
ItemSeparatorComponent={() => <View style={styles.separator} />}
/>
);
}
interface MainScreenItemProps {
name: string;
onPressItem: (name: string) => void;
}
function MainScreenItem({ name, onPressItem }: MainScreenItemProps) {
return (
<RectButton style={[styles.button]} onPress={() => onPressItem(name)}>
<Text style={styles.text}>{name}</Text>
</RectButton>
);
}
const styles = StyleSheet.create({
root: {
flex: 1,
},
sectionTitle: {
...Platform.select({
ios: {
fontSize: 17,
fontWeight: '500',
},
android: {
fontSize: 19,
fontFamily: 'sans-serif-medium',
},
}),
paddingTop: 10,
paddingBottom: 5,
paddingLeft: 10,
backgroundColor: '#efefef',
color: 'black',
},
separator: {
height: 2,
},
button: {
flex: 1,
height: 50,
padding: 10,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#fff',
},
text: {
color: 'black',
},
});
``` | /content/code_sandbox/MacOSExample/src/App.tsx | xml | 2016-10-27T08:31:38 | 2024-08-16T12:03:40 | react-native-gesture-handler | software-mansion/react-native-gesture-handler | 5,989 | 821 |
```xml
import { defineConfig } from 'dumi';
import { repository, version } from './package.json';
export default defineConfig({
locales: [
{ id: 'zh', name: '' },
{ id: 'en', name: 'English' },
],
themeConfig: {
title: 'F2',
description: 'The Grammar of Graphics in JavaScript',
siteUrl: 'path_to_url
defaultLanguage: 'zh',
isAntVSite: false,
githubUrl: repository.url, // GitHub
footerTheme: 'light', //
showSearch: true, //
showGithubCorner: true, // GitHub icon
showGithubStars: true, // GitHub star
showAntVProductsCard: true, // AntV
showLanguageSwitcher: true, //
showWxQrcode: true, //
showChartResize: true, // demo
showAPIDoc: true, // demo API
versions: {
[version]: 'path_to_url
'4.x': 'path_to_url
'3.x': 'path_to_url
},
navs: [
{
slug: 'docs/tutorial/getting-started',
title: {
zh: '',
en: 'Manual',
},
},
{
slug: 'docs/api',
title: {
zh: 'API',
en: 'Component Documentation',
},
},
{
slug: 'examples',
title: {
zh: '',
en: 'Examples',
},
},
],
docs: [
{
slug: 'api/chart',
title: {
zh: ' - Chart',
en: 'Chart',
},
order: 4,
},
{
slug: 'tutorial/framework',
title: {
zh: '/ - Framework',
en: 'Framework',
},
order: 70,
},
{
slug: 'tutorial/advanced',
title: {
zh: ' - Advanced',
en: 'Advanced',
},
order: 80,
},
{
slug: 'tutorial/question',
title: {
zh: ' - Question',
en: 'Question',
},
order: 90,
},
],
cases: [
{
logo: 'path_to_url
title: {
zh: '',
en: 'Ant Fortune',
},
description: {
zh: ' app ',
en: 'It has been widely used in various financial business scenarios such as funds, fixed-term, gold, and stocks, and supports many visualization scenarios on the Ant Fortune app. At the same time, through in-depth analysis of users visualization demands, a number of financial-oriented visualization solutions have been developed',
},
link: 'path_to_url
image:
'path_to_url
},
{
logo: 'path_to_url
title: {
zh: '',
en: 'Alipay',
},
description: {
zh: '',
en: 'Covering business scenarios such as ant membership, Alipay monthly bills, personal total assets, etc., helping you to understand your consumption data faster and better through visualization',
},
image: 'path_to_url
},
{
logo: 'path_to_url
title: {
zh: '',
en: 'Beacon Pro',
},
description: {
zh: '',
en: 'Beacon Professional Edition, providing valuable data for film and television people. Integrate Alibabas massive user data, provide comprehensive professional data, make the industry more open and transparent, and improve the efficiency of industry decision-making',
},
image: 'path_to_url
},
],
detail: {
engine: {
zh: 'F2',
en: 'F2',
},
title: {
zh: 'F2',
en: 'F2Mobile visualization engine',
},
description: {
zh: 'F2 H5 Node, ',
en: 'F2 is an out-of-the-box visualization engine focused on the mobile terminal, oriented to conventional statistical charts, perfectly supporting the H5 environment and compatible with multiple environments (Node, applet), complete graphics grammar theory, to meet your various visualization needs , professional mobile design guidelines to bring you the best mobile graphics experience',
},
image:
'path_to_url
imageStyle: {
marginLeft: '80px',
marginTop: '30px',
transform: 'scale(1.4)',
},
buttons: [
{
text: {
zh: '',
en: 'Getting Started',
},
link: `/tutorial/getting-started`,
},
{
text: {
zh: '',
en: 'Examples',
},
link: `/examples`,
type: 'primary',
},
],
},
features: [
{
icon: 'path_to_url
title: {
zh: '',
en: 'focus on mobile, experience elegance',
},
description: {
zh: '',
en: 'provide users with best practices for mobile charts around design, performance, and heterogeneous environments',
},
},
{
icon: 'path_to_url
title: {
zh: '',
en: 'rich charts and complete components',
},
description: {
zh: '50+',
en: 'based on graphics syntax, various charts (50+) can be flexibly constructed, with complete components, covering various scenarios',
},
},
{
icon: 'path_to_url
title: {
zh: '',
en: 'flexible expansion, unlimited creativity',
},
description: {
zh: '',
en: 'plug-in mechanism, graphics, animations, and interactions can be flexibly expanded and used more freely',
},
},
],
companies: [
{
name: '',
img: 'path_to_url
},
{
name: '',
img: 'path_to_url
},
{
name: '',
img: 'path_to_url
},
{
name: '',
img: 'path_to_url
},
{
name: '',
img: 'path_to_url
},
{
name: '',
img: 'path_to_url
},
{
name: '',
img: 'path_to_url
},
{
name: '',
img: 'path_to_url
},
],
examples: [
{
slug: 'creative',
icon: 'gallery',
title: {
zh: '',
en: 'Creative Charts',
},
},
{
slug: 'line',
icon: 'line',
title: {
zh: '',
en: 'Line Charts',
},
},
{
slug: 'area',
icon: 'area',
title: {
zh: '',
en: 'Area Charts',
},
},
{
slug: 'column',
icon: 'column',
title: {
zh: '',
en: 'Column Charts',
},
},
{
slug: 'bar',
icon: 'bar',
title: {
zh: '',
en: 'Bar Charts',
},
},
{
slug: 'pie',
icon: 'pie',
title: {
zh: '',
en: 'Pie Charts',
},
},
{
slug: 'radar',
icon: 'radar',
title: {
zh: '',
en: 'Radar Charts',
},
},
{
slug: 'point',
icon: 'point',
title: {
zh: '',
en: 'Point Charts',
},
},
{
slug: 'funnel',
icon: 'funnel',
title: {
zh: '',
en: 'Funnel Charts',
},
},
{
slug: 'relation',
icon: 'relation',
title: {
zh: '',
en: 'Relation Charts',
},
},
{
slug: 'candlestick',
icon: 'candlestick',
title: {
zh: 'K ',
en: 'Candlestick Charts',
},
},
{
slug: 'component',
icon: 'component',
title: {
zh: '',
en: 'Chart Components',
},
},
{
slug: 'other',
icon: 'other',
title: {
zh: '',
en: 'Other Chart',
},
},
],
playground: {
playgroundDidMount: 'window.initPlayground()',
dependencies: {
'@antv/f2': '5.x',
},
devDependencies: {
typescript: 'latest',
},
container: `
<div class="mobile-container">
<div class="mobile-header"></div>
<div class="mobile-content">
<canvas id="container" style="display: block; width: 375px; height: 260px;" />
</div>
</div>
`,
json: {
// riddle
gravity: {
gmap: { '@antv/f2': '@antv/f2/dist/index.min.js' },
},
},
},
docsearchOptions: {
apiKey: '349619374e9488b3f000714317d67381',
indexName: 'antv_f2',
},
},
runtimePublicPath: {},
headScripts: [
'path_to_url~locale.en',
],
legacy: {},
});
``` | /content/code_sandbox/site/.dumirc.ts | xml | 2016-08-29T06:26:23 | 2024-08-16T15:50:14 | F2 | antvis/F2 | 7,877 | 2,061 |
```xml
import { PluginBase } from '@electron-forge/plugin-base';
import {
ForgeListrTaskDefinition,
ForgeMutatingHookFn,
ForgeMutatingHookSignatures,
ForgeSimpleHookFn,
ForgeSimpleHookSignatures,
IForgePlugin,
IForgePluginInterface,
ResolvedForgeConfig,
StartResult,
} from '@electron-forge/shared-types';
import { autoTrace } from '@electron-forge/tracer';
import chalk from 'chalk';
import debug from 'debug';
import { StartOptions } from '../api';
import requireSearch from './require-search';
const d = debug('electron-forge:plugins');
function isForgePlugin(plugin: IForgePlugin | unknown): plugin is IForgePlugin {
return (plugin as IForgePlugin).__isElectronForgePlugin;
}
export default class PluginInterface implements IForgePluginInterface {
private plugins: IForgePlugin[];
private config: ResolvedForgeConfig;
constructor(dir: string, forgeConfig: ResolvedForgeConfig) {
this.plugins = forgeConfig.plugins.map((plugin) => {
if (isForgePlugin(plugin)) {
return plugin;
}
if (typeof plugin === 'object' && 'name' in plugin && 'config' in plugin) {
const { name: pluginName, config: opts } = plugin;
if (typeof pluginName !== 'string') {
throw new Error(`Expected plugin[0] to be a string but found ${pluginName}`);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const Plugin = requireSearch<any>(dir, [pluginName]);
if (!Plugin) {
throw new Error(`Could not find module with name: ${pluginName}. Make sure it's listed in the devDependencies of your package.json`);
}
return new Plugin(opts);
}
throw new Error(`Expected plugin to either be a plugin instance or a { name, config } object but found ${JSON.stringify(plugin)}`);
});
// TODO: fix hack
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.config = null as any;
Object.defineProperty(this, 'config', {
value: forgeConfig,
enumerable: false,
configurable: false,
writable: false,
});
for (const plugin of this.plugins) {
plugin.init(dir, forgeConfig);
}
this.triggerHook = this.triggerHook.bind(this);
this.overrideStartLogic = this.overrideStartLogic.bind(this);
}
async triggerHook<Hook extends keyof ForgeSimpleHookSignatures>(hookName: Hook, hookArgs: ForgeSimpleHookSignatures[Hook]): Promise<void> {
for (const plugin of this.plugins) {
if (typeof plugin.getHooks === 'function') {
let hooks = plugin.getHooks()[hookName] as ForgeSimpleHookFn<Hook>[] | ForgeSimpleHookFn<Hook>;
if (hooks) {
if (typeof hooks === 'function') hooks = [hooks];
for (const hook of hooks) {
await hook(this.config, ...hookArgs);
}
}
}
}
}
async getHookListrTasks<Hook extends keyof ForgeSimpleHookSignatures>(
childTrace: typeof autoTrace,
hookName: Hook,
hookArgs: ForgeSimpleHookSignatures[Hook]
): Promise<ForgeListrTaskDefinition[]> {
const tasks: ForgeListrTaskDefinition[] = [];
for (const plugin of this.plugins) {
if (typeof plugin.getHooks === 'function') {
let hooks = plugin.getHooks()[hookName] as ForgeSimpleHookFn<Hook>[] | ForgeSimpleHookFn<Hook>;
if (hooks) {
if (typeof hooks === 'function') hooks = [hooks];
for (const hook of hooks) {
tasks.push({
title: `${chalk.cyan(`[plugin-${plugin.name}]`)} ${(hook as any).__hookName || `Running ${chalk.yellow(hookName)} hook`}`,
task: childTrace(
{ name: 'forge-plugin-hook', category: '@electron-forge/hooks', extraDetails: { plugin: plugin.name, hook: hookName } },
async (_, __, task) => {
if ((hook as any).__hookName) {
// Also give it the task
return await (hook as any).call(task, this.config, ...(hookArgs as any[]));
} else {
await hook(this.config, ...hookArgs);
}
}
),
rendererOptions: {},
});
}
}
}
}
return tasks;
}
async triggerMutatingHook<Hook extends keyof ForgeMutatingHookSignatures>(
hookName: Hook,
...item: ForgeMutatingHookSignatures[Hook]
): Promise<ForgeMutatingHookSignatures[Hook][0]> {
let result: ForgeMutatingHookSignatures[Hook][0] = item[0];
for (const plugin of this.plugins) {
if (typeof plugin.getHooks === 'function') {
let hooks = plugin.getHooks()[hookName] as ForgeMutatingHookFn<Hook>[] | ForgeMutatingHookFn<Hook>;
if (hooks) {
if (typeof hooks === 'function') hooks = [hooks];
for (const hook of hooks) {
result = (await hook(this.config, ...item)) || result;
}
}
}
}
return result;
}
async overrideStartLogic(opts: StartOptions): Promise<StartResult> {
let newStartFn;
const claimed: string[] = [];
for (const plugin of this.plugins) {
if (typeof plugin.startLogic === 'function' && plugin.startLogic !== PluginBase.prototype.startLogic) {
claimed.push(plugin.name);
newStartFn = plugin.startLogic;
}
}
if (claimed.length > 1) {
throw new Error(`Multiple plugins tried to take control of the start command, please remove one of them\n --> ${claimed.join(', ')}`);
}
if (claimed.length === 1 && newStartFn) {
d(`plugin: "${claimed[0]}" has taken control of the start command`);
const result = await newStartFn(opts);
if (typeof result === 'object' && 'tasks' in result) {
result.tasks = result.tasks.map((task) => ({
...task,
title: `${chalk.cyan(`[plugin-${claimed[0]}]`)} ${task.title}`,
}));
}
return result;
}
return false;
}
}
``` | /content/code_sandbox/packages/api/core/src/util/plugin-interface.ts | xml | 2016-10-05T14:51:53 | 2024-08-15T20:08:12 | forge | electron/forge | 6,380 | 1,384 |
```xml
// Please don't have includes in here that aren't inside the DSL folder, or the d.ts/flow defs break
import type * as Types from "@gitbeaker/rest"
import { RepoMetaData } from "./RepoMetaData"
// getPlatformReviewDSLRepresentation
export interface GitLabJSONDSL {
/** Info about the repo */
metadata: RepoMetaData
/** Info about the merge request */
mr: Types.ExpandedMergeRequestSchema
/** All the individual commits in the merge request */
commits: Types.CommitSchema[]
/** Merge Request-level MR approvals Configuration */
approvals: Types.MergeRequestLevelMergeRequestApprovalSchema
}
// danger.gitlab
/** The GitLab metadata for your MR */
export interface GitLabDSL extends GitLabJSONDSL {
utils: {
fileContents(path: string, repoSlug?: string, ref?: string): Promise<string>
addLabels(...labels: string[]): Promise<boolean>
removeLabels(...labels: string[]): Promise<boolean>
}
api: InstanceType<typeof Types.Gitlab>
}
``` | /content/code_sandbox/source/dsl/GitLabDSL.ts | xml | 2016-08-20T12:57:06 | 2024-08-13T14:00:02 | danger-js | danger/danger-js | 5,229 | 217 |
```xml
import React from 'react';
type IconProps = React.SVGProps<SVGSVGElement>;
export declare const IcChevronUpFilled: (props: IconProps) => React.JSX.Element;
export {};
``` | /content/code_sandbox/packages/icons/lib/icChevronUpFilled.d.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 45 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="path_to_url"
xmlns:tools="path_to_url"
xmlns:app="path_to_url">
<data>
<import type="android.view.View" />
<variable
name="emailRequest"
type="com.eventyay.organizer.data.auth.model.EmailRequest"/>
<variable
name="buildConfig"
type="com.eventyay.organizer.BuildConfig" />
</data>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.eventyay.organizer.core.auth.login.LoginFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:padding="@dimen/spacing_normal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="@dimen/spacing_normal"
android:paddingLeft="@dimen/spacing_normal"
android:paddingRight="@dimen/spacing_normal"
android:paddingStart="@dimen/spacing_normal">
<TextView
android:textColor="@color/color_accent"
android:textSize="@dimen/text_size_extra_large"
android:layout_marginTop="@dimen/spacing_small"
android:layout_marginBottom="@dimen/spacing_small"
android:gravity="start"
android:layout_gravity="center_horizontal"
android:text="@string/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/spacing_small"
android:layout_marginBottom="@dimen/spacing_small"
android:text="@string/get_started_hint"/>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/email_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:paddingBottom="@dimen/spacing_normal"
android:paddingTop="@dimen/spacing_normal"
android:transitionName="@string/email">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="@+id/email_dropdown"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={ emailRequest.email }"
android:inputType="textEmailAddress"
android:imeOptions="actionNext"
app:validateType='@{"email"}'
app:go="@{() -> btnStart.performClick() }"
/>
</com.google.android.material.textfield.TextInputLayout>
<include
android:id="@+id/url"
layout="@layout/auth_url_container"
android:visibility="@{ buildConfig.DEBUG ? View.VISIBLE : View.GONE }"
app:action="@{ () -> btnStart.performClick() }" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:backgroundTint="@color/color_accent"
android:text="@string/get_started"
android:textAllCaps="true"
android:textColor="@android:color/white" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<FrameLayout
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<include layout="@layout/progressbar_layout" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
``` | /content/code_sandbox/app/src/main/res/layout/start_fragment.xml | xml | 2016-08-13T08:08:39 | 2024-08-06T13:58:48 | open-event-organizer-android | fossasia/open-event-organizer-android | 1,783 | 843 |
```xml
import React from "react"
import { currentUserAtom } from "@/modules/JotaiProiveder"
import { IUser } from "@/modules/auth/types"
import { useAtomValue } from "jotai"
import { MoreVertical } from "lucide-react"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { IAbsence, IAbsenceType } from "../../../types"
import AbcenseDelete from "../form/AbsenceDelete"
type Props = {
absence: IAbsence
}
const AbsenceRowAction = ({ absence }: Props) => {
const currentUser = useAtomValue(currentUserAtom)
const user = absence.user || ({} as IUser)
return (
<Popover>
<PopoverTrigger asChild={true}>
<button>
<MoreVertical size={16} />
</button>
</PopoverTrigger>
<PopoverContent className="w-40 p-1" align="end">
{currentUser?.isOwner || currentUser?._id === user._id ? (
<AbcenseDelete id={absence._id} />
) : null}
</PopoverContent>
</Popover>
)
}
export default AbsenceRowAction
``` | /content/code_sandbox/exm-web/modules/timeclock/component/absence/action/AbsenceRowAction.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 265 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<bean id="dataSource" class="org.flowable.common.engine.impl.test.ClosingDataSource">
<constructor-arg>
<bean class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg>
<bean class="com.zaxxer.hikari.HikariConfig">
<property name="minimumIdle" value="0" />
<property name="jdbcUrl" value="${jdbc.url:jdbc:h2:mem:flowable;DB_CLOSE_DELAY=1000}"/>
<property name="driverClassName" value="${jdbc.driver:org.h2.Driver}"/>
<property name="username" value="${jdbc.username:sa}"/>
<property name="password" value="${jdbc.password:}"/>
</bean>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
<bean id="processEngineConfiguration" class="org.flowable.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="dataSource" ref="dataSource"/>
<property name="engineLifecycleListeners">
<list>
<ref bean="dataSource"/>
</list>
</property>
<property name="databaseSchemaUpdate" value="true" />
<property name="activityBehaviorFactory">
<bean class="org.flowable.standalone.parsing.CustomActivityBehaviorFactory" />
</property>
</bean>
</beans>
``` | /content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/standalone/parsing/custom.activitybehaviorfactory.flowable.cfg.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 354 |
```xml
import net from 'net'
import type { Addresses, RestoreOriginalFunction } from './types'
/**
* Proxy the TCP connect method to determine if any network access is made during the build
*
* @param addresses An array to track the addresses that are accessed.
* @returns A function that restores the original connect method.
*/
export function tcpProxy(addresses: Addresses): RestoreOriginalFunction {
// net.Socket docs path_to_url#class-netsocket
const originalConnect = net.Socket.prototype.connect
// Override the connect method
net.Socket.prototype.connect = function (...args: any) {
// First, check if the first argument is an object and not null
if (typeof args[0] === 'object' && args[0] !== null) {
const options = args[0] as net.SocketConnectOpts
// check if the options has what we need
if (
'port' in options &&
options.port !== undefined &&
'host' in options &&
options.host !== undefined
) {
addresses.push({ addr: options.host, port: options.port.toString() })
}
}
return originalConnect.apply(this, args)
}
return () => {
// Restore the original connect method
net.Socket.prototype.connect = originalConnect
}
}
``` | /content/code_sandbox/packages/next/src/build/turborepo-access-trace/tcp.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 273 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:id="@+id/activity_save_as_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/activity_save_as_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/color_primary"
app:title="@string/save_as"
app:titleTextAppearance="@style/AppTheme.ActionBar.TitleTextStyle" />
<RelativeLayout
android:id="@+id/activity_save_as_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
``` | /content/code_sandbox/app/src/main/res/layout/activity_save_as.xml | xml | 2016-07-12T20:06:21 | 2024-08-16T13:08:21 | Simple-File-Manager | SimpleMobileTools/Simple-File-Manager | 1,490 | 202 |
```xml
<vector
xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:tint="?attr/colorControlNormal"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="@android:color/white"
android:pathData="M12,7c2.76,0 5,2.24 5,5 0,0.65 -0.13,1.26 -0.36,1.83l2.92,2.92c1.51,-1.26 2.7,-2.89 3.43,-4.75 -1.73,-4.39 -6,-7.5 -11,-7.5 -1.4,0 -2.74,0.25 -3.98,0.7l2.16,2.16C10.74,7.13 11.35,7 12,7zM2,4.27l2.28,2.28 0.46,0.46C3.08,8.3 1.78,10.02 1,12c1.73,4.39 6,7.5 11,7.5 1.55,0 3.03,-0.3 4.38,-0.84l0.42,0.42L19.73,22 21,20.73 3.27,3 2,4.27zM7.53,9.8l1.55,1.55c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.66 1.34,3 3,3 0.22,0 0.44,-0.03 0.65,-0.08l1.55,1.55c-0.67,0.33 -1.41,0.53 -2.2,0.53 -2.76,0 -5,-2.24 -5,-5 0,-0.79 0.2,-1.53 0.53,-2.2zM11.84,9.02l3.15,3.15 0.02,-0.16c0,-1.66 -1.34,-3 -3,-3l-0.17,0.01z"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/vd_trimclip_eye_masked.xml | xml | 2016-11-04T14:23:35 | 2024-08-12T07:50:44 | adp-delightful-details | alexjlockwood/adp-delightful-details | 1,070 | 537 |
```xml
export function mapToArray<K, V>(map: Map<K, V>) {
return [...map.values()];
}
export function compareSemanticVersion(left: string, right: string) {
const leftSplit = left.split('.').map((val) => parseInt(val, 10));
const rightSplit = right.split('.').map((val) => parseInt(val, 10));
while (leftSplit.length < rightSplit.length) {
leftSplit.push(0);
}
while (rightSplit.length < leftSplit.length) {
rightSplit.push(0);
}
for (let x = 0; x < leftSplit.length; x++) {
if (leftSplit[x] === rightSplit[x]) {
continue; // eslint-disable-line no-continue
}
if (leftSplit[x] > rightSplit[x]) {
return 1;
}
if (leftSplit[x] < rightSplit[x]) {
return -1;
}
}
return 0;
}
``` | /content/code_sandbox/src/extension/utils/helpers.ts | xml | 2016-01-03T05:38:10 | 2024-08-13T16:08:09 | toolkit-for-ynab | toolkit-for-ynab/toolkit-for-ynab | 1,418 | 212 |
```xml
import { Component, OnInit } from '@angular/core';
import { FilterMatchMode, FilterService, SelectItem } from 'primeng/api';
import { Car } from '@domain/car';
import { Code } from '@domain/code';
import { CarService } from '@service/carservice';
@Component({
selector: 'filter-service-table-integration-demo',
template: `
<app-docsectiontext>
<p>A custom equals filter that checks for exact case sensitive value is registered and defined as a match mode of a column filter.</p>
</app-docsectiontext>
<div class="card">
<p-table #dt [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" responsiveLayout="scroll">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">{{col.header}}</th>
</tr>
<tr>
<th *ngFor="let col of columns">
<p-columnFilter type="text" [field]="col.field" [matchModeOptions]="matchModeOptions" [matchMode]="'custom-equals'" />
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">{{rowData[col.field]}}</td>
</tr>
</ng-template>
</p-table>
</div>
<app-code [code]="code" selector="filter-service-table-integration-demo" [extFiles]="extFiles"></app-code>
`,
providers: [FilterService]
})
export class TableIntegrationDoc implements OnInit {
cars: Car[];
cols: any[];
matchModeOptions: SelectItem[];
constructor(private carService: CarService, private filterService: FilterService) {}
ngOnInit() {
const customFilterName = 'custom-equals';
this.filterService.register(customFilterName, (value, filter): boolean => {
if (filter === undefined || filter === null || filter.trim() === '') {
return true;
}
if (value === undefined || value === null) {
return false;
}
return value.toString() === filter.toString();
});
this.cols = [
{ field: 'year', header: 'Year' },
{ field: 'brand', header: 'Brand' },
{ field: 'color', header: 'Color' },
{ field: 'vin', header: 'Vin' }
];
this.matchModeOptions = [
{ label: 'Custom Equals', value: customFilterName },
{ label: 'Starts With', value: FilterMatchMode.STARTS_WITH },
{ label: 'Contains', value: FilterMatchMode.CONTAINS }
];
this.carService.getCarsMedium().then((cars) => (this.cars = cars));
}
code: Code = {
basic: `<p-table #dt [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" responsiveLayout="scroll">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
<tr>
<th *ngFor="let col of columns">
<p-columnFilter
type="text"
[field]="col.field"
[matchModeOptions]="matchModeOptions"
[matchMode]="'custom-equals'" />
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>`,
html: `<div class="card">
<p-table #dt [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" responsiveLayout="scroll">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">{{col.header}}</th>
</tr>
<tr>
<th *ngFor="let col of columns">
<p-columnFilter
type="text"
[field]="col.field"
[matchModeOptions]="matchModeOptions"
[matchMode]="'custom-equals'" />
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">{{rowData[col.field]}}</td>
</tr>
</ng-template>
</p-table>
</div>`,
typescript: `import { Component, OnInit } from '@angular/core';
import { FilterMatchMode, FilterService, SelectItem } from 'primeng/api';
import { Car } from '@domain/car';
import { CarService } from '@service/carservice';
import { TableModule } from 'primeng/table';
import { CommonModule } from '@angular/common';
@Component({
selector: 'filter-service-table-integration-demo',
templateUrl: './filter-service-table-integration-demo.html',
standalone: true,
imports: [TableModule, CommonModule],
providers: [FilterService, CarService]
})
export class FilterServiceTableIntegrationDemo implements OnInit {
cars: Car[];
cols: any[];
matchModeOptions: SelectItem[];
constructor(private carService: CarService, private filterService: FilterService) {}
ngOnInit() {
const customFilterName = 'custom-equals';
this.filterService.register(customFilterName, (value, filter): boolean => {
if (filter === undefined || filter === null || filter.trim() === '') {
return true;
}
if (value === undefined || value === null) {
return false;
}
return value.toString() === filter.toString();
});
this.cols = [
{ field: 'year', header: 'Year' },
{ field: 'brand', header: 'Brand' },
{ field: 'color', header: 'Color' },
{ field: 'vin', header: 'Vin' }
];
this.matchModeOptions = [
{ label: 'Custom Equals', value: customFilterName },
{ label: 'Starts With', value: FilterMatchMode.STARTS_WITH },
{ label: 'Contains', value: FilterMatchMode.CONTAINS }
];
this.carService.getCarsMedium().then((cars) => (this.cars = cars));
}
}`,
service: ['CarService']
};
extFiles = [
{
path: 'src/domain/product.ts',
content: `
export interface Product {
id?: string;
code?: string;
name?: string;
description?: string;
price?: number;
quantity?: number;
inventoryStatus?: string;
category?: string;
image?: string;
rating?: number;
}`
},
{
path: 'src/domain/car.ts',
content: `
export interface Car {
id?;
vin?;
year?;
brand?;
color?;
price?;
saleDate?;
}`
}
];
}
``` | /content/code_sandbox/src/app/showcase/doc/filterservice/tableintegrationdoc.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 1,625 |
```xml
import { Construct } from 'constructs'
import { App, RedirectStatus } from '@aws-cdk/aws-amplify-alpha'
import { CfnOutput } from 'aws-cdk-lib'
import { Asset } from 'aws-cdk-lib/aws-s3-assets'
import { execSync } from 'node:child_process'
import { getEnvironmentConfig, getEnvironmentName } from '../environment-config'
import { getMissingEnvVars, getMissingEnvVarsMessage } from '../../../common/required-env-vars'
import { configDotenv } from 'dotenv'
import path from 'node:path'
export default class WebApp extends Construct {
readonly amplifyApp: App
readonly amplifyUrl: string
constructor(scope: Construct, id: string) {
super(scope, id)
const envName = getEnvironmentName(this.node)
const amplifyApp = new App(this, 'AmplifyApp', {
appName: `Todo ${envName}`,
customRules: [
{
source: '/getting-started',
target: '/getting-started',
status: RedirectStatus.REWRITE,
},
{
source: '/account',
target: '/account',
status: RedirectStatus.REWRITE,
},
{
source: '/todo-lists',
target: '/todo-lists',
status: RedirectStatus.REWRITE,
},
{
source: '/todo-lists/<listId>',
target: '/todo-lists/[listId]',
status: RedirectStatus.REWRITE,
},
{
source: '/users',
target: '/users',
status: RedirectStatus.REWRITE,
},
{
source: '/users/<userId>',
target: '/users/[userId]',
status: RedirectStatus.REWRITE,
},
{
source: '</^[^.]+$|\\.(?!(css|gif|ico|jpg|webp|js|png|txt|svg|woff|woff2|ttf|map|json)$)([^.]+$)/>',
target: '/index',
status: RedirectStatus.REWRITE,
},
],
})
const packagedWebAppAsset = this.packageWebApp()
const branch = amplifyApp.addBranch(envName, {
asset: packagedWebAppAsset,
autoBuild: false,
})
const environmentConfig = getEnvironmentConfig(this.node)
const { domainName } = environmentConfig.ui || {}
if (domainName) {
const domain = amplifyApp.addDomain(domainName)
domain.mapRoot(branch)
}
this.amplifyApp = amplifyApp
this.amplifyUrl = `path_to_url{envName}.${amplifyApp.defaultDomain}`
new CfnOutput(this, 'AmplifyUrl', { key: 'AmplifyUrl', value: this.amplifyUrl })
}
packageWebApp() {
const skipDeployWebApp = this.node.tryGetContext('skipDeployWebApp')
if (skipDeployWebApp) {
console.info('Skipping WebApp deploy')
// This results in the nested stack that Amplify creates for deploying assets being deleted, and
// needs to be recreated again the next time cdk deploy is run with deploy web app, resulting in
// a longer stack update time.
return
}
const envName = getEnvironmentName(this.node)
const uiPackagePath = path.resolve(import.meta.dirname, '../../../ui')
const uiDotEnvPath = path.join(uiPackagePath, `.env/.env.${envName}`)
configDotenv({ path: uiDotEnvPath })
const REQUIRED_ENV_VARS = [
'NEXT_PUBLIC_ApiGatewayUrl',
'NEXT_PUBLIC_LambdaFunctionUrl',
'NEXT_PUBLIC_CloudFrontDistributionUrl',
'NEXT_PUBLIC_ApiEndpoint',
'NEXT_PUBLIC_CognitoUserPoolId',
'NEXT_PUBLIC_CognitoUserPoolClientId',
'NEXT_PUBLIC_Region',
]
const missingEnvVars = getMissingEnvVars(REQUIRED_ENV_VARS)
if (missingEnvVars.length) {
console.info(getMissingEnvVarsMessage(missingEnvVars))
console.info(
`Skipping web app deploy due to missing environment variables. If you're missing the packages/ui/.env/.env.${envName} file, try running \`npm run copy-outputs-to-dotenv:dev\` to copy values from cdk-outputs.${envName} to the .env file. If the cdk-outputs file also doesn't exist, first run \`npm run pull-stack-outputs:${envName}\`. Then, run \`npm run deploy:${envName}\` again to deploy the web app.`
)
return
}
execSync(`npm run build:${envName}`, {
cwd: uiPackagePath,
env: {
...process.env,
},
stdio: 'inherit',
})
// TODO: Consider Asset bundling path_to_url#asset-bundling
return new Asset(this, 'PackagedAsset', {
path: path.join(uiPackagePath, 'out'),
})
}
}
``` | /content/code_sandbox/examples/lambda-function-url/packages/cdk/lib/constructs/WebApp.ts | xml | 2016-09-13T23:29:07 | 2024-08-15T09:52:47 | serverless-express | CodeGenieApp/serverless-express | 5,117 | 1,060 |
```xml
import type { IFlexProps } from './../../primitives/Flex/types';
export type IWrapProps = IFlexProps & {
space?: number;
};
``` | /content/code_sandbox/src/components/composites/Wrap/types.ts | xml | 2016-04-15T11:37:23 | 2024-08-14T16:16:44 | NativeBase | GeekyAnts/NativeBase | 20,132 | 33 |
```xml
export * from 'rxjs-compat/operator/shareReplay';
``` | /content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/operator/shareReplay.d.ts | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 13 |
```xml
import { Chart } from '@antv/g2';
const data = [
{ name: 'London', : 'Jan.', : 18.9 },
{ name: 'London', : 'Feb.', : 28.8 },
{ name: 'London', : 'Mar.', : 39.3 },
{ name: 'London', : 'Apr.', : 81.4 },
{ name: 'London', : 'May', : 47 },
{ name: 'London', : 'Jun.', : 20.3 },
{ name: 'London', : 'Jul.', : 24 },
{ name: 'London', : 'Aug.', : 35.6 },
{ name: 'Berlin', : 'Jan.', : 12.4 },
{ name: 'Berlin', : 'Feb.', : 23.2 },
{ name: 'Berlin', : 'Mar.', : 34.5 },
{ name: 'Berlin', : 'Apr.', : 99.7 },
{ name: 'Berlin', : 'May', : 52.6 },
{ name: 'Berlin', : 'Jun.', : 35.5 },
{ name: 'Berlin', : 'Jul.', : 37.4 },
{ name: 'Berlin', : 'Aug.', : 42.4 },
];
const chart = new Chart({
container: 'container',
autoFit: true,
});
chart
.interval()
.data(data)
.encode('x', '')
.encode('y', '')
.encode('color', 'name')
.encode('key', (d) => d['name'] + d[''])
.interaction({
legendFilter: false,
elementPointMove: {
precision: 3,
selection: [5],
},
})
.transform({ type: 'stackY' });
chart.render();
``` | /content/code_sandbox/site/examples/interaction/data/demo/column-element-point-move.ts | xml | 2016-05-26T09:21:04 | 2024-08-15T16:11:17 | G2 | antvis/G2 | 12,060 | 402 |
```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
/* eslint-disable max-lines */
import int32ToUint32 = require( '@stdlib/number/int32/base/to-uint32' );
/**
* Interface describing the `base` namespace.
*/
interface Namespace {
/**
* Converts a signed 32-bit integer to an unsigned 32-bit integer.
*
* @param x - signed 32-bit integer
* @returns unsigned 32-bit integer
*
* @example
* var float64ToInt32 = require( '@stdlib/number/float64/base/to-int32' );
* var y = ns.int32ToUint32( float64ToInt32( -1.0 ) );
* // returns 4294967295
*
* @example
* var float64ToInt32 = require( '@stdlib/number/float64/base/to-int32' );
* var y = ns.int32ToUint32( float64ToInt32( 3 ) );
* // returns 3
*/
int32ToUint32: typeof int32ToUint32;
}
/**
* Base utilities for signed 32-bit integers.
*/
declare var ns: Namespace;
// EXPORTS //
export = ns;
``` | /content/code_sandbox/lib/node_modules/@stdlib/number/int32/base/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 307 |
```xml
<clickhouse>
<interserver_http_port>9010</interserver_http_port>
</clickhouse>
``` | /content/code_sandbox/tests/integration/test_https_replication/configs/no_ssl_conf.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 24 |
```xml
import type { ExtractedProp } from 'storybook/internal/docs-tools';
import {
type ArgTypesExtractor,
convert,
extractComponentProps,
hasDocgen,
} from 'storybook/internal/docs-tools';
import type { SBType, StrictArgTypes, StrictInputType } from 'storybook/internal/types';
import type { VueDocgenInfo, VueDocgenInfoEntry, VueDocgenPlugin } from '@storybook/vue3-vite';
type PropertyMetaSchema = VueDocgenInfoEntry<'vue-component-meta', 'props'>['schema'];
// "exposed" is used by the vue-component-meta plugin while "expose" is used by vue-docgen-api
const ARG_TYPE_SECTIONS = ['props', 'events', 'slots', 'exposed', 'expose'] as const;
export const extractArgTypes: ArgTypesExtractor = (component): StrictArgTypes | null => {
if (!hasDocgen<VueDocgenInfo<VueDocgenPlugin>>(component)) {
return null;
}
const usedDocgenPlugin: VueDocgenPlugin =
// eslint-disable-next-line no-underscore-dangle
'exposed' in component.__docgenInfo ? 'vue-component-meta' : 'vue-docgen-api';
const argTypes: StrictArgTypes = {};
ARG_TYPE_SECTIONS.forEach((section) => {
const props = extractComponentProps(component, section);
props.forEach((extractedProp) => {
let argType: StrictInputType | undefined;
// use the corresponding extractor whether vue-docgen-api or vue-component-meta
// was used for the docinfo
if (usedDocgenPlugin === 'vue-docgen-api') {
const docgenInfo = extractedProp.docgenInfo as VueDocgenInfoEntry<'vue-docgen-api'>;
argType = extractFromVueDocgenApi(docgenInfo, section, extractedProp);
} else {
const docgenInfo =
extractedProp.docgenInfo as unknown as VueDocgenInfoEntry<'vue-component-meta'>;
argType = extractFromVueComponentMeta(docgenInfo, section);
}
// skip duplicate and global props
// skip duplicate and global props
if (!argType || argTypes[argType.name]) {
return;
}
// disable controls for events and exposed since they can not be controlled
// disable controls for events and exposed since they can not be controlled
const sectionsToDisableControls: (typeof section)[] = ['events', 'expose', 'exposed'];
if (sectionsToDisableControls.includes(section)) {
argType.control = { disable: true };
}
argTypes[argType.name] = argType;
});
});
return argTypes;
};
/**
* Extracts the argType for a prop/event/slot/expose generated with "vue-docgen-api".
*
* @param docgenInfo __docgenInfo from "vue-docgen-api"
* @param section Whether the arg is a prop, event, slot or expose
* @param extractedProp Extracted prop, needed when "section" is "slots"
*/
export const extractFromVueDocgenApi = (
docgenInfo: VueDocgenInfoEntry<'vue-docgen-api'>,
section: (typeof ARG_TYPE_SECTIONS)[number],
extractedProp?: ExtractedProp
): StrictInputType => {
let type: string | undefined;
let sbType: SBType | undefined;
if (section === 'events') {
const eventInfo = docgenInfo as VueDocgenInfoEntry<'vue-docgen-api', 'events'>;
type = eventInfo.type?.names.join();
sbType = { name: 'other', value: type ?? '', required: false };
}
if (section === 'slots') {
const slotInfo = docgenInfo as VueDocgenInfoEntry<'vue-docgen-api', 'slots'>;
// extract type of slot bindings/props
const slotBindings = slotInfo.bindings
?.filter((binding) => !!binding.name)
.map((binding) => {
return `${binding.name}: ${binding.type?.name ?? 'unknown'}`;
})
.join('; ');
type = slotBindings ? `{ ${slotBindings} }` : undefined;
sbType = { name: 'other', value: type ?? '', required: false };
}
if (section === 'props') {
const propInfo = docgenInfo as VueDocgenInfoEntry<'vue-docgen-api', 'props'>;
type = propInfo.type?.name;
sbType = extractedProp ? convert(extractedProp.docgenInfo) : { name: 'other', value: type };
// try to get more specific types for array, union and intersection
// e.g. "string[]" instead of "Array"
if (
propInfo.type &&
'elements' in propInfo.type &&
Array.isArray(propInfo.type.elements) &&
propInfo.type.elements.length > 0
) {
const elements = (propInfo.type.elements as { name: string }[]).map((i) => i.name);
if (type === 'Array') {
const arrayElements = elements.length === 1 ? elements[0] : `(${elements.join(' | ')})`;
type = `${arrayElements}[]`;
}
if (type === 'union') {
type = elements.join(' | ');
} else if (type === 'intersection') {
type = elements.join(' & ');
}
}
}
const required = 'required' in docgenInfo ? docgenInfo.required ?? false : false;
return {
name: docgenInfo.name,
description: docgenInfo.description,
type: sbType ? { ...sbType, required } : { name: 'other', value: type ?? '' },
table: {
type: type ? { summary: type } : undefined,
defaultValue: extractedProp?.propDef.defaultValue ?? undefined,
jsDocTags: extractedProp?.propDef.jsDocTags,
category: section,
},
};
};
/**
* Extracts the argType for a prop/event/slot/exposed generated with "vue-component-meta".
*
* @param docgenInfo __docgenInfo from "vue-component-meta"
* @param section Whether the arg is a prop, event, slot or exposed
*/
export const extractFromVueComponentMeta = (
docgenInfo: VueDocgenInfoEntry<'vue-component-meta'>,
section: (typeof ARG_TYPE_SECTIONS)[number]
): StrictInputType | undefined => {
// ignore global props
// ignore global props
if ('global' in docgenInfo && docgenInfo.global) {
return;
}
const tableType = { summary: docgenInfo.type.replace(' | undefined', '') };
if (section === 'props') {
const propInfo = docgenInfo as VueDocgenInfoEntry<'vue-component-meta', 'props'>;
const defaultValue = propInfo.default ? { summary: propInfo.default } : undefined;
return {
name: propInfo.name,
description: formatDescriptionWithTags(propInfo.description, propInfo.tags),
defaultValue,
type: convertVueComponentMetaProp(propInfo),
table: {
type: tableType,
defaultValue,
category: section,
},
};
} else {
return {
name: docgenInfo.name,
description: 'description' in docgenInfo ? docgenInfo.description : '',
type: { name: 'other', value: docgenInfo.type },
table: { type: tableType, category: section },
};
}
};
/** Converts the given prop info that was generated with "vue-component-meta" into a SBType. */
export const convertVueComponentMetaProp = (
propInfo: Pick<VueDocgenInfoEntry<'vue-component-meta', 'props'>, 'schema' | 'required' | 'type'>
): SBType => {
const schema = propInfo.schema;
const required = propInfo.required;
const fallbackSbType: SBType = { name: 'other', value: propInfo.type, required };
const KNOWN_SCHEMAS = ['string', 'number', 'function', 'boolean', 'symbol'] as const;
type KnownSchema = (typeof KNOWN_SCHEMAS)[number];
if (typeof schema === 'string') {
if (KNOWN_SCHEMAS.includes(schema as KnownSchema)) {
return { name: schema as KnownSchema, required };
}
return fallbackSbType;
}
switch (schema.kind) {
case 'enum': {
// filter out empty or "undefined" for optional props
let definedSchemas = schema.schema?.filter((item) => item !== 'undefined') ?? [];
if (isBooleanSchema(definedSchemas)) {
return { name: 'boolean', required };
}
if (isLiteralUnionSchema(definedSchemas) || isEnumSchema(definedSchemas)) {
// remove quotes from literals
const literals = definedSchemas.map((literal) => literal.replace(/"/g, ''));
return { name: 'enum', value: literals, required };
}
if (definedSchemas.length === 1) {
return convertVueComponentMetaProp({
schema: definedSchemas[0],
type: propInfo.type,
required,
});
}
// for union types like "string | number | boolean",
// the schema will be "string | number | true | false"
// so we need to replace "true | false" with boolean
if (
definedSchemas.length > 2 &&
definedSchemas.includes('true') &&
definedSchemas.includes('false')
) {
definedSchemas = definedSchemas.filter((i) => i !== 'true' && i !== 'false');
definedSchemas.push('boolean');
}
// recursively convert every type of the union
return {
name: 'union',
value: definedSchemas.map((i) => {
if (typeof i === 'object') {
return convertVueComponentMetaProp({
schema: i,
type: i.type,
required: false,
});
} else {
return convertVueComponentMetaProp({ schema: i, type: i, required: false });
}
}),
required,
};
}
case 'array': {
// filter out empty or "undefined" for optional props
const definedSchemas = schema.schema?.filter((item) => item !== 'undefined') ?? [];
if (definedSchemas.length === 0) {
return fallbackSbType;
}
if (definedSchemas.length === 1) {
return {
name: 'array',
value: convertVueComponentMetaProp({
schema: definedSchemas[0],
type: propInfo.type,
required: false,
}),
required,
};
}
// recursively convert every type of the array
// e.g. "(string | number)[]"
return {
name: 'union',
value: definedSchemas.map((i) => {
if (typeof i === 'object') {
return convertVueComponentMetaProp({
schema: i,
type: i.type,
required: false,
});
} else {
return convertVueComponentMetaProp({ schema: i, type: i, required: false });
}
}),
required,
};
}
case 'object':
return {
name: 'object',
// while Storybook generates simple JSON object controls, nested schemas don't have specialized controls
// so we don't need to recursively map the object schema here
value: {},
required,
};
default:
return fallbackSbType;
}
};
/** Adds the descriptions for the given tags if available. */
const formatDescriptionWithTags = (
description: string,
tags: VueDocgenInfoEntry<'vue-component-meta', 'props'>['tags']
): string => {
if (!tags?.length || !description) {
return description ?? '';
}
const tagDescriptions = tags.map((tag) => `@${tag.name}: ${tag.text}`).join('<br>');
return `${tagDescriptions}<br><br>${description}`;
};
/**
* Checks whether the given schemas are all literal union schemas.
*
* @example Foo | "bar" | "baz"
*/
const isLiteralUnionSchema = (schemas: PropertyMetaSchema[]): schemas is `"${string}"`[] => {
return schemas.every(
(schema) => typeof schema === 'string' && schema.startsWith('"') && schema.endsWith('"')
);
};
/**
* Checks whether the given schemas are all enums.
*
* @example MyEnum.Foo, MyEnum.Bar
*/
const isEnumSchema = (schemas: PropertyMetaSchema[]): schemas is string[] => {
return schemas.every((schema) => typeof schema === 'string' && schema.includes('.'));
};
/**
* Checks whether the given schemas are representing a boolean.
*
* @example
*
* ```
* true, false;
* ```
*/
const isBooleanSchema = (
schemas: PropertyMetaSchema[]
): schemas is ['true', 'false'] | ['false', 'true'] => {
return schemas.length === 2 && schemas.includes('true') && schemas.includes('false');
};
``` | /content/code_sandbox/code/renderers/vue3/src/docs/extractArgTypes.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 2,827 |
```xml
declare interface IWebpartDetailsWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'WebpartDetailsWebPartStrings' {
const strings: IWebpartDetailsWebPartStrings;
export = strings;
}
``` | /content/code_sandbox/samples/react-webpartdetails/src/webparts/webpartDetails/loc/mystrings.d.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 61 |
```xml
import { TDictionary } from '../TDictionary';
import { ICLIOptions } from '../../interfaces/options/ICLIOptions';
export type TInputCLIOptions = Partial<Pick<ICLIOptions, keyof ICLIOptions>> & TDictionary;
``` | /content/code_sandbox/src/types/options/TInputCLIOptions.ts | xml | 2016-05-09T08:16:53 | 2024-08-16T19:43:07 | javascript-obfuscator | javascript-obfuscator/javascript-obfuscator | 13,358 | 50 |
```xml
<?xml version="1.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.
-->
<!--
This is the URDF model for the Intel RealSense 435i camera, in it's
aluminum peripherial evaluation case.
-->
<robot name="sensor_d435i" xmlns:xacro="path_to_url">
<xacro:include filename="$(find realsense2_description)/urdf/_d435.urdf.xacro"/>
<xacro:include filename="$(find realsense2_description)/urdf/_d435i_imu_modules.urdf.xacro"/>
<xacro:macro name="sensor_d435i" params="parent *origin name:=camera use_nominal_extrinsics:=false">
<xacro:sensor_d435 parent="${parent}" name="${name}" use_nominal_extrinsics="${use_nominal_extrinsics}">
<xacro:insert_block name="origin" />
</xacro:sensor_d435>
<xacro:d435i_imu_modules name="${name}" use_nominal_extrinsics="${use_nominal_extrinsics}"/>
</xacro:macro>
</robot>
``` | /content/code_sandbox/realsense2_description/urdf/_d435i.urdf.xacro | xml | 2016-02-23T23:52:58 | 2024-08-15T13:59:39 | realsense-ros | IntelRealSense/realsense-ros | 2,479 | 270 |
```xml
import { TestBed } from "@angular/core/testing";
import { FormBuilder } from "@angular/forms";
import { BehaviorSubject, first } from "rxjs";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { SendType } from "@bitwarden/common/tools/send/enums/send-type";
import { SendView } from "@bitwarden/common/tools/send/models/view/send.view";
import { SendListFiltersService } from "./send-list-filters.service";
describe("SendListFiltersService", () => {
let service: SendListFiltersService;
const policyAppliesToActiveUser$ = new BehaviorSubject<boolean>(false);
const i18nService = {
t: (key: string) => key,
} as I18nService;
const policyService = {
policyAppliesToActiveUser$: jest.fn(() => policyAppliesToActiveUser$),
};
beforeEach(() => {
policyAppliesToActiveUser$.next(false);
policyService.policyAppliesToActiveUser$.mockClear();
TestBed.configureTestingModule({
providers: [
{
provide: I18nService,
useValue: i18nService,
},
{
provide: PolicyService,
useValue: policyService,
},
{ provide: FormBuilder, useClass: FormBuilder },
],
});
service = TestBed.inject(SendListFiltersService);
});
it("returns all send types", () => {
expect(service.sendTypes.map((c) => c.value)).toEqual([SendType.File, SendType.Text]);
});
it("filters disabled sends", (done) => {
const sends = [{ disabled: true }, { disabled: false }, { disabled: true }] as SendView[];
service.filterFunction$.pipe(first()).subscribe((filterFunction) => {
expect(filterFunction(sends)).toEqual([sends[1]]);
done();
});
service.filterForm.patchValue({});
});
it("resets the filter form", () => {
service.filterForm.patchValue({ sendType: SendType.Text });
service.resetFilterForm();
expect(service.filterForm.value).toEqual({ sendType: null });
});
it("filters by sendType", (done) => {
const sends = [
{ type: SendType.File },
{ type: SendType.Text },
{ type: SendType.File },
] as SendView[];
service.filterFunction$.subscribe((filterFunction) => {
expect(filterFunction(sends)).toEqual([sends[1]]);
done();
});
service.filterForm.patchValue({ sendType: SendType.Text });
});
});
``` | /content/code_sandbox/libs/tools/send/send-ui/src/services/send-list-filters.service.spec.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 577 |
```xml
import _ = require("lodash");
import { ColumnType } from "./ColumnType";
import { SQLDialect, ensureDialectColumnType } from "./dialect";
import { dialects } from "./dialectRegistry";
// metadata for a single column:
export type ColumnMetadata = {
displayName: string;
columnType: string; // sql type name, based on dialect
};
export type ColumnMetaMap = {
[colId: string]: ColumnMetadata;
};
const validateColumnMetadata = (dialect: SQLDialect, cmap: ColumnMetaMap) => {
for (let [colId, cmd] of Object.entries(cmap)) {
ensureDialectColumnType(dialect, cmd.columnType);
}
};
class SchemaError {
message: string;
rest: Array<any>;
constructor(message: string, ...rest: Array<any>) {
this.message = message;
this.rest = rest;
}
}
interface SchemaJSON {
dialect: string;
columns: string[];
columnMetadata: ColumnMetaMap;
}
export class Schema {
dialect: SQLDialect;
columnMetadata: ColumnMetaMap;
columns: Array<string>;
columnIndices: {
[colId: string]: number;
};
_sortedColumns: Array<string> | undefined | null;
constructor(
dialect: SQLDialect,
columns: Array<string>,
columnMetadata: ColumnMetaMap
) {
this.dialect = dialect;
this.columns = columns.slice();
this.columnMetadata = columnMetadata;
validateColumnMetadata(dialect, columnMetadata);
this._sortedColumns = null;
var columnIndices: { [colId: string]: number } = {};
for (var i = 0; i < columns.length; i++) {
var col = columns[i];
columnIndices[col] = i;
}
this.columnIndices = columnIndices;
}
columnType(colId: string): ColumnType {
const cmd = this.columnMetadata[colId];
if (cmd == null) {
throw new Error(`Schema.columnType: unknown column '${colId}'`);
}
const sqlTypeName = cmd.columnType;
return this.dialect.columnTypes[sqlTypeName];
}
displayName(colId: string): string {
const md = this.columnMetadata[colId];
const dn = (md && md.displayName) || colId;
return dn;
}
columnIndex(colId: string): number {
return this.columnIndices[colId];
}
compatCheck(sb: Schema): boolean {
if (this.columns.length !== sb.columns.length) {
throw new SchemaError(
"incompatible schema: columns length mismatch",
this,
sb
);
}
for (var i = 0; i < this.columns.length; i++) {
var colId = this.columns[i];
var bColId = sb.columns[i];
if (colId !== bColId) {
throw new SchemaError(
"incompatible schema: expected '" +
colId +
"', found '" +
bColId +
"'",
this,
sb
);
}
var colType = this.columnMetadata[colId].columnType;
var bColType = sb.columnMetadata[bColId].columnType;
if (colType !== bColType) {
throw new SchemaError(
"mismatched column types for col '" +
colId +
"': " +
colType +
", " +
bColType,
this,
sb
);
}
}
return true;
}
// Construct a row map with keys being column ids:
rowMapFromRow(rowArray: Array<any>): Object {
var columnIds = this.columns;
var rowMap: { [cid: string]: any } = {};
for (var col = 0; col < rowArray.length; col++) {
rowMap[columnIds[col]] = rowArray[col];
}
return rowMap;
}
// calculate extension of this schema (as in extend query):
extend(colId: string, columnMetadata: ColumnMetadata): Schema {
var outCols = this.columns.concat([colId]);
let cMap: { [cid: string]: ColumnMetadata } = {};
cMap[colId] = columnMetadata;
var outMetadata = _.extend(cMap, this.columnMetadata);
var outSchema = new Schema(this.dialect, outCols, outMetadata);
return outSchema;
}
// returned an array of column ids in locale-sorted order
// cached lazily
sortedColumns(): Array<string> {
let sc = this._sortedColumns;
if (sc == null) {
sc = this.columns.slice();
sc.sort((cid1, cid2) =>
this.displayName(cid1).localeCompare(this.displayName(cid2))
);
this._sortedColumns = sc;
}
return sc;
}
toJSON(): SchemaJSON {
return {
dialect: this.dialect.dialectName,
columns: this.columns,
columnMetadata: this.columnMetadata,
};
}
static fromJSON(json: SchemaJSON | string): Schema {
if (typeof json === "string") {
return JSON.parse(json, Schema.reviver);
} else {
const dialect = dialects[json.dialect];
let schema = new Schema(dialect, json.columns, json.columnMetadata);
return schema;
}
}
static reviver(key: string, value: any): any {
return key === "" ? Schema.fromJSON(value) : value;
}
}
``` | /content/code_sandbox/packages/reltab/src/Schema.ts | xml | 2016-10-24T18:59:04 | 2024-08-16T16:29:52 | tad | antonycourtney/tad | 3,125 | 1,183 |
```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>com.apple.security.app-sandbox</key>
<true/>
</dict>
</plist>
``` | /content/code_sandbox/entitlements.mas.loginhelper.plist | xml | 2016-10-30T10:49:56 | 2024-08-16T19:12:59 | lossless-cut | mifi/lossless-cut | 25,459 | 71 |
```xml
import { Log, ServiceKey, ServiceScope } from "@microsoft/sp-core-library";
import { spfi, SPFI, SPFx as spSPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import { PageContext } from "@microsoft/sp-page-context";
const LOG_SOURCE: string = "'advanced-iframe-webpart:ScriptSaveDomainService";
/**
* A service that tells us if a given domain is save to display in an IFrame
*/
export interface IScriptSaveDomainService {
/**
* Returns true if the given url is a safe url
* @param url
* @returns
*/
isInSaveDomain: (url: string) => Promise<boolean>;
}
/**
* A service that tells us if a given domain is save to display in an IFrame
*/
export class ScriptSaveDomainService implements IScriptSaveDomainService {
/**
* Stores the downloaded script save domains
*/
private _scriptSaveDomains: string[] = null;
/**
* The pnpjs spfi object
*/
private _spfi: SPFI;
//Create a ServiceKey which will be used to consume the service.
public static readonly serviceKey: ServiceKey<IScriptSaveDomainService> =
ServiceKey.create<IScriptSaveDomainService>(LOG_SOURCE, ScriptSaveDomainService);
/**
* Constructor
* @param serviceScope the servicescipe
*/
constructor(serviceScope: ServiceScope) {
serviceScope.whenFinished(() => {
Log.info(LOG_SOURCE, "Begin constructing ScriptSaveDomainService");
const pageContext = serviceScope.consume(PageContext.serviceKey);
this._spfi = spfi().using(spSPFx({ pageContext }));
Log.info(LOG_SOURCE, "Constructed ScriptSaveDomainService");
});
}
/**
* Fetches an array of all script save domains
* @returns
*/
private async fetchScriptSaveDomains() {
// If we don't have already downloaded the domains
if (this._scriptSaveDomains == null) {
Log.info(LOG_SOURCE, "Downloading Property Bag");
// get the Script Save Domains from the site's property bag
const props = await this._spfi.web.allProperties();
//parse and split them into an array
this._scriptSaveDomains = `${props["OData__x005f__x005f_ScriptSafeDomains"]}`
.split(";")
.filter((d: string) => d != null && d.length > 0)
;
// Always allow IFrames from the current domain
this._scriptSaveDomains.push(window.location.host);
Log.info(LOG_SOURCE, "Created script safe domains array");
}
return this._scriptSaveDomains;
}
/**
* Returns true if the given url is a safe url
* @param url
* @returns
*/
public async isInSaveDomain(url: string) {
const result = (await this.fetchScriptSaveDomains()).reduce((value, domain) => {
if (url.indexOf(domain) != -1) {
return true;
}
return value;
}, false)
Log.info(LOG_SOURCE, `Domain ${url} is a save domain? ${result}`);
return result;
}
}
``` | /content/code_sandbox/samples/react-advanced-iframe/src/webparts/advancediframewebpart/services/ScriptSaveDomainService.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 695 |
```xml
<vector xmlns:android="path_to_url"
android:width="96dp"
android:height="96dp"
android:viewportWidth="96"
android:viewportHeight="96">
<path
android:pathData="M18.5237,68.8835C28.9052,65.0448 39.1931,64.4806 49.3391,68.8835L48.9641,89.0009C38.3071,95.1636 28.1427,93.4452 18.1487,89.0009Z"
android:fillColor="#ede45d"/>
<path
android:pathData="M28.2107,14.2887C25.4354,20.7084 16.7964,24.0962 16.7964,30.8914L16.7964,34.0044C16.7964,36.0798 17.7822,36.1654 18.8717,37.1174 17.7822,38.0695 16.7964,38.1551 16.7964,40.2305 16.7964,42.3058 17.7822,42.3914 18.8717,43.3434 17.7822,44.2955 16.7964,44.3811 16.7964,46.4564 16.7964,48.5318 17.8489,48.4216 18.8717,49.5695 17.8341,50.6071 16.7964,50.6071 16.7964,52.6825 16.7381,53.9404 17.8341,54.7578 18.8717,55.7955 17.8341,56.8332 16.7815,68.9829 16.7964,72.3981 16.826,79.2286 16.7985,86.6707 17.834,89.0009 21.6554,94.6582 44.454,94.4169 48.9641,89.0009 50.0635,86.4376 50.0172,79.0892 50.0018,72.3982 49.9941,69.0526 48.9641,56.8331 47.9264,55.7955 48.9641,54.7578 50.0018,54.1026 50.0018,52.6825 50.0018,50.6071 48.9641,50.6071 47.9264,49.5695 48.9641,48.5318 50.0018,48.5318 50.0018,46.4565 50.0018,44.3811 49.016,44.2955 47.9264,43.3435 49.016,42.3914 50.0018,42.3058 50.0018,40.2305 50.0018,38.1551 49.016,38.0695 47.9264,37.1174 49.016,36.1654 50.0018,36.0798 50.0018,34.0044L50.0018,30.8914C50.0018,24.2634 41.5209,20.3729 38.5874,14.2888L38.5874,10.1381 28.2107,10.1381Z"
android:strokeAlpha="0.66666667"
android:strokeWidth="2.38394427"
android:fillColor="#f2ed9a"
android:strokeColor="#decf8a"
android:fillAlpha="0.41414143"/>
<path
android:pathData="M47.7513,54.6014C37.9505,51.8739 27.976,51.7926 18.6966,54.6014"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M47.7513,48.3753C37.7686,45.7254 27.8099,45.4829 18.6967,48.3754"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M47.7514,42.1494C38.1199,39.3406 28.1503,39.4242 18.6966,42.1493"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M47.7513,35.9233C38.1199,33.1146 28.1503,33.1981 18.6966,35.9233"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M18.8717,37.1174C28.6726,39.8449 38.6471,39.9262 47.9264,37.1174"
android:strokeAlpha="0.66666667"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M18.8717,43.3434C28.8545,45.9934 38.8132,46.2359 47.9264,43.3435"
android:strokeAlpha="0.66666667"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M18.8717,49.5695C28.5032,52.3782 38.4728,52.2947 47.9264,49.5695"
android:strokeAlpha="0.66666667"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M18.8717,55.7955C28.5032,58.6042 38.4728,58.5207 47.9264,55.7955"
android:strokeAlpha="0.66666667"
android:strokeWidth="2.38394427"
android:strokeColor="#ded98a"
android:strokeLineCap="round"/>
<path
android:pathData="M25.0977,10.6569a2.7488,8.3013 90,1 0,16.6027 -0a2.7488,8.3013 90,1 0,-16.6027 0z"
android:fillColor="#9fd770"/>
<path
android:pathData="M19.4777,87.9206C19.0087,80.3052 17.4808,73.862 20.5153,59.0604 25.2016,60.2383 31.7196,60.93 37.9611,61.0709 22.4669,61.9933 21.8344,78.8578 19.4777,87.9206Z"
android:fillColor="#eef7fb"
android:fillAlpha="0.8"/>
<path
android:pathData="M19.1116,32.0626C17.9139,26.5323 28.7424,20.8627 30.8299,14.4277 30.9586,23.1549 22.7404,31.791 24.5751,33.3098 21.656,32.8795 20.1239,32.7313 19.1116,32.0626Z"
android:fillColor="#eef7fb"
android:fillAlpha="0.8"/>
<path
android:pathData="M19.3586,38.9878C18.8031,39.36 18.1279,41.3839 18.6966,42.1493 18.6493,41.1144 36.1568,41.2108 38.1086,41.1529 31.5501,40.6957 24.7621,40.435 19.3586,38.9878Z"
android:fillColor="#eef7fb"
android:fillAlpha="0.8"/>
<path
android:pathData="M19.6147,44.8108C19.0593,45.1831 18.4299,47.2069 18.9986,47.9724 18.9513,46.9374 36.4129,47.0339 38.3648,46.976 31.8062,46.5187 25.0182,46.2581 19.6147,44.8108Z"
android:fillColor="#eef7fb"
android:fillAlpha="0.8"/>
<path
android:pathData="M19.6796,51.2314C19.1241,51.6037 18.6323,53.5816 19.201,54.3471 19.1537,53.3121 36.4778,53.4544 38.4296,53.3965 31.8711,52.9393 25.0831,52.6787 19.6796,51.2314Z"
android:fillColor="#eef7fb"
android:fillAlpha="0.8"/>
<path
android:pathData="M33.3824,2.5031A1.0377,6.226 103.3101,0 0,27.2334 3.3867L27.1564,3.3868 27.1564,3.5408 27.1564,9.6127A1.0377,6.226 103.3101,0 0,33.3824 10.6504,1.0377 6.226,103.3101 0,0 39.6084,9.6128L39.6084,3.5408 39.6084,3.3867 39.5334,3.3867A1.0377,6.226 103.3101,0 0,33.3824 2.5031Z"
android:fillColor="#53a23e"/>
<path
android:pathData="M27.0813,3.5164a1.1674,6.2584 90,1 0,12.5169 -0a1.1674,6.2584 90,1 0,-12.5169 0z"
android:fillColor="#8ecd7d"/>
<path
android:pathData="M83.9453,55.231C83.9453,65.896 75.2997,74.5416 64.6347,74.5416 53.9697,74.5416 45.3241,65.896 45.3241,55.231 45.3241,45.1221 64.5251,21.7571 64.5251,16.6558 64.5251,21.5838 83.9453,44.6024 83.9453,55.231Z"
android:fillColor="#ffc62e"
android:fillAlpha="0.7171717"/>
<path
android:pathData="M49.932,51.6079a8.5406,12.8605 135,1 0,18.1875 18.1875a8.5406,12.8605 135,1 0,-18.1875 -18.1875z"
android:fillColor="#ffca27"
android:fillAlpha="0.53535354"/>
<path
android:pathData="M54.0275,43.7675C40.8307,58.6255 53.558,70.8539 62.8336,71.7748 58.8986,68.6886 49.1738,61.474 54.0275,43.7675Z"
android:fillColor="#fff4c4"
android:fillAlpha="0.96470588"/>
<path
android:pathData="M65.1912,24.1395C69.9324,34.2202 88.3916,51.1391 75.0561,54.0513 61.7207,56.9637 65.8251,32.3996 65.1912,24.1395Z"
android:fillColor="#ffe47c"
android:fillAlpha="0.65656565"/>
<path
android:pathData="M65.9694,25.7288C70.7106,35.8094 81.8,46.85 73.8164,47.8321 65.8328,48.8142 66.6033,33.9889 65.9694,25.7288Z"
android:fillColor="#fffef0"
android:fillAlpha="0.65656565"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_recycling_cooking_oil.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 3,153 |
```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.
*/
import minmaxabsn = require( './index' );
// TESTS //
// The function returns an array of numbers...
{
minmaxabsn(); // $ExpectType number[]
minmaxabsn( -0.2 ); // $ExpectType number[]
minmaxabsn( 3.0, -0.2 ); // $ExpectType number[]
minmaxabsn( 3.0, -0.2, -1.2 ); // $ExpectType number[]
minmaxabsn( 3.0, -0.2, -1.2, -4.0 ); // $ExpectType number[]
minmaxabsn( 3.0, -0.2, -1.2, -4.0, 5.0 ); // $ExpectType number[]
}
// The compiler throws an error if the function is provided an argument which is not a number...
{
minmaxabsn( true ); // $ExpectError
minmaxabsn( false ); // $ExpectError
minmaxabsn( [] ); // $ExpectError
minmaxabsn( {} ); // $ExpectError
minmaxabsn( 'abc' ); // $ExpectError
minmaxabsn( ( x: number ): number => x ); // $ExpectError
minmaxabsn( 1.2, true ); // $ExpectError
minmaxabsn( 1.2, false ); // $ExpectError
minmaxabsn( 1.2, [] ); // $ExpectError
minmaxabsn( 1.2, {} ); // $ExpectError
minmaxabsn( 1.2, 'abc' ); // $ExpectError
minmaxabsn( 1.2, ( x: number ): number => x ); // $ExpectError
minmaxabsn( 1.2, 3.0, true ); // $ExpectError
minmaxabsn( 1.2, 3.0, false ); // $ExpectError
minmaxabsn( 1.2, 3.0, [] ); // $ExpectError
minmaxabsn( 1.2, 3.0, {} ); // $ExpectError
minmaxabsn( 1.2, 3.0, 'abc' ); // $ExpectError
minmaxabsn( 1.2, 3.0, ( x: number ): number => x ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, true ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, false ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, [] ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, {} ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 'abc' ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, ( x: number ): number => x ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, true ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, false ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, [] ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, {} ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 'abc' ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, ( x: number ): number => x ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, true ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, false ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, [] ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, {} ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, 'abc' ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, ( x: number ): number => x ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, 7.0, true ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, 7.0, false ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, 7.0, [] ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, 7.0, {} ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, 7.0, 'abc' ); // $ExpectError
minmaxabsn( 1.2, 3.0, 4.0, 5.0, 6.0, 7.0, ( x: number ): number => x ); // $ExpectError
}
// Attached to the main export is an `assign` method which returns an array-like object containing numbers...
{
const out = [ 0.0, 0.0 ];
minmaxabsn.assign( out, 1, 0 ); // $ExpectType Collection<number>
minmaxabsn.assign( 3.0, out, 1, 0 ); // $ExpectType Collection<number>
minmaxabsn.assign( 3.0, -0.2, out, 1, 0 ); // $ExpectType Collection<number>
minmaxabsn.assign( 3.0, -0.2, 1.0, out, 1, 0 ); // $ExpectType Collection<number>
minmaxabsn.assign( 3.0, -0.2, -1.2, -4.0, out, 1, 0 ); // $ExpectType Collection<number>
minmaxabsn.assign( 3.0, -0.2, -1.2, -4.0, 5.0, out, 1, 0 ); // $ExpectType Collection<number>
minmaxabsn.assign( 3.0, -0.2, -1.2, -4.0, 5.0, 6.0, out, 1, 0 ); // $ExpectType Collection<number>
}
// The compiler throws an error if the `assign` method is provided a first argument which is not a number...
{
const out = [ 0.0, 0.0 ];
minmaxabsn.assign( true, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( false, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( '5', -0.2, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( null, -0.2, 1.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( [], -0.2, -1.2, -4.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( {}, -0.2, -1.2, -4.0, 5.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( ( x: number ): number => x, -0.2, -1.2, -4.0, 5.0, 6.0, out, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `assign` method is provided a second argument which is not a number...
{
const out = [ 0.0, 0.0 ];
minmaxabsn.assign( 1.0, false, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, '5', -0.2, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, null, -0.2, 1.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, [], -0.2, -1.2, -4.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, {}, -0.2, -1.2, -4.0, 5.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, ( x: number ): number => x, -0.2, -1.2, -4.0, 5.0, 6.0, out, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `assign` method is provided an invalid third argument...
{
const out = [ 0.0, 0.0 ];
minmaxabsn.assign( 1.0, 2.0, false, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, null, -0.2, 1.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, {}, -0.2, -1.2, -4.0, 5.0, out, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `assign` method is provided an invalid fourth argument...
{
const out = [ 0.0, 0.0 ];
minmaxabsn.assign( 1.0, 2.0, 3.0, false, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, 3.0, null, -0.2, 1.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, 3.0, {}, -0.2, -1.2, -4.0, 5.0, out, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `assign` method is provided an invalid fifth argument...
{
const out = [ 0.0, 0.0 ];
minmaxabsn.assign( 1.0, 2.0, 3.0, 4.0, false, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, 3.0, 4.0, null, -0.2, 1.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, 3.0, 4.0, {}, -0.2, -1.2, -4.0, 5.0, out, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `assign` method is provided an invalid sixth argument...
{
const out = [ 0.0, 0.0 ];
minmaxabsn.assign( 1.0, 2.0, 3.0, 4.0, 5.0, false, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, 3.0, 4.0, 5.0, null, -0.2, 1.0, out, 1, 0 ); // $ExpectError
minmaxabsn.assign( 1.0, 2.0, 3.0, 4.0, 5.0, {}, -0.2, -1.2, -4.0, 5.0, out, 1, 0 ); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/math/base/special/minmaxabsn/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 2,986 |
```xml
import {Minimum, Name, Required} from "@tsed/schema";
import moment from "moment";
import {OnSerialize} from "../../src/decorators/onSerialize.js";
import {deserialize} from "../../src/utils/deserialize.js";
import {serialize} from "../../src/utils/serialize.js";
function serializeDate(date: Date) {
return date && moment(date).format("YYYYMMDD");
}
class ProductCalendarParameters {
@Required()
@Minimum(1)
duration: number;
@Name("first_date")
@OnSerialize(serializeDate)
@Required()
firstDate: Date;
@Name("last_date")
@OnSerialize(serializeDate)
@Required()
lastDate: Date;
@Name("number_of_adults")
numberOfAdults: number;
@Name("departure_option_id")
departureOptionId: string;
}
describe("Date mapper", () => {
it("should serialize object correctly", () => {
const productCalendarParameters = deserialize(
{
duration: 7,
first_date: "2020-11-13T14:48:24.651Z",
last_date: "2020-12-13T14:48:24.652Z",
number_of_adults: 2
},
{type: ProductCalendarParameters}
);
expect(productCalendarParameters).toEqual({
duration: 7,
firstDate: new Date("2020-11-13T14:48:24.651Z"),
lastDate: new Date("2020-12-13T14:48:24.652Z"),
numberOfAdults: 2
});
expect(serialize(productCalendarParameters)).toEqual({
duration: 7,
first_date: "20201113",
last_date: "20201213",
number_of_adults: 2
});
});
});
``` | /content/code_sandbox/packages/specs/json-mapper/test/integration/models.date.intregration.spec.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 401 |
```xml
import * as moment from "moment";
import { generateModels, IModels } from "../../../connectionResolver";
import { IFieldDocument } from "../../../db/models/definitions/fields";
const prepareData = async (
models: IModels,
_subdomain: string,
_query: any
): Promise<any[]> => {
let data: any[] = [];
const { page, perPage } = _query;
const skip = (page - 1) * perPage;
const productsFilter: any = {};
data = await models.Products.find(productsFilter)
.skip(skip)
.limit(perPage)
.lean();
return data;
};
const prepareDataCount = async (
models: IModels,
_subdomain: string,
_query: any
): Promise<any> => {
let data = 0;
const productsFilter: any = {};
data = await models.Products.find(productsFilter).countDocuments();
return data;
};
const getCustomFieldsData = async (item, fieldId) => {
let value;
if (item.customFieldsData && item.customFieldsData.length > 0) {
for (const customFeild of item.customFieldsData) {
if (customFeild.field === fieldId) {
value = customFeild.value;
if (Array.isArray(value)) {
value = value.join(", ");
}
return { value };
}
}
}
return { value };
};
export const fillValue = async (
models: IModels,
column: string,
item: any
): Promise<string> => {
let value = item[column];
switch (column) {
case "createdAt":
value = moment(value).format("YYYY-MM-DD");
break;
case "categoryName":
const category = await models.ProductCategories.findOne({
_id: item.categoryId
}).lean();
value = category?.name || "-";
break;
case "tag":
const tags = await models.Tags.find({ _id: { $in: item.tagIds || [] } });
let tagNames = "";
for (const tag of tags) {
tagNames = tagNames.concat(tag.name, ", ");
}
value = tags ? tagNames : "-";
break;
case "barcodes":
value =
item.barcodes && item.barcodes.length ? item.barcodes.join(",") : "";
break;
case "uom":
const uom = await models.Uoms.findOne({
_id: item.uom
}).lean();
value = uom?.name || "-";
break;
default:
break;
}
return value || "-";
};
export const IMPORT_EXPORT_TYPES = [
{
text: "Product & Services",
contentType: "product",
icon: "server-alt",
skipFilter: true
}
];
const fillProductSubUomValue = async (models: IModels, column, item) => {
const subUoms = item.subUoms;
let value;
for (const subUom of subUoms) {
let uom;
switch (column) {
case "subUoms.code":
uom = (await models.Uoms.findOne({ _id: subUom.uom })) || {};
value = uom.code;
break;
case "subUoms.name":
uom = (await models.Uoms.findOne({ _id: subUom.uom })) || {};
value = uom.name;
break;
case "subUoms.subratio":
value = subUom.ratio;
break;
}
}
return { value };
};
export default {
importExportTypes: IMPORT_EXPORT_TYPES,
prepareExportData: async ({ subdomain, data }) => {
const models = await generateModels(subdomain);
const { columnsConfig } = data;
let totalCount = 0;
const headers = [] as any;
const excelHeader = [] as any;
try {
const results = await prepareDataCount(models, subdomain, data);
totalCount = results;
for (const column of columnsConfig) {
if (column.startsWith("customFieldsData")) {
const fieldId = column.split(".")[1];
const field =
(await models.Fields.findOne({ _id: fieldId })) ||
({} as IFieldDocument);
headers.push(`customFieldsData.${field.text}.${fieldId}`);
} else if (column.startsWith("subUoms")) {
headers.push(column);
} else {
headers.push(column);
}
}
for (const header of headers) {
if (header.startsWith("customFieldsData")) {
excelHeader.push(header.split(".")[1]);
} else {
excelHeader.push(header);
}
}
} catch (e) {
return {
error: e.message
};
}
return { totalCount, excelHeader };
},
getExportDocs: async ({ subdomain, data }) => {
const models = await generateModels(subdomain);
const { columnsConfig } = data;
const docs = [] as any;
const headers = [] as any;
try {
const results = await prepareData(models, subdomain, data);
for (const column of columnsConfig) {
if (column.startsWith("customFieldsData")) {
const fieldId = column.split(".")[1];
const field =
(await models.Fields.findOne({ _id: fieldId })) ||
({} as IFieldDocument);
headers.push(`customFieldsData.${field.text}.${fieldId}`);
} else if (column.startsWith("subUoms")) {
headers.push(column);
} else {
headers.push(column);
}
}
for (const item of results) {
const result = {};
for (const column of headers) {
if (column.startsWith("customFieldsData")) {
const fieldId = column.split(".")[2];
const fieldName = column.split(".")[1];
const { value } = await getCustomFieldsData(item, fieldId);
result[column] = value || "-";
} else if (column.startsWith("subUoms")) {
const { value } = await fillProductSubUomValue(
models,
column,
item
);
result[column] = value || "-";
} else {
const value = await fillValue(models, column, item);
result[column] = value || "-";
}
}
docs.push(result);
}
} catch (e) {
return { error: e.message };
}
return { docs };
}
};
``` | /content/code_sandbox/packages/core/src/data/modules/product/exporter.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,397 |
```xml
import { Guid } from "@microsoft/sp-core-library";
import { ISearchResult } from "@pnp/sp/search";
import { SearchHit } from "@microsoft/microsoft-graph-types";
export interface ISearchResultExtended extends ISearchResult {
SPSiteURL?: string;
ListItemId?: number;
ListId?: string;
ListUrl?: string;
SharedWithUsersOWSUSER?: string;
FileName?: string;
SharedWithDetails?: string;
Rank?: number;
DocId?: number;
WorkId?: number;
IdentityListItemId?: Guid;
ViewableByExternalUsers?: boolean;
DriveItemId?: string;
FileId?: string;
DriveId?: string;
SiteUrl?: string;
}
export interface IGraphSearchResultExtended extends SearchHit {
}
``` | /content/code_sandbox/samples/react-governor-sharing/src/webparts/sharing/components/SharingView/ISearchResultExtended.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 169 |
```xml
<mxfile modified="2022-01-19T14:14:16.016Z" host="app.diagrams.net" agent="5.0 (X11)" etag="5VNsiw-64COc7e_b5nam" version="16.4.0" type="device"><diagram id="9906a0a6-bcd4-fe14-221d-85032a32ce87" name="Page-1">7Zxtc5s4EIB/jWdyH+JBvBl/TJykvZveTKbpXNqPAmTMRUYuyHFyv/your_sha512_hash/your_sha256_hashmAY24rPKI4W4tKeIyp8GDxEKVkn4noj05rnn6J6Ccu+your_sha256_hashV/gHukr94ByU/your_sha256_hashRnsOCDLOBDlGPoIX1ZzOCOYpKwqIQniXdCUPKCykE2tm3+qmlJUvKd5jHGt5dzh/3g5SegNXMaYo/llHcQhZIOakSQjfFh5veAR2OJ7rR8j/7ByiOMoYWUBm2jEKi/FjKGUoqdWYYBKxOzZQWSJaPrMmojHRDwjmy1xE4HJosaaLcqgYDyq+tnKmR0IUR8jdjBVxD4yXUzFNEjCd3+uSVlxnuUTdsEaAHP1tK3kj17Bw7ZMmfNaazfif2GSxT5G56s1v+fiyour_sha512_hash/u/6A0hAlsiNs8XtyKbDUEtCuV0r0T8ja9wwwe6EDeXqv2CONH3rkY71Y/iJEr+your_sha256_hashjyYL1n+KCv99Ei+your_sha256_hashS/nHM5cq4akJGULkhEEojrmG1Fb3Qo+your_sha512_hash/ckBQyob5x2CFPpQVsj17rxXS8NgPkI4CJPPBGScaJkM0h2tMBxw/your_sha256_hashlAVNOPwOPqJsxHdK2X8hpOyMDO0ChA89DiC+EJPlE0rJklWgJLzgu6i8DJPgYa/ED5QWCiN0J24FYZ9srrcFl3kBqyjvahd/your_sha256_hashdDQxGwHTpokphqt0lNNUjeeFykbdA6425jB89gl5+your_sha256_hash1ddUs5EmJMrZsZt9jHBRU8x/V47/sGt+Ng1bPG9Zudz6/4y0EsL1zfpZtPalp7XsahbHmggqHTVEeyW6Wqv0xXqjkr2HaMyE+b+g1M9tmSuPec1XJfR590Og3sg6wIAY2wY5Y71K/G3DUtmqXRejsXfAV6jI/eV8KuXKtuQ+TxDnXsiZqsjEpBUdXCH4MuvHHwBrinhqgm+your_sha256_hashyour_sha256_hash1+CzJpo0ILcDTeSpOwJnczZM5qbCYJG7tBlb6c5yHzRbMyDyY0SDsbpTxQZIG+KWZFU6/your_sha256_hashg01+V5X/your_sha256_hashyour_sha256_hashyour_sha256_hashh7y56oHG0LkzYNf0qbt8phCmC2q2+FfbiFlw0ryEjPfdOjCs26k2wNrqti5EpCufSpgqHmq6pp/IONtyFC2QjVvYvRHhuoBWQMZ74QM25a34UDp4pyCDE3ahD2Q8U7IcBo6w3TUVVN/your_sha256_hash7NPpjMc4mn3zbQpAcnNnYJR9+/zXOQDqUvZsE1Oyour_sha512_hasha9NLTSaISVT7uKlWbQmaHTUWRat/obb7gs0c76cPe2b/QOpffc5uu2your_sha512_hash2OY1vX/</diagram></mxfile>
``` | /content/code_sandbox/doc/source/_graphs/recording-workflow.xml | xml | 2016-06-08T20:52:08 | 2024-08-12T19:10:07 | ara | ansible-community/ara | 1,829 | 1,054 |
```xml
import type { SearchResultItemAction } from "@common/Core";
import type { ActionHandler } from "@Core/ActionHandler";
import type { UeliCommandInvoker } from "@Core/UeliCommand";
export class UeliCommandActionHandler implements ActionHandler {
public readonly id = "UeliCommand";
public constructor(private readonly ueliCommandInvoker: UeliCommandInvoker) {}
public async invokeAction(action: SearchResultItemAction): Promise<void> {
const map: Record<string, () => Promise<void>> = {
quit: () => this.ueliCommandInvoker.invokeUeliCommand("quit"),
settings: () => this.ueliCommandInvoker.invokeUeliCommand("openSettings"),
extensions: () => this.ueliCommandInvoker.invokeUeliCommand("openExtensions"),
centerWindow: () => this.ueliCommandInvoker.invokeUeliCommand("centerWindow"),
};
if (!Object.keys(map).includes(action.argument)) {
throw new Error(`Unexpected argument: ${action.argument}`);
}
await map[action.argument]();
}
}
``` | /content/code_sandbox/src/main/Extensions/UeliCommand/UeliCommandActionHandler.ts | xml | 2016-10-11T04:59:52 | 2024-08-16T11:53:31 | ueli | oliverschwendener/ueli | 3,543 | 221 |
```xml
import { DisposableDelegate, IDisposable } from '@lumino/disposable';
import { ISignal, Signal } from '@lumino/signaling';
import { JupyterFrontEnd } from './frontend';
import { ILabStatus } from './tokens';
/**
* The application status signals and flags class.
*/
export class LabStatus implements ILabStatus {
/**
* Construct a new status object.
*/
constructor(app: JupyterFrontEnd<any, any>) {
this._busySignal = new Signal(app);
this._dirtySignal = new Signal(app);
}
/**
* Returns a signal for when application changes its busy status.
*/
get busySignal(): ISignal<JupyterFrontEnd, boolean> {
return this._busySignal;
}
/**
* Returns a signal for when application changes its dirty status.
*/
get dirtySignal(): ISignal<JupyterFrontEnd, boolean> {
return this._dirtySignal;
}
/**
* Whether the application is busy.
*/
get isBusy(): boolean {
return this._busyCount > 0;
}
/**
* Whether the application is dirty.
*/
get isDirty(): boolean {
return this._dirtyCount > 0;
}
/**
* Set the application state to dirty.
*
* @returns A disposable used to clear the dirty state for the caller.
*/
setDirty(): IDisposable {
const oldDirty = this.isDirty;
this._dirtyCount++;
if (this.isDirty !== oldDirty) {
this._dirtySignal.emit(this.isDirty);
}
return new DisposableDelegate(() => {
const oldDirty = this.isDirty;
this._dirtyCount = Math.max(0, this._dirtyCount - 1);
if (this.isDirty !== oldDirty) {
this._dirtySignal.emit(this.isDirty);
}
});
}
/**
* Set the application state to busy.
*
* @returns A disposable used to clear the busy state for the caller.
*/
setBusy(): IDisposable {
const oldBusy = this.isBusy;
this._busyCount++;
if (this.isBusy !== oldBusy) {
this._busySignal.emit(this.isBusy);
}
return new DisposableDelegate(() => {
const oldBusy = this.isBusy;
this._busyCount--;
if (this.isBusy !== oldBusy) {
this._busySignal.emit(this.isBusy);
}
});
}
private _busyCount = 0;
private _busySignal: Signal<JupyterFrontEnd, boolean>;
private _dirtyCount = 0;
private _dirtySignal: Signal<JupyterFrontEnd, boolean>;
}
``` | /content/code_sandbox/packages/application/src/status.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 573 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\framework\src\Volo.Abp.AspNetCore.Mvc\Volo.Abp.AspNetCore.Mvc.csproj" />
<ProjectReference Include="..\..\..\framework\src\Volo.Abp.Autofac\Volo.Abp.Autofac.csproj" />
<ProjectReference Include="..\..\..\framework\src\Volo.Abp.EntityFrameworkCore.SqlServer\Volo.Abp.EntityFrameworkCore.SqlServer.csproj" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
``` | /content/code_sandbox/test/AbpPerfTest/AbpPerfTest.WithAbp/AbpPerfTest.WithAbp.csproj | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 185 |
```xml
import * as React from 'react';
import descriptionMd from './Description.md';
import { Slider, Provider, teamsTheme } from '@fluentui/react-northstar';
import { makeStyles, Slider as V9Slider, useId } from '@fluentui/react-components';
import { slider } from '@fluentui/react-migration-v0-v9';
const useStyles = makeStyles({
root: {
width: '100%',
},
fluid: {
...slider.fluid(),
},
});
export const Fluid = () => {
const styles = useStyles();
const id = useId('sliders');
return (
<Provider theme={teamsTheme} className={styles.root}>
<div>
<h3 id={`${id}-v0`}>v0</h3>
<Slider aria-labelledby={`${id}-v0`} fluid />
</div>
<div>
<h3 id={`${id}-v9`}>V9 With mixin</h3>
{/*
* const useStyles = makeStyles({
* fluid: {
* ...slider.fluid();
* }
* })
*/}
<V9Slider aria-labelledby={`${id}-v9`} className={styles.fluid} />
</div>
</Provider>
);
};
export default {
title: 'Migration Shims/V0/SliderMixin',
parameters: {
docs: {
description: {
component: [descriptionMd].join('\n'),
},
},
},
};
``` | /content/code_sandbox/packages/react-components/react-migration-v0-v9/stories/src/SliderMixin/index.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 316 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="path_to_url"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="@color/white"
android:paddingTop="30dp"
android:layout_height="match_parent">
</FrameLayout>
``` | /content/code_sandbox/sample/src/main/res/layout/sss.xml | xml | 2016-02-15T03:06:06 | 2024-08-15T05:21:50 | StatusBarUtil | laobie/StatusBarUtil | 8,813 | 74 |
```xml
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFF"
android:pathData="M16.049,8.696c-0.217,0.231 -0.217,0.594 0,0.825a0.539,0.539 0,0 0,0.788 0c0.868,-0.924 0.867,-2.378 -0.002,-3.301a0.539,0.539 0,0 0,-0.787 0,0.604 0.604,0 0,0 0,0.825c0.435,0.456 0.436,1.195 0.001,1.651m-1.787,-1.893c0.562,0 1.019,0.478 1.019,1.067 0,0.589 -0.457,1.067 -1.019,1.067 -0.561,0 -1.016,-0.478 -1.016,-1.067s0.455,-1.067 1.016,-1.067M13.5,2c0.701,0 1.271,0.598 1.271,1.334v2.401h-1.017V3.601H9.175v8.004h4.579v-1.601h1.016v2.401c0,0.736 -0.57,1.334 -1.271,1.334H9.429c-0.704,0 -1.273,-0.598 -1.273,-1.334V3.334C8.157,2.598 8.727,2 9.427,2Z" />
<path
android:fillColor="#FFF"
android:pathData="M1.4,21.914v-6.16h1.244v2.424h2.437v-2.424h1.244v6.16L5.081,21.914v-2.693h-2.437v2.693zM8.997,21.914v-5.118L7.169,16.796v-1.042h4.895v1.042h-1.824v5.118zM14.253,21.914v-5.118L12.425,16.796v-1.042h4.895v1.042h-1.824v5.118zM18.123,21.914v-6.16h1.996q1.135,0 1.479,0.093 0.529,0.139 0.887,0.605 0.357,0.462 0.357,1.197 0,0.567 -0.206,0.954 -0.206,0.387 -0.525,0.609 -0.315,0.219 -0.643,0.29 -0.445,0.088 -1.29,0.088h-0.811v2.324zM19.366,16.796v1.748h0.681q0.735,0 0.983,-0.097 0.248,-0.097 0.387,-0.303 0.143,-0.206 0.143,-0.479 0,-0.336 -0.198,-0.555 -0.197,-0.219 -0.5,-0.273 -0.223,-0.042 -0.895,-0.042z" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_notification_small_anim2_24dp.xml | xml | 2016-07-18T08:07:33 | 2024-08-14T13:46:53 | ScreenStream | dkrivoruchko/ScreenStream | 1,630 | 842 |
```xml
/**
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** Not all features of the VS Code API may be enabled / rolled out, so they are controlled individually.
* In OSS, they are all enabled. Interally, they may be disabled while transitioning from an older system.
* blame => inline and toggleable blame
* sidebar => VS Code SCM API, VS Code Source Control sidebar entry.
* diffview => diff commands, gutters. Requires 'sidebar'.
* autoresolve => automatically mark merge conflicts as resolved on file save
* */
export type EnabledSCMApiFeature = 'blame' | 'sidebar' | 'autoresolve';
``` | /content/code_sandbox/addons/vscode/extension/types.ts | xml | 2016-05-05T16:53:47 | 2024-08-16T19:12:02 | sapling | facebook/sapling | 5,987 | 150 |
```xml
import JsonFile from '@expo/json-file';
import spawnAsync, { SpawnOptions } from '@expo/spawn-async';
import npmPackageArg from 'npm-package-arg';
import path from 'path';
import { BasePackageManager } from './BasePackageManager';
import { findYarnOrNpmWorkspaceRoot, NPM_LOCK_FILE } from '../utils/nodeWorkspaces';
import { createPendingSpawnAsync } from '../utils/spawn';
export class NpmPackageManager extends BasePackageManager {
readonly name = 'npm';
readonly bin = 'npm';
readonly lockFile = NPM_LOCK_FILE;
workspaceRoot() {
const root = findYarnOrNpmWorkspaceRoot(this.ensureCwdDefined('workspaceRoot'));
if (root) {
return new NpmPackageManager({
...this.options,
silent: this.silent,
log: this.log,
cwd: root,
});
}
return null;
}
addAsync(namesOrFlags: string[] = []) {
if (!namesOrFlags.length) {
return this.installAsync();
}
const { flags, versioned, unversioned } = this.parsePackageSpecs(namesOrFlags);
return createPendingSpawnAsync(
() => this.updatePackageFileAsync(versioned, 'dependencies'),
() =>
!unversioned.length
? this.runAsync(['install', ...flags])
: this.runAsync(['install', '--save', ...flags, ...unversioned.map((spec) => spec.raw)])
);
}
addDevAsync(namesOrFlags: string[] = []) {
if (!namesOrFlags.length) {
return this.installAsync();
}
const { flags, versioned, unversioned } = this.parsePackageSpecs(namesOrFlags);
return createPendingSpawnAsync(
() => this.updatePackageFileAsync(versioned, 'devDependencies'),
() =>
!unversioned.length
? this.runAsync(['install', ...flags])
: this.runAsync([
'install',
'--save-dev',
...flags,
...unversioned.map((spec) => spec.raw),
])
);
}
addGlobalAsync(namesOrFlags: string[] = []) {
if (!namesOrFlags.length) {
return this.installAsync();
}
return this.runAsync(['install', '--global', ...namesOrFlags]);
}
removeAsync(namesOrFlags: string[]) {
return this.runAsync(['uninstall', ...namesOrFlags]);
}
removeDevAsync(namesOrFlags: string[]) {
return this.runAsync(['uninstall', '--save-dev', ...namesOrFlags]);
}
removeGlobalAsync(namesOrFlags: string[]) {
return this.runAsync(['uninstall', '--global', ...namesOrFlags]);
}
runBinAsync(command: string[], options: SpawnOptions = {}) {
this.log?.(`> npx ${command.join(' ')}`);
return spawnAsync('npx', command, { ...this.options, ...options });
}
/**
* Parse all package specifications from the names or flag list.
* The result from this method can be used for `.updatePackageFileAsync`.
*/
private parsePackageSpecs(namesOrFlags: string[]) {
const result: {
flags: string[];
versioned: npmPackageArg.Result[];
unversioned: npmPackageArg.Result[];
} = { flags: [], versioned: [], unversioned: [] };
namesOrFlags
.map((name) => {
if (name.trim().startsWith('-')) {
result.flags.push(name);
return null;
}
return npmPackageArg(name);
})
.forEach((spec) => {
// When using a dist-tag version of a library, we need to consider it as "unversioned".
// Doing so will install that version with `npm install --save(-dev)`, and resolve the dist-tag properly.
const hasExactSpec = !!spec && spec.rawSpec !== '' && spec.rawSpec !== '*';
if (spec && hasExactSpec && spec.type !== 'tag') {
result.versioned.push(spec);
} else if (spec) {
result.unversioned.push(spec);
}
});
return result;
}
/**
* Older npm versions have issues with mismatched nested dependencies when adding exact versions.
* This propagates as issues like mismatched `@expo/config-pugins` versions.
* As a workaround, we update the `package.json` directly and run `npm install`.
*/
private async updatePackageFileAsync(
packageSpecs: npmPackageArg.Result[],
packageType: 'dependencies' | 'devDependencies'
) {
if (!packageSpecs.length) {
return;
}
const pkgPath = path.join(this.options.cwd?.toString() || '.', 'package.json');
const pkg =
await JsonFile.readAsync<Record<typeof packageType, { [pkgName: string]: string }>>(pkgPath);
packageSpecs.forEach((spec) => {
pkg[packageType] = pkg[packageType] || {};
pkg[packageType][spec.name!] = spec.rawSpec;
});
await JsonFile.writeAsync(pkgPath, pkg, { json5: false });
}
}
``` | /content/code_sandbox/packages/@expo/package-manager/src/node/NpmPackageManager.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 1,112 |
```xml
import { IterableX } from '../iterablex.js';
import { OperatorFunction } from '../../interfaces.js';
/** @ignore */
export class BufferIterable<TSource> extends IterableX<TSource[]> {
private _source: Iterable<TSource>;
private _count: number;
private _skip: number;
constructor(source: Iterable<TSource>, count: number, skip: number) {
super();
this._source = source;
this._count = count;
this._skip = skip;
}
*[Symbol.iterator]() {
const buffers: TSource[][] = [];
let i = 0;
for (const item of this._source) {
if (i % this._skip === 0) {
buffers.push([]);
}
for (const buff of buffers) {
buff.push(item);
}
if (buffers.length > 0 && buffers[0].length === this._count) {
yield buffers.shift()!;
}
i++;
}
while (buffers.length > 0) {
yield buffers.shift()!;
}
}
}
/**
* Generates a sequence of buffers over the source sequence, with specified length and possible overlap.
* @example <caption>Creates a sequence of buffers with and without skip</caption>
* const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
*
* // Without skip
* const result = buffer(source, 5);
* const result = Ix.Iterable.from(source).buffer(5);
* for (const item of result) {
* console.log(result);
* }
* // => [0, 1, 2, 3, 4]
* // => [5, 6, 7, 8, 9]
*
* // With skip
* const result = buffer(source, 3, 4);
* const result = Ix.Iterable.from(source).buffer(3, 4);
* for (const item of result) {
* console.log(result);
* }
* // => [0, 1, 2]
* // => [4, 5, 6]
* // => [8, 9]
* @param {Iterabel<TSource>} source Source sequence
* @param {number} count Number of elements for allocated buffers.
* @param {number} [skip] Number of elements to skip between the start of consecutive buffers. If not specified, defaults
* to the count.
* @return {IterableX<TSource>[]} Sequence of buffers containing source sequence elements
*/
export function buffer<TSource>(
count: number,
skip?: number
): OperatorFunction<TSource, TSource[]> {
let s = skip;
if (s == null) {
s = count;
}
return function bufferOperatorFunction(source: Iterable<TSource>): IterableX<TSource[]> {
return new BufferIterable(source, count, s!);
};
}
``` | /content/code_sandbox/src/iterable/operators/buffer.ts | xml | 2016-02-22T20:04:19 | 2024-08-09T18:46:41 | IxJS | ReactiveX/IxJS | 1,319 | 619 |
```xml
/* eslint-disable */
//@ts-nocheck
// This functions is taken from react native web
import hash from '../useResponsiveQuery/hash';
import prefixStyles from '../react-native-web-fucntions/prefixStyles';
import normalizeValueWithProperty from './normalizeValueWithProperty';
import createReactDOMStyle from '../react-native-web-fucntions/createReactDOMStyle';
import hyphenateStyleName from '../react-native-web-fucntions/hyphenateStyleName';
type Value = Object | Array<any> | string | number;
type Style = { [key: string]: Value };
type Rule = string;
type Rules = Array<Rule>;
type RulesData = [Rules, number];
type CompiledStyle = {
//@ts-ignore
$$css: boolean;
//@ts-ignore
$$css$localize?: boolean;
[key: string]: string | Array<string>;
};
const borderTopLeftRadius = 'borderTopLeftRadius';
const borderTopRightRadius = 'borderTopRightRadius';
const borderBottomLeftRadius = 'borderBottomLeftRadius';
const borderBottomRightRadius = 'borderBottomRightRadius';
const borderLeftColor = 'borderLeftColor';
const borderLeftStyle = 'borderLeftStyle';
const borderLeftWidth = 'borderLeftWidth';
const borderRightColor = 'borderRightColor';
const borderRightStyle = 'borderRightStyle';
const borderRightWidth = 'borderRightWidth';
const right = 'right';
const marginLeft = 'marginLeft';
const marginRight = 'marginRight';
const paddingLeft = 'paddingLeft';
const paddingRight = 'paddingRight';
const left = 'left';
const PROPERTIES_VALUE: any = ['clear', 'float', 'textAlign'];
// Map of LTR property names to their BiDi equivalent.
const PROPERTIES_FLIP: { [key: string]: string } = {
[borderTopLeftRadius]: borderTopRightRadius,
[borderTopRightRadius]: borderTopLeftRadius,
[borderBottomLeftRadius]: borderBottomRightRadius,
[borderBottomRightRadius]: borderBottomLeftRadius,
[borderLeftColor]: borderRightColor,
[borderLeftStyle]: borderRightStyle,
[borderLeftWidth]: borderRightWidth,
[borderRightColor]: borderLeftColor,
[borderRightStyle]: borderLeftStyle,
[borderRightWidth]: borderLeftWidth,
[left]: right,
[marginLeft]: marginRight,
[marginRight]: marginLeft,
[paddingLeft]: paddingRight,
[paddingRight]: paddingLeft,
[right]: left,
};
// Map of I18N property names to their LTR equivalent.
const PROPERTIES_I18N: any = {
borderTopStartRadius: borderTopLeftRadius,
borderTopEndRadius: borderTopRightRadius,
borderBottomStartRadius: borderBottomLeftRadius,
borderBottomEndRadius: borderBottomRightRadius,
borderStartColor: borderLeftColor,
borderStartStyle: borderLeftStyle,
borderStartWidth: borderLeftWidth,
borderEndColor: borderRightColor,
borderEndStyle: borderRightStyle,
borderEndWidth: borderRightWidth,
end: right,
marginStart: marginLeft,
marginEnd: marginRight,
paddingStart: paddingLeft,
paddingEnd: paddingRight,
start: left,
};
type CompilerOutput = [CompiledStyle, Array<RulesData>];
const customGroup: { [key: string]: number } = {
borderColor: 2,
borderRadius: 2,
borderStyle: 2,
borderWidth: 2,
display: 2,
flex: 2,
margin: 2,
overflow: 2,
overscrollBehavior: 2,
padding: 2,
marginHorizontal: 2.1,
marginVertical: 2.1,
paddingHorizontal: 2.1,
paddingVertical: 2.1,
};
const atomicGroup = 2.2;
const cache = new Map();
export function atomic(style: Style): CompilerOutput {
//@ts-ignore
const compiledStyle: CompiledStyle = { $$css: true };
const compiledRules: any = [];
function atomicCompile(prop: any, value: any) {
const valueString = stringifyValueWithProperty(value, prop);
const cacheKey = prop + valueString;
const cachedResult = cache.get(cacheKey);
let identifier;
if (cachedResult != null) {
identifier = cachedResult[0];
compiledRules.push(cachedResult[1]);
} else {
identifier = createIdentifier('r', prop, value);
const order = customGroup[prop] || atomicGroup;
const rules = createAtomicRules(identifier, prop, value);
const orderedRules = [rules, order];
compiledRules.push(orderedRules);
cache.set(cacheKey, [identifier, orderedRules]);
}
return identifier;
}
Object.keys(style)
.sort()
.forEach((prop) => {
const value = style[prop];
if (value != null) {
let localizeableValue;
// BiDi flip values
if (PROPERTIES_VALUE.indexOf(prop) > -1) {
const left = atomicCompile(prop, 'left');
const right = atomicCompile(prop, 'right');
if (value === 'start') {
localizeableValue = [left, right];
} else if (value === 'end') {
localizeableValue = [right, left];
}
}
// BiDi flip properties
const propPolyfill = PROPERTIES_I18N[prop];
if (propPolyfill != null) {
const ltr = atomicCompile(propPolyfill, value);
const rtl = atomicCompile(PROPERTIES_FLIP[propPolyfill], value);
localizeableValue = [ltr, rtl];
}
// BiDi flip transitionProperty value
if (prop === 'transitionProperty') {
const values = Array.isArray(value) ? value : [value];
const polyfillIndices = [];
for (let i = 0; i < values.length; i++) {
const val = values[i];
if (typeof val === 'string' && PROPERTIES_I18N[val] != null) {
polyfillIndices.push(i);
}
}
if (polyfillIndices.length > 0) {
const ltrPolyfillValues = [...values];
const rtlPolyfillValues = [...values];
polyfillIndices.forEach((i) => {
const ltrVal = ltrPolyfillValues[i];
if (typeof ltrVal === 'string') {
const ltrPolyfill = PROPERTIES_I18N[ltrVal];
const rtlPolyfill = PROPERTIES_FLIP[ltrPolyfill];
ltrPolyfillValues[i] = ltrPolyfill;
rtlPolyfillValues[i] = rtlPolyfill;
const ltr = atomicCompile(prop, ltrPolyfillValues);
const rtl = atomicCompile(prop, rtlPolyfillValues);
localizeableValue = [ltr, rtl];
}
});
}
}
if (localizeableValue == null) {
localizeableValue = atomicCompile(prop, value);
} else {
compiledStyle['$$css$localize'] = true;
}
compiledStyle[prop] = localizeableValue;
}
});
return [compiledStyle, compiledRules];
}
/**
* Create a value string that normalizes different input values with a common
* output.
*/
export function stringifyValueWithProperty(
value: Value,
property?: string
): string {
// e.g., 0 => '0px', 'black' => 'rgba(0,0,0,1)'
const normalizedValue = normalizeValueWithProperty(value, property);
return typeof normalizedValue !== 'string'
? JSON.stringify(normalizedValue || '')
: normalizedValue;
}
/**
* An identifier is associated with a unique set of styles.
*/
function createIdentifier(prefix: string, name: string, value: Value): string {
const hashedString = hash(name + stringifyValueWithProperty(value, name));
return process.env.NODE_ENV !== 'production'
? `${prefix}-${name}-${hashedString}`
: `${prefix}-${hashedString}`;
}
/**
* Create the Atomic CSS rules needed for a given StyleSheet rule.
* Translates StyleSheet declarations to CSS.
*/
function createAtomicRules(
identifier: string,
property: any,
value: any
): Rules {
const rules = [];
const selector = `.${identifier}`;
// Handle non-standard properties and object values that require multiple
// CSS rules to be created.
switch (property) {
case 'animationKeyframes': {
const [animationNames, keyframesRules] = processKeyframesValue(value);
const block = createDeclarationBlock({
animationName: animationNames.join(','),
});
rules.push(`${selector}${block}`, ...keyframesRules);
break;
}
// Equivalent to using '::placeholder'
case 'placeholderTextColor': {
const block = createDeclarationBlock({ color: value, opacity: 1 });
rules.push(
`${selector}::-webkit-input-placeholder${block}`,
`${selector}::-moz-placeholder${block}`,
`${selector}:-ms-input-placeholder${block}`,
`${selector}::placeholder${block}`
);
break;
}
// Polyfill for additional 'pointer-events' values
// See d13f78622b233a0afc0c7a200c0a0792c8ca9e58
case 'pointerEvents': {
let finalValue = value;
if (value === 'auto' || value === 'box-only') {
finalValue = 'auto!important';
if (value === 'box-only') {
const block = createDeclarationBlock({ pointerEvents: 'none' });
rules.push(`${selector}>*${block}`);
}
} else if (value === 'none' || value === 'box-none') {
finalValue = 'none!important';
if (value === 'box-none') {
const block = createDeclarationBlock({ pointerEvents: 'auto' });
rules.push(`${selector}>*${block}`);
}
}
const block = createDeclarationBlock({ pointerEvents: finalValue });
rules.push(`${selector}${block}`);
break;
}
// Polyfill for draft spec
// path_to_url
case 'scrollbarWidth': {
if (value === 'none') {
rules.push(`${selector}::-webkit-scrollbar{display:none}`);
}
const block = createDeclarationBlock({ scrollbarWidth: value });
rules.push(`${selector}${block}`);
break;
}
default: {
const block = createDeclarationBlock({ [property]: value });
rules.push(`${selector}${block}`);
break;
}
}
return rules;
}
/**
* Creates a CSS declaration block from a StyleSheet object.
*/
function createDeclarationBlock(style: Style): string {
const domStyle: any = prefixStyles(createReactDOMStyle(style));
const declarationsString = Object.keys(domStyle)
.map((property) => {
const value = domStyle[property];
const prop = hyphenateStyleName(property);
// The prefixer may return an array of values:
// { display: [ '-webkit-flex', 'flex' ] }
// to represent "fallback" declarations
// { display: -webkit-flex; display: flex; }
if (Array.isArray(value)) {
return value.map((v) => `${prop}:${v}`).join(';');
} else {
return `${prop}:${value}`;
}
})
// Once properties are hyphenated, this will put the vendor
// prefixed and short-form properties first in the list.
.sort()
.join(';');
return `{${declarationsString};}`;
}
/**
* Create CSS keyframes rules and names from a StyleSheet keyframes object.
*/
function processKeyframesValue(keyframesValue: any) {
if (typeof keyframesValue === 'number') {
throw new Error(`Invalid CSS keyframes type: ${typeof keyframesValue}`);
}
const animationNames: any = [];
const rules: any = [];
const value = Array.isArray(keyframesValue)
? keyframesValue
: [keyframesValue];
value.forEach((keyframes) => {
if (typeof keyframes === 'string') {
// Support external animation libraries (identifiers only)
animationNames.push(keyframes);
} else {
// Create rules for each of the keyframes
const [identifier, keyframesRules] = createKeyframes(keyframes);
animationNames.push(identifier);
rules.push(...keyframesRules);
}
});
return [animationNames, rules];
}
/**
* Create individual CSS keyframes rules.
*/
function createKeyframes(keyframes: any): [string, Rules] {
const prefixes = ['-webkit-', ''];
const identifier = createIdentifier('r', 'animation', keyframes);
const steps =
'{' +
Object.keys(keyframes)
.map((stepName) => {
const rule = keyframes[stepName];
const block = createDeclarationBlock(rule);
return `${stepName}${block}`;
})
.join('') +
'}';
const rules = prefixes.map((prefix) => {
return `@${prefix}keyframes ${identifier}${steps}`;
});
return [identifier, rules];
}
``` | /content/code_sandbox/src/utils/react-native-web-fucntions/atomic.ts | xml | 2016-04-15T11:37:23 | 2024-08-14T16:16:44 | NativeBase | GeekyAnts/NativeBase | 20,132 | 2,805 |
```xml
import { SPFI } from "@pnp/sp";
import { SearchResults } from "@pnp/sp/search";
import {
Icon,
Shimmer,
ShimmerElementType,
} from "office-ui-fabric-react";
import * as React from "react";
import { useEffect, useState } from "react";
import { ILink } from "../utils/ILink";
interface IReactAssociatedSitesLinksProps {
sp: SPFI;
}
const ReactAssociatedSitesLinks = (
props: IReactAssociatedSitesLinksProps
): JSX.Element => {
const shimmerElements = [
{ type: ShimmerElementType.line, width: 255.67, height: 66 },
{ type: ShimmerElementType.gap, width: 12 },
{ type: ShimmerElementType.line, width: 255.67, height: 66 },
{ type: ShimmerElementType.gap, width: 12 },
{ type: ShimmerElementType.line, width: 255.67, height: 66 },
];
const [isDataLeaded, setIsDataLoded] = useState(false);
const [links, setLinks] = useState<ILink[]>([]);
useEffect(() => {
getAssociatedSitesLinks()
.then((result) => {
setLinks(result);
setIsDataLoded(true);
})
.catch((error) => {
console.error(error);
alert("Failed on getting associated sites links.");
});
}, []);
async function getAssociatedSitesLinks(): Promise<ILink[]> {
const site = await props.sp.site();
const searchResults: SearchResults = await props.sp.search(
`DepartmentId=${site.Id} contentclass:sts_site -SiteId:${site.Id}`
);
return searchResults.PrimarySearchResults.map(
(result): ILink => ({
title: result.Title,
url: result.Path,
logoUrl: result.SiteLogo,
})
);
}
return (
<>
{isDataLeaded ? (
<section className={`tw-flex tw-gap-3 tw-flex-wrap`}>
{links.map((link) => (
<a
key={link.url}
className={`
tw-border tw-border-solid tw-border-[#dddddd] tw-text-lg tw-p-3 tw-no-underline
tw-flex tw-gap-4 tw-items-center tw-basis-[32%] hover:tw-bg-gray-100 tw-text-inherit
tw-h-[66px] tw-box-border
`}
href={link.url}
>
{link.logoUrl ? (
<img src={link.logoUrl} className="tw-w-10" alt="logo" />
) : (
<Icon className="tw-text-lg" iconName="Globe" />
)}
{link.title}
</a>
))}
</section>
) : (
<Shimmer shimmerElements={shimmerElements} />
)}
</>
);
};
export { IReactAssociatedSitesLinksProps, ReactAssociatedSitesLinks };
``` | /content/code_sandbox/samples/react-associated-sites-links/src/webparts/reactAssociatedSitesLinks/components/ReactAssociatedSitesLinks.tsx | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 638 |
```xml
import React, { useState } from "react";
import { useSelector } from "react-redux";
import { getIsWorkspaceMode } from "store/features/teams/selectors";
import { ShareFromPrivate } from "./ShareFromPrivate";
import { ShareFromWorkspace } from "./ShareFromWorkspace";
import { PostSharing } from "./PostSharing";
interface ShareInWorkspaceProps {
selectedRules: string[];
toggleModal: () => void;
onRulesShared?: () => void;
}
export const ShareInWorkspaces: React.FC<ShareInWorkspaceProps> = ({
selectedRules,
toggleModal,
onRulesShared = () => {},
}) => {
const isWorkspaceMode = useSelector(getIsWorkspaceMode);
const [postShareViewData, setPostShareViewData] = useState(null);
return (
<div className="sharing-modal-body share-in-workspaces-wrapper">
{postShareViewData ? (
<PostSharing
postShareViewData={postShareViewData}
setPostShareViewData={setPostShareViewData}
toggleModal={toggleModal}
/>
) : (
<>
{isWorkspaceMode ? (
<ShareFromWorkspace
selectedRules={selectedRules}
setPostShareViewData={setPostShareViewData}
onRulesShared={onRulesShared}
/>
) : (
<ShareFromPrivate
selectedRules={selectedRules}
setPostShareViewData={setPostShareViewData}
onRulesShared={onRulesShared}
/>
)}
</>
)}
</div>
);
};
``` | /content/code_sandbox/app/src/components/common/SharingModal/Workspaces/index.tsx | xml | 2016-12-01T04:36:06 | 2024-08-16T19:12:19 | requestly | requestly/requestly | 2,121 | 333 |
```xml
<?xml version="1.0"?>
<project xsi:schemaLocation="path_to_url path_to_url" xmlns="path_to_url" xmlns:xsi="path_to_url">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.roncoo.pay</groupId>
<artifactId>roncoo-pay</artifactId>
<version>2.1.2-SNAPSHOT</version>
</parent>
<groupId>com.roncoo.pay.service</groupId>
<artifactId>roncoo-pay-service</artifactId>
<name>roncoo-pay-service</name>
<description></description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>com.roncoo.pay.common</groupId>
<artifactId>roncoo-pay-common-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
</dependency>
</dependencies>
<build>
<finalName>${project.name}</finalName>
</build>
</project>
``` | /content/code_sandbox/roncoo-pay-service/pom.xml | xml | 2016-07-21T02:46:06 | 2024-08-16T02:04:09 | roncoo-pay | roncoo/roncoo-pay | 4,801 | 673 |
```xml
import * as ts from 'typescript';
import {updateModuleSpecifier, updateNamedImport} from './import-operations';
describe('import operations', () => {
describe('updateModuleSpecifier', () => {
function runUpdateModuleSpecifierTest(
description: string,
opts: {old: string; new: string},
): void {
const node = createNode(opts.old, ts.SyntaxKind.ImportDeclaration) as ts.ImportDeclaration;
const update = updateModuleSpecifier(node!, {moduleSpecifier: 'new-module-name'});
const newImport = update?.updateFn(opts.old);
expect(newImport).withContext(description).toBe(opts.new);
}
it('updates the module specifier of import declarations', () => {
runUpdateModuleSpecifierTest('default export', {
old: `import defaultExport from 'old-module-name';`,
new: `import defaultExport from 'new-module-name';`,
});
runUpdateModuleSpecifierTest('namespace import', {
old: `import * as name from 'old-module-name';`,
new: `import * as name from 'new-module-name';`,
});
runUpdateModuleSpecifierTest('named import', {
old: `import { export1 } from 'old-module-name';`,
new: `import { export1 } from 'new-module-name';`,
});
runUpdateModuleSpecifierTest('aliased named import', {
old: `import { export1 as alias1 } from 'old-module-name';`,
new: `import { export1 as alias1 } from 'new-module-name';`,
});
runUpdateModuleSpecifierTest('multiple named import', {
old: `import { export1, export2 } from 'old-module-name';`,
new: `import { export1, export2 } from 'new-module-name';`,
});
runUpdateModuleSpecifierTest('multiple named import w/ alias', {
old: `import { export1, export2 as alias2 } from 'old-module-name';`,
new: `import { export1, export2 as alias2 } from 'new-module-name';`,
});
});
});
describe('updateNamedExport', () => {
function runUpdateNamedExportTest(
description: string,
opts: {
oldFile: string;
newFile: string;
oldExport: string;
newExport: string;
},
): void {
const node = createNode(opts.oldFile, ts.SyntaxKind.NamedImports) as ts.NamedImports;
const newImport = updateNamedImport(node, {
oldExport: opts.oldExport,
newExport: opts.newExport,
})?.updateFn(opts.oldFile);
expect(newImport).withContext(description).toBe(opts.newFile);
}
it('updates the named exports of import declarations', () => {
runUpdateNamedExportTest('named binding', {
oldExport: 'oldExport',
newExport: 'newExport',
oldFile: `import { oldExport } from 'module-name';`,
newFile: `import { newExport } from 'module-name';`,
});
runUpdateNamedExportTest('aliased named binding', {
oldExport: 'oldExport',
newExport: 'newExport',
oldFile: `import { oldExport as alias } from 'module-name';`,
newFile: `import { newExport as alias } from 'module-name';`,
});
runUpdateNamedExportTest('multiple named bindings', {
oldExport: 'oldExport1',
newExport: 'newExport1',
oldFile: `import { oldExport1, export2 } from 'module-name';`,
newFile: `import { newExport1, export2 } from 'module-name';`,
});
runUpdateNamedExportTest('multiple named bindings w/ alias', {
oldExport: 'oldExport2',
newExport: 'newExport2',
oldFile: `import { export1, oldExport2 as alias2 } from 'module-name';`,
newFile: `import { export1, newExport2 as alias2 } from 'module-name';`,
});
});
});
});
function createSourceFile(text: string): ts.SourceFile {
return ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest);
}
function visitNodes(node: ts.SourceFile | ts.Node, visitFn: (node: ts.Node) => void): void {
node.forEachChild(child => {
visitFn(child);
visitNodes(child, visitFn);
});
}
function getNodeByKind(file: ts.SourceFile, kind: ts.SyntaxKind): ts.Node | null {
let node: ts.Node | null = null;
visitNodes(file, (_node: ts.Node) => {
if (_node.kind === kind) {
node = _node;
}
});
return node;
}
function createNode(text: string, kind: ts.SyntaxKind): ts.Node | null {
return getNodeByKind(createSourceFile(text), kind);
}
``` | /content/code_sandbox/src/material/schematics/migration-utilities/typescript/import-operations.spec.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 1,060 |
```xml
import { join } from 'path';
import { ensureDir } from 'fs-extra';
import { createSymlink } from '../utils/symlink';
import {
writeHandler,
writeVCConfig,
copyFunctionLibs,
copyHTMLFiles,
writePrerenderConfig,
} from '../handlers/build';
import type { GatsbyFunction, GatsbyPage } from '../schemas';
/**
* Gatsby SSR/DSG on Vercel is enabled through Vercel Serverless Functions.
* This plugin creates one Serverless Function called `_ssr.func` that is used by SSR and DSG pages through symlinks.
* DSG is enabled through prerender functions.
*/
export async function createServerlessFunctions(
ssrRoutes: GatsbyPage[],
prefix?: string
) {
let functionName: string;
let functionDir: string;
const handlerFile = join(__dirname, '../templates/ssr-handler.js');
await Promise.all(
ssrRoutes.map(async (page, index) => {
let pathName = page.path;
// HTML renderer
const ssrPath = join(prefix ?? '', pathName, 'index.html');
if (index === 0) {
// For the first page, create the SSR Serverless Function
functionName = `${ssrPath}.func`;
functionDir = join('.vercel/output/functions', functionName);
await ensureDir(functionDir);
await Promise.all([
writeHandler({ outDir: functionDir, handlerFile, prefix }),
copyFunctionLibs({ functionDir }),
copyHTMLFiles({ functionDir }),
writeVCConfig({ functionDir }),
]);
} else {
// If it's not the first page, then symlink to the first function
await createSymlink(ssrPath, functionName);
}
if (page.mode === 'DSG') {
writePrerenderConfig(
join(
'.vercel',
'output',
'functions',
`${ssrPath}.prerender-config.json`
),
index + 1
);
}
// page-data renderer
if (!pathName || pathName === '/') {
pathName = 'index';
}
const pageDataPath = join(
prefix ?? '',
'page-data',
pathName,
'page-data.json'
);
await createSymlink(pageDataPath, functionName);
if (page.mode === 'DSG') {
writePrerenderConfig(
join(
'.vercel',
'output',
'functions',
`${pageDataPath}.prerender-config.json`
),
index + 1
);
}
})
);
}
export async function createAPIRoutes(
functions: GatsbyFunction[],
prefix?: string
) {
const apiDir = join('.vercel', 'output', 'functions', 'api', prefix ?? '');
await ensureDir(apiDir);
await Promise.allSettled(
functions.map(async (func: GatsbyFunction) => {
const apiRouteDir = `${apiDir}/${func.functionRoute}.func`;
const handlerFile = func.originalAbsoluteFilePath;
await ensureDir(apiRouteDir);
await Promise.all([
writeHandler({ outDir: apiRouteDir, handlerFile }),
writeVCConfig({ functionDir: apiRouteDir }),
]);
})
);
}
``` | /content/code_sandbox/packages/gatsby-plugin-vercel-builder/src/helpers/functions.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 708 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const ToggleBorderIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M1582 558q96 0 181 37t148 100 100 148 37 181q0 96-37 181t-100 148-148 100-181 37H466q-96 0-181-37t-148-100-100-148-37-181q0-96 37-181t100-148 148-100 181-37h1116zm0 838q77 0 145-29t118-80 80-118 30-145q0-77-29-144t-80-118-119-80-145-30H466q-77 0-145 29t-118 80-80 118-30 145q0 77 29 144t80 118 119 80 145 30h1116z" />
</svg>
),
displayName: 'ToggleBorderIcon',
});
export default ToggleBorderIcon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/ToggleBorderIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 282 |
```xml
export { UntrustedCertificate } from './untrusted-certificate'
``` | /content/code_sandbox/app/src/ui/untrusted-certificate/index.ts | xml | 2016-05-11T15:59:00 | 2024-08-16T17:00:41 | desktop | desktop/desktop | 19,544 | 14 |
```xml
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at path_to_url
*/
import * as ts from 'typescript';
import {FileSystem} from '../file-system';
// We use TypeScript's native `ts.matchFiles` utility for the virtual file system
// hosts, as that function implements complex logic for matching files with respect
// to root directory, extensions, excludes, includes etc. The function is currently
// internal but we can use it as the API most likely will not change any time soon,
// nor does it seem like this is being made public any time soon.
// Related issue for tracking: path_to_url
// path_to_url#L6192
declare module 'typescript' {
export interface FileSystemEntries {
readonly files: readonly string[];
readonly directories: readonly string[];
}
export const matchFiles:
| undefined
| ((
path: string,
extensions: readonly string[] | undefined,
excludes: readonly string[] | undefined,
includes: readonly string[] | undefined,
useCaseSensitiveFileNames: boolean,
currentDirectory: string,
depth: number | undefined,
getFileSystemEntries: (path: string) => FileSystemEntries,
realpath: (path: string) => string,
directoryExists: (path: string) => boolean,
) => string[]);
}
/**
* Implementation of a TypeScript parse config host that relies fully on
* a given virtual file system.
*/
export class FileSystemHost implements ts.ParseConfigHost {
useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
constructor(private _fileSystem: FileSystem) {}
fileExists(path: string): boolean {
return this._fileSystem.fileExists(this._fileSystem.resolve(path));
}
readFile(path: string): string | undefined {
const content = this._fileSystem.read(this._fileSystem.resolve(path));
if (content === null) {
return undefined;
}
// Strip BOM as otherwise TSC methods (e.g. "getWidth") will return an offset which
// which breaks the CLI UpdateRecorder. path_to_url
return content.replace(/^\uFEFF/, '');
}
readDirectory(
rootDir: string,
extensions: string[],
excludes: string[] | undefined,
includes: string[],
depth?: number,
): string[] {
if (ts.matchFiles === undefined) {
throw Error(
'Unable to read directory in virtual file system host. This means that ' +
'TypeScript changed its file matching internals.\n\nPlease consider downgrading your ' +
'TypeScript version, and report an issue in the Angular Components repository.',
);
}
return ts.matchFiles(
rootDir,
extensions,
extensions,
includes,
this.useCaseSensitiveFileNames,
'/',
depth,
p => this._getFileSystemEntries(p),
p => this._fileSystem.resolve(p),
p => this._fileSystem.directoryExists(this._fileSystem.resolve(p)),
);
}
private _getFileSystemEntries(path: string): ts.FileSystemEntries {
return this._fileSystem.readDirectory(this._fileSystem.resolve(path));
}
}
/**
* Creates a TypeScript compiler host that fully relies fully on the given
* virtual file system. i.e. no interactions with the working directory.
*/
export function createFileSystemCompilerHost(
options: ts.CompilerOptions,
fileSystem: FileSystem,
): ts.CompilerHost {
const host = ts.createCompilerHost(options, true);
const virtualHost = new FileSystemHost(fileSystem);
host.readFile = virtualHost.readFile.bind(virtualHost);
host.readDirectory = virtualHost.readDirectory.bind(virtualHost);
host.fileExists = virtualHost.fileExists.bind(virtualHost);
host.directoryExists = dirPath => fileSystem.directoryExists(fileSystem.resolve(dirPath));
host.getCurrentDirectory = () => '/';
host.getCanonicalFileName = p => fileSystem.resolve(p);
return host;
}
/** Creates a format diagnostic host that works with the given file system. */
export function createFormatDiagnosticHost(fileSystem: FileSystem): ts.FormatDiagnosticsHost {
return {
getCanonicalFileName: p => fileSystem.resolve(p),
getCurrentDirectory: () => '/',
getNewLine: () => '\n',
};
}
``` | /content/code_sandbox/src/cdk/schematics/update-tool/utils/virtual-host.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 908 |
```xml
// tslint:disable
import { configure } from "enzyme"
import * as Adapter from "enzyme-adapter-react-16"
// React 16 Enzyme adapter
configure({ adapter: new Adapter() })
// Make Enzyme functions available in all test files without importing
// ;(global as any).shallow = shallow
// ;(global as any).render = render
// ;(global as any).mount = mount
``` | /content/code_sandbox/ui-tests/jestsetup.ts | xml | 2016-11-16T14:42:55 | 2024-08-14T11:48:05 | oni | onivim/oni | 11,355 | 91 |
```xml
import type { RequestConfig } from '../../common/types';
import type { SignatureParams } from '../types';
import { request } from '../../utils/request';
export const createWalletSignature = (
config: RequestConfig,
{ walletId, role, index, data }: SignatureParams
): Promise<Buffer> =>
request(
{
method: 'POST',
path: `/v2/wallets/${walletId}/signatures/${role}/${index}`,
...config,
},
{},
data,
{
isOctetStreamResponse: true,
}
);
``` | /content/code_sandbox/source/renderer/app/api/voting/requests/createWalletSignature.ts | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 121 |
```xml
import { Spinner } from '@fluentui/react-components';
import descriptionMd from './SpinnerDescription.md';
import bestPracticesMd from './SpinnerBestPractices.md';
export { Default } from './SpinnerDefault.stories';
export { Appearance } from './SpinnerAppearance.stories';
export { Labels } from './SpinnerLabel.stories';
export { Size } from './SpinnerSize.stories';
export default {
title: 'Components/Spinner',
component: Spinner,
parameters: {
docs: {
description: {
component: [descriptionMd, bestPracticesMd].join('\n'),
},
},
},
};
``` | /content/code_sandbox/packages/react-components/react-spinner/stories/src/Spinner/index.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 130 |
```xml
import { TestBed, inject } from '@angular/core/testing';
import { EndpointsService } from './endpoints.service';
describe('EndpointsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [EndpointsService],
});
});
it('should be created', inject([EndpointsService], (service: EndpointsService) => {
expect(service).toBeTruthy();
}));
});
``` | /content/code_sandbox/frontend_v2/src/app/services/endpoints.service.spec.ts | xml | 2016-10-21T00:51:45 | 2024-08-16T14:41:56 | EvalAI | Cloud-CV/EvalAI | 1,736 | 83 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
export {default as Button} from './Button';
``` | /content/code_sandbox/optimize/client/src/modules/components/Button/index.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 38 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="path_to_url"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff000000">
<com.github.chrisbanes.photoview.PhotoView
android:id="@+id/zoom_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="@+id/view_mask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBannerMask"
android:visibility="visible" />
<ProgressBar
android:id="@+id/loading"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center" />
</FrameLayout>
``` | /content/code_sandbox/app/src/main/res/layout/viewpager_very_image.xml | xml | 2016-11-20T11:59:25 | 2024-08-14T13:24:02 | CloudReader | youlookwhat/CloudReader | 4,933 | 191 |
```xml
<Project>
<ItemGroup>
<TestApkInstrumentation Include="xamarin.android.runtimetests.NUnitInstrumentation">
<Package>$(_MonoAndroidTestPackage)</Package>
<ResultsPath>$(OutputPath)TestResult-$(_MonoAndroidTestPackage).xml</ResultsPath>
</TestApkInstrumentation>
<TestApkPermission Include="READ_EXTERNAL_STORAGE">
<Package>$(_MonoAndroidTestPackage)</Package>
</TestApkPermission>
<TestApkPermission Include="WRITE_EXTERNAL_STORAGE">
<Package>$(_MonoAndroidTestPackage)</Package>
</TestApkPermission>
</ItemGroup>
<Target Name="BuildNativeLibs"
BeforeTargets="CoreBuild"
DependsOnTargets="AndroidPrepareForBuild"
Inputs="$(MSBuildThisFileDirectory)jni\reuse-threads.c;$(MSBuildThisFileDirectory)jni\Android.mk"
Outputs="@(AndroidNativeLibrary)">
<Error Text="Could not locate Android NDK." Condition="!Exists ('$(NdkBuildPath)')" />
<Exec Command=""$(NdkBuildPath)"" WorkingDirectory="$(MSBuildThisFileDirectory)"/>
</Target>
</Project>
``` | /content/code_sandbox/tests/Mono.Android-Tests/Directory.Build.targets | xml | 2016-03-30T15:37:14 | 2024-08-16T19:22:13 | android | dotnet/android | 1,905 | 260 |
```xml
import {
Column,
Entity,
PrimaryGeneratedColumn,
TableInheritance,
} from "../../../../src"
@Entity("content")
@TableInheritance({ column: { type: "varchar", name: "type" } })
export class Content {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
}
``` | /content/code_sandbox/test/github-issues/7558/entity/Content.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 72 |
```xml
/**
* @license
*
* 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.
*/
/**
* @file Facilities for drawing spheres in WebGL
*/
import { RefCounted } from "#src/util/disposable.js";
import type { Buffer } from "#src/webgl/buffer.js";
import { getMemoizedBuffer } from "#src/webgl/buffer.js";
import type { GL } from "#src/webgl/context.js";
import type { ShaderBuilder, ShaderProgram } from "#src/webgl/shader.js";
export function getSphereVertexArray(
latitudeBands: number,
longitudeBands: number,
) {
const result = new Float32Array(
(latitudeBands + 1) * (longitudeBands + 1) * 3,
);
let i = 0;
for (let latIndex = 0; latIndex <= latitudeBands; ++latIndex) {
const theta = (latIndex * Math.PI) / latitudeBands;
const sinTheta = Math.sin(theta);
const cosTheta = Math.cos(theta);
for (let lonIndex = 0; lonIndex <= longitudeBands; ++lonIndex) {
const phi = (lonIndex * 2 * Math.PI) / longitudeBands;
const sinPhi = Math.sin(phi);
const cosPhi = Math.cos(phi);
result[i++] = cosPhi * sinTheta; // x
result[i++] = cosTheta; // y
result[i++] = sinPhi * sinTheta; // z
}
}
return result;
}
export function getSphereIndexArray(
latitudeBands: number,
longitudeBands: number,
) {
const result = new Uint16Array(latitudeBands * longitudeBands * 6);
let i = 0;
for (let latIndex = 0; latIndex < latitudeBands; latIndex++) {
for (let lonIndex = 0; lonIndex < longitudeBands; lonIndex++) {
const first = latIndex * (longitudeBands + 1) + lonIndex;
const second = first + longitudeBands + 1;
result[i++] = first;
result[i++] = second;
result[i++] = first + 1;
result[i++] = second;
result[i++] = second + 1;
result[i++] = first + 1;
}
}
return result;
}
export class SphereRenderHelper extends RefCounted {
private vertexBuffer: Buffer;
private indexBuffer: Buffer;
private numIndices: number;
constructor(gl: GL, latitudeBands: number, longitudeBands: number) {
super();
this.vertexBuffer = this.registerDisposer(
getMemoizedBuffer(
gl,
WebGL2RenderingContext.ARRAY_BUFFER,
getSphereVertexArray,
latitudeBands,
longitudeBands,
),
).value;
this.indexBuffer = this.registerDisposer(
getMemoizedBuffer(
gl,
WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER,
getSphereIndexArray,
latitudeBands,
longitudeBands,
),
).value;
this.numIndices = latitudeBands * longitudeBands * 6;
}
defineShader(builder: ShaderBuilder) {
builder.addAttribute("highp vec3", "aSphereVertex");
builder.addVarying("highp float", "vLightingFactor");
// projectionMatrix = cameraMatrix * modelViewMat
// normalTransformMatrix = (modelViewMat^{-1})^T
// eff modelViewMat = modelViewMat * scalMat(radii)
// normalTransformMatrix = (modelViewMat * scalMat)^{-1}^T
// = (scalMat^{-1} * modelViewMat^{-1})^T
// = modelViewMat^{-1}^T * (scalMat^{-1})^T
builder.addVertexCode(`
void emitSphere(mat4 projectionMatrix, mat4 normalTransformMatrix, vec3 centerPosition, vec3 radii, vec4 lightDirection) {
vec3 vertexPosition = aSphereVertex * radii + centerPosition;
gl_Position = projectionMatrix * vec4(vertexPosition, 1.0);
vec3 normal = normalize((normalTransformMatrix * vec4(aSphereVertex / max(radii, 1e-6), 0.0)).xyz);
vLightingFactor = abs(dot(normal, uLightDirection.xyz)) + uLightDirection.w;
}
`);
}
draw(shader: ShaderProgram, numInstances: number) {
const aSphereVertex = shader.attribute("aSphereVertex");
this.vertexBuffer.bindToVertexAttrib(
aSphereVertex,
/*components=*/ 3,
/*attributeType=*/ WebGL2RenderingContext.FLOAT,
/*normalized=*/ false,
);
this.indexBuffer.bind();
shader.gl.drawElementsInstanced(
WebGL2RenderingContext.TRIANGLES,
this.numIndices,
WebGL2RenderingContext.UNSIGNED_SHORT,
/*offset=*/ 0,
numInstances,
);
shader.gl.disableVertexAttribArray(aSphereVertex);
}
}
``` | /content/code_sandbox/src/webgl/spheres.ts | xml | 2016-05-27T02:37:25 | 2024-08-16T07:24:25 | neuroglancer | google/neuroglancer | 1,045 | 1,109 |
```xml
import { global as globalThis } from '@storybook/global';
// FIXME: do this using basic React functions for multi-framework
// once sandbox linking is working
//
// import { createElement } from 'react';
// import { Title, Primary } from '@storybook/addon-docs';
//
// const Override = () =>
// createElement('div', { style: { border: '10px solid green', padding: '100px' } }, [
// createElement(Title),
// createElement(Primary),
// ]);
const Override = () => 'overridden';
export default {
component: globalThis.Components.Button,
tags: ['autodocs'],
args: { label: 'Click Me!' },
parameters: {
chromatic: { disable: true },
docs: { page: Override },
},
};
export const Basic = {};
``` | /content/code_sandbox/code/addons/docs/template/stories/docspage/override.stories.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 176 |
```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.
*/
import bifurcateEntries = require( './index' );
// TESTS //
// The function returns group results...
{
const x = [ 1, 2, 3 ];
const f = [ 0, 1, 0 ];
bifurcateEntries( x, f ); // $ExpectType Results<number>
}
// The compiler throws an error if the function is provided a first argument which is not an array...
{
const f = [ 0, 1, 0 ];
bifurcateEntries( 5, f ); // $ExpectError
bifurcateEntries( true, f ); // $ExpectError
bifurcateEntries( false, f ); // $ExpectError
bifurcateEntries( null, f ); // $ExpectError
bifurcateEntries( void 0, f ); // $ExpectError
bifurcateEntries( {}, f ); // $ExpectError
bifurcateEntries( ( x: number ): number => x, f ); // $ExpectError
}
// The compiler throws an error if the function is provided a second argument which is not an array...
{
const x = [ 1, 2, 3 ];
bifurcateEntries( x, 5 ); // $ExpectError
bifurcateEntries( x, true ); // $ExpectError
bifurcateEntries( x, false ); // $ExpectError
bifurcateEntries( x, null ); // $ExpectError
bifurcateEntries( x, void 0 ); // $ExpectError
bifurcateEntries( x, {} ); // $ExpectError
bifurcateEntries( x, ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function is provided an unsupported number of arguments...
{
const x = [ 1, 2, 3 ];
const f = [ 0, 1, 0 ];
bifurcateEntries(); // $ExpectError
bifurcateEntries( x ); // $ExpectError
bifurcateEntries( x, f, {} ); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/array/base/bifurcate-entries/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 503 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ 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.
-->
<sql-cases>
<sql-case id="create_trigger" value="CREATE TRIGGER reminder1 ON Sales.Customer AFTER INSERT, UPDATE AS INSERT INTO SalesPersonQuotaHistory VALUES(t1, 100)" db-types="SQLServer" />
<sql-case id="create_trigger_with_database_scoped" value="CREATE TRIGGER ddl_trig_database ON ALL SERVER AFTER INSERT AS SELECT EVENTDATA()" db-types="SQLServer" />
<sql-case id="create_trigger_with_create_view" value="CREATE TRIGGER tr1 BEFORE INSERT ON t1 FOR EACH ROW BEGIN create view v1 as select 1; END" db-types="MySQL" />
<sql-case id="create_trigger_with_dml_event_clause" value="CREATE TRIGGER scott.emp_permit_changes BEFORE DELETE OR INSERT OR UPDATE ON scott.emp BEGIN IF (IS_SERVERERROR (1017)) THEN NULL; ELSE NULL; END IF; END;" db-types="Oracle" />
<sql-case id="create_trigger_with_body" value="CREATE TRIGGER log_errors AFTER SERVERERROR ON DATABASE BEGIN IF (IS_SERVERERROR (1017)) THEN NULL; ELSE NULL; END IF; END;" db-types="Oracle" />
<sql-case id="create_trigger_with_execute_immediate_statement" value="CREATE TRIGGER adg_logon_sync_trigger AFTER LOGON ON user.schema begin if (SYS_CONTEXT('USERENV', 'DATABASE_ROLE') IN ('PHYSICAL STANDBY')) then execute immediate 'alter session sync with primary'; end if; end;" db-types="Oracle" />
<sql-case id="create_trigger_with_assignment_statement" value="CREATE TRIGGER Contacts_BI BEFORE INSERT ON Contacts FOR EACH ROW BEGIN :NEW.ID := Contacts_Seq.NEXTVAL; END;" db-types="Oracle" />
<sql-case id="create_trigger_with_logon" value="CREATE OR REPLACE TRIGGER check_user AFTER LOGON ON DATABASE BEGIN check_user; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR (-20000, 'Unexpected error: '|| DBMS_Utility.Format_Error_Stack); END;" db-types="Oracle" />
<sql-case id="create_trigger_with_cascade_1" value="CREATE OR REPLACE TRIGGER dept_cascade3 AFTER UPDATE OF Deptno ON dept BEGIN UPDATE emp SET Update_id = NULL WHERE Update_id = Integritypackage.Updateseq; END;" db-types="Oracle" />
<sql-case id="create_trigger_with_cascade_2" value="CREATE OR REPLACE TRIGGER dept_del_cascade AFTER DELETE ON dept FOR EACH ROW BEGIN DELETE FROM emp WHERE emp.Deptno = :OLD.Deptno; END;" db-types="Oracle" />
<sql-case id="create_trigger_with_cascade_3" value="CREATE OR REPLACE TRIGGER dept_cascade2 AFTER DELETE OR UPDATE OF Deptno ON dept FOR EACH ROW BEGIN IF UPDATING THEN UPDATE emp SET Deptno = :NEW.Deptno, Update_id = Integritypackage.Updateseq WHERE emp.Deptno = :OLD.Deptno AND Update_id IS NULL; END IF; IF DELETING THEN DELETE FROM emp WHERE emp.Deptno = :OLD.Deptno; END IF; END;" db-types="Oracle" />
<sql-case id="create_trigger_with_cascade_4" value="CREATE OR REPLACE TRIGGER dept_restrict BEFORE DELETE OR UPDATE OF Deptno ON dept FOR EACH ROW DECLARE Dummy INTEGER; Employees_present EXCEPTION; employees_not_present EXCEPTION; CURSOR Dummy_cursor (Dn NUMBER) IS SELECT Deptno FROM emp WHERE Deptno = Dn; BEGIN OPEN Dummy_cursor (:OLD.Deptno); FETCH Dummy_cursor INTO Dummy; IF Dummy_cursor%FOUND THEN RAISE Employees_present; ELSE RAISE Employees_not_present; END IF; CLOSE Dummy_cursor; EXCEPTION WHEN Employees_present THEN CLOSE Dummy_cursor; Raise_application_error(-20001, 'Employees Present in' || ' Department ' || TO_CHAR(:OLD.DEPTNO)); WHEN Employees_not_present THEN CLOSE Dummy_cursor; END;" db-types="Oracle" />
<sql-case id="create_trigger_with_dataManipulationLanguage_statement" value="CREATE OR REPLACE TRIGGER lineitems_trigger
AFTER INSERT OR UPDATE OR DELETE ON lineitems
FOR EACH ROW
BEGIN
IF (INSERTING OR UPDATING)
THEN
UPDATE orders SET line_items_count = NVL(line_items_count,0)+1
WHERE order_id = :new.order_id;
END IF;
IF (DELETING OR UPDATING)
THEN
UPDATE orders SET line_items_count = NVL(line_items_count,0)-1
WHERE order_id = :old.order_id;
END IF;
END;" db-types="Oracle"/>
<sql-case id="create_trigger_with_exceptionInit_pragma" value="CREATE OR REPLACE TRIGGER Employee_permit_changes
BEFORE INSERT OR DELETE OR UPDATE ON employees
DECLARE
Dummy INTEGER;
Not_on_weekends EXCEPTION;
Nonworking_hours EXCEPTION;
PRAGMA EXCEPTION_INIT (Not_on_weekends, -4097);
PRAGMA EXCEPTION_INIT (Nonworking_hours, -4099);
BEGIN
IF (TO_CHAR(Sysdate, 'DAY') = 'SAT' OR
TO_CHAR(Sysdate, 'DAY') = 'SUN') THEN
RAISE Not_on_weekends;
END IF;
IF (TO_CHAR(Sysdate, 'HH24') < 8 OR
TO_CHAR(Sysdate, 'HH24') > 18) THEN
RAISE Nonworking_hours;
END IF;
EXCEPTION
WHEN Not_on_weekends THEN
Raise_application_error(-20324,'Might not change '
||'employee table during the weekend');
WHEN Nonworking_hours THEN
Raise_application_error(-20326,'Might not change '
||'emp table during Nonworking hours');
END;" db-types="Oracle"/>
<sql-case id="create_trigger_with_dml_event" value="CREATE OR REPLACE TRIGGER order_info_insert
INSTEAD OF INSERT ON order_info
DECLARE
duplicate_info EXCEPTION;
PRAGMA EXCEPTION_INIT (duplicate_info, -00001);
BEGIN
INSERT INTO customers
(customer_id, cust_last_name, cust_first_name)
VALUES (
:new.customer_id,
:new.cust_last_name,
:new.cust_first_name);
INSERT INTO orders (order_id, order_date, customer_id)
VALUES (
:new.order_id,
:new.order_date,
:new.customer_id);
EXCEPTION
WHEN duplicate_info THEN
RAISE_APPLICATION_ERROR (
num=> -20107,
msg=> 'Duplicate customer or order ID');
END order_info_insert;" db-types="Oracle" />
</sql-cases>
``` | /content/code_sandbox/test/it/parser/src/main/resources/sql/supported/ddl/create-trigger.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 1,505 |
```xml
import { Then } from 'cucumber';
import { waitUntilTextInSelector } from '../../../common/e2e/steps/helpers';
const SELECTORS = {
REPORT_ISSUE_BTN: '.ReportIssue_actionButton.reportIssueButton',
REPORT_ISSUE_HEADER: '.ReportIssue_reportIssueText',
SYNCING_CONNECTING_COMPONENT: '.SyncingConnecting_component',
};
Then(/^I should not see the loading screen$/, async function () {
await this.client.waitForVisible(
SELECTORS.SYNCING_CONNECTING_COMPONENT,
null,
true
);
});
Then(
/^I should see the report issue notification displaying "([^"]*)"$/,
async function (text) {
await waitUntilTextInSelector(this.client, {
selector: SELECTORS.REPORT_ISSUE_HEADER,
text,
});
}
);
Then(/^I should not see the report issue notification$/, async function () {
await this.client.waitForVisible(SELECTORS.REPORT_ISSUE_HEADER, null, true);
});
Then(/^The report issue button should be (hidden|visible)$/, async function (
state
) {
const waitForHidden = state === 'hidden';
await this.client.waitForVisible(
SELECTORS.REPORT_ISSUE_BTN,
null,
waitForHidden
);
});
``` | /content/code_sandbox/tests/app/e2e/steps/trouble-connecting-notification.ts | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 261 |
```xml
import { css, unsafeCSS } from 'lit';
import { customElement } from 'lit/decorators.js';
import { TopAppBarFixedBase } from '@material/mwc-top-app-bar-fixed/mwc-top-app-bar-fixed-base';
import { styles } from '@material/mwc-top-app-bar/mwc-top-app-bar.css';
import baseStyles from './top-app-bar.scss?inline';
declare global {
interface HTMLElementTagNameMap {
'cv-top-app-bar-fixed': CovalentTopAppBarFixed;
}
}
@customElement('cv-top-app-bar-fixed')
export class CovalentTopAppBarFixed extends TopAppBarFixedBase {
static override styles = [
styles,
css`
${unsafeCSS(baseStyles)}
`,
];
}
export default CovalentTopAppBarFixed;
``` | /content/code_sandbox/libs/components/src/top-app-bar/top-app-bar-fixed.ts | xml | 2016-07-11T23:30:52 | 2024-08-15T15:20:45 | covalent | Teradata/covalent | 2,228 | 164 |
```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 classNames from "classnames";
import { format, isValid } from "date-fns";
import * as React from "react";
import { Icon, Intent, type Props, Tag } from "@blueprintjs/core";
import type { DateRange } from "@blueprintjs/datetime";
const FORMAT = "EEEE, MMMM d, yyyy";
const FORMAT_WITH_TIME = "MMMM d, yyyy 'at' K:mm a";
const DateFnsDate: React.FC<{ date: Date; formatStr?: string; withTime?: boolean }> = ({
date,
withTime = false,
formatStr = withTime ? FORMAT_WITH_TIME : FORMAT,
}) => {
if (isValid(date)) {
return <Tag intent={Intent.PRIMARY}>{format(date, formatStr)}</Tag>;
} else {
return <Tag minimal={true}>no date</Tag>;
}
};
/** @deprecated use `FormattedDateRange` */
export const DateFnsDateRange: React.FC<{ range: DateRange; formatStr?: string; withTime?: boolean } & Props> = ({
className,
range: [start, end],
withTime = false,
formatStr = withTime ? FORMAT_WITH_TIME : FORMAT,
}) => (
<div className={classNames("docs-date-range", className)}>
<DateFnsDate withTime={withTime} date={start} formatStr={formatStr} />
<Icon icon="arrow-right" />
<DateFnsDate withTime={withTime} date={end} formatStr={formatStr} />
</div>
);
``` | /content/code_sandbox/packages/docs-app/src/examples/datetime-examples/common/dateFnsDate.tsx | xml | 2016-10-25T21:17:50 | 2024-08-16T15:14:48 | blueprint | palantir/blueprint | 20,593 | 369 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="1024"
android:viewportHeight="1024">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M811.008 335.872c-2.048-7.168-11.264-9.216-17.408-4.096L690.176 435.2c-8.192
8.192-20.48 8.192-28.672 0l-72.704-72.704c-8.192-8.192-8.192-20.48
0-28.672l104.448-104.448c5.12-5.12
3.072-14.336-4.096-17.408-17.408-4.096-35.84-7.168-54.272-7.168-108.544
0-195.584 94.208-183.296 204.8 2.048 17.408 6.144 32.768 12.288 48.128L225.28
697.344c-27.648 27.648-27.648 73.728 0 101.376 14.336 14.336 32.768 21.504 51.2
21.504s36.864-7.168 51.2-21.504l238.592-238.592c15.36 6.144 31.744 10.24 48.128
12.288 111.616 12.288 204.8-74.752 204.8-183.296
0-18.432-3.072-36.864-8.192-53.248z" />
</vector>
``` | /content/code_sandbox/feature/utilcode/pkg/src/main/res/drawable/bar_status_nav_custom.xml | xml | 2016-07-30T18:18:32 | 2024-08-16T01:37:59 | AndroidUtilCode | Blankj/AndroidUtilCode | 33,178 | 428 |
```xml
import { Signature } from "./signature";
import { Widget } from "./widget";
export interface LoadoutFile {
signature: Signature;
widgets: Widget[];
}
export const signature: Signature = {
code: "p2c-cap-load",
version: "0.13.0",
};
``` | /content/code_sandbox/IntelPresentMon/AppCef/Web/src/core/loadout.ts | xml | 2016-03-09T18:44:16 | 2024-08-15T19:51:10 | PresentMon | GameTechDev/PresentMon | 1,580 | 62 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
xmlns="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id=your_sha256_hashal">
<startEvent id="theStart" />
<sequenceFlow id="flow1" sourceRef="theStart" targetRef="serviceTask" />
<serviceTask id="serviceTask" activiti:class="org.activiti.engine.test.bpmn.event.error.ThrowBpmnErrorDelegate">
<multiInstanceLoopCharacteristics isSequential="true">
<loopCardinality>3</loopCardinality>
</multiInstanceLoopCharacteristics>
</serviceTask>
<boundaryEvent id="catchError" attachedToRef="serviceTask">
<errorEventDefinition />
</boundaryEvent>
<sequenceFlow id="flow3" sourceRef="catchError" targetRef="escalatedTask" />
<userTask id="escalatedTask" name="Escalated Task" />
<sequenceFlow id="flow4" sourceRef="serviceTask" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByJavaDelegateOnMultiInstanceServiceTaskSequential.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 269 |
```xml
<vector xmlns:android="path_to_url"
android:width="128dp"
android:height="128dp"
android:viewportWidth="34"
android:viewportHeight="34">
<path
android:pathData="m33.87,16.93c0,9.35 -7.58,16.93 -16.93,16.93 -9.35,0 -16.93,-7.58 -16.93,-16.93 0,-9.35 7.58,-16.93 16.93,-16.93 9.35,0 16.93,7.58 16.93,16.93"
android:fillColor="#b9a065"/>
<path
android:pathData="m13.19,5.21c-0.72,0.03 -1.42,0.37 -1.89,0.97 -0.83,1.07 -0.63,2.6 0.44,3.44 0.33,0.26 0.98,0.45 1.71,0.59 -3.4,-0.05 -7.16,1.61 -7.16,7.72 0,5.42 5.5,11.69 8.29,11.69 1.25,0 1.66,-0.53 2.43,-0.53 0.73,0 1.01,0.53 2.63,0.53 2.79,0 7.82,-6.1 7.82,-11.57 0,-8.06 -6.55,-8.49 -9.75,-7.37 0.16,-0.98 0.88,-3.21 3.76,-3.21v-1.05c-2.92,0 -4.19,1.67 -4.65,3.24 -0.45,-1.25 -1.29,-3.38 -2.04,-3.96 -0.47,-0.36 -1.04,-0.53 -1.59,-0.5z"
android:fillAlpha="0.2"
android:fillColor="#000"/>
<path
android:pathData="m17.2,9.52c0,0 -4.32,-0.15 -5.4,-0.98 -1.07,-0.83 -1.28,-2.36 -0.44,-3.44 0.83,-1.07 2.41,-1.3 3.48,-0.47 1.07,0.83 2.36,4.89 2.36,4.89z"
android:fillColor="#83bf4f"/>
<path
android:pathData="m16.67,10.05c0,-1.74 0.97,-4.69 4.86,-4.69v1.05c-3.52,0 -3.8,3.32 -3.8,3.64z"
android:fillColor="#947151"/>
<path
android:pathData="m17.19,9.84c-3.44,-1.39 -10.84,-1.58 -10.84,7 0,5.42 5.5,11.69 8.29,11.69 1.25,0 1.66,-0.53 2.43,-0.53 0.73,0 1.01,0.53 2.63,0.53 2.79,0 7.82,-6.1 7.82,-11.57 0,-8.58 -7.41,-8.52 -10.32,-7.13z"
android:fillColor="#ef4d3c"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_quest_apple.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 869 |
```xml
import { IModels } from '../../connectionResolver';
import { PAYMENTS } from '../constants';
import { BaseAPI } from '../base';
import redis from '../../redis';
export const paypalCallbackHandler = async (models: IModels, data: any) => {
const { paymentId, PayerID } = data;
if (!paymentId) {
throw new Error('paymentId is required');
}
if (!PayerID) {
throw new Error('PayerID is required');
}
};
export interface IPaypalConfig {
paypalMode: 'sandbox' | 'live';
paypalClientId: string;
paypalClientSecret: string;
}
export class PaypalAPI extends BaseAPI {
private mode: string;
private clientId: string;
private clientSecret: any;
constructor(config: IPaypalConfig) {
super(config);
this.mode = config.paypalMode;
this.clientId = config.paypalClientId;
this.clientSecret = config.paypalClientSecret;
this.apiUrl =
config.paypalMode === 'sandbox'
? 'path_to_url
: 'path_to_url
}
async getHeaders() {
const { clientId, clientSecret } = this;
const token = await redis.get(`paypal_token_${clientId}`);
if (token) {
return {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
};
}
try {
const res = await this.request({
path: PAYMENTS.paypal.actions.getToken,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
'Accept-Language': 'en_US',
Authorization: `Basic ${Buffer.from(
`${clientId}:${clientSecret}`,
).toString('base64')}`,
},
data: {
grant_type: 'client_credentials',
},
}).then((r) => r.json());
await redis.set(
`paypal_token_${clientId}`,
res.access_token,
'EX',
res.expires_in - 60,
);
return {
'Content-Type': 'application/json',
Authorization: `Bearer ${res.access_token}`,
};
} catch (e) {
console.error('e', e);
}
}
}
``` | /content/code_sandbox/packages/plugin-payment-api/src/api/paypal/api.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 484 |
```xml
/**
* @license
*
* 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 svg_maximize from "ikonate/icons/maximise.svg?raw";
import type { MakeIconOptions } from "#src/widget/icon.js";
import { makeIcon } from "#src/widget/icon.js";
export function makeMaximizeButton(options: MakeIconOptions = {}) {
return makeIcon({ svg: svg_maximize, ...options });
}
``` | /content/code_sandbox/src/widget/maximize_button.ts | xml | 2016-05-27T02:37:25 | 2024-08-16T07:24:25 | neuroglancer | google/neuroglancer | 1,045 | 114 |
```xml
import { trackEvent } from "modules/analytics";
import { SESSION_RECORDING } from "../constants";
export enum ActionSource {
Preview = "preview",
List = "list",
TrafficTable = "taffic_table",
}
export function trackHarImportButtonClicked() {
trackEvent(SESSION_RECORDING.network.import.har.btn_clicked);
}
export function trackHarImportCanceled() {
trackEvent(SESSION_RECORDING.network.import.har.canceled);
}
export function trackHarImportCompleted() {
trackEvent(SESSION_RECORDING.network.import.har.completed);
}
export function trackWebSessionImportButtonClicked() {
trackEvent(SESSION_RECORDING.network.import.web_sessions.btn_clicked);
}
export function trackWebSessionImportCanceled() {
trackEvent(SESSION_RECORDING.network.import.web_sessions.canceled);
}
export function trackWebSessionImportCompleted() {
trackEvent(SESSION_RECORDING.network.import.web_sessions.completed);
}
export function trackDeleteNetworkSessionClicked(source: ActionSource) {
const params = { source };
trackEvent(SESSION_RECORDING.network.delete.btn_clicked, params);
}
export function trackDeleteNetworkSessionCanceled() {
trackEvent(SESSION_RECORDING.network.delete.canceled);
}
export function trackDeleteNetworkSessionConfirmed() {
trackEvent(SESSION_RECORDING.network.delete.confirmed);
}
export function trackDownloadNetworkSessionClicked(source: ActionSource) {
const params = { source };
trackEvent(SESSION_RECORDING.network.download, params);
}
export function trackNetworkSessionSaveClicked() {
trackEvent(SESSION_RECORDING.network.save.btn_clicked);
}
export function trackNetworkSessionSaved() {
trackEvent(SESSION_RECORDING.network.save.saved);
}
export function trackNetworkSessionSaveCanceled() {
trackEvent(SESSION_RECORDING.network.save.canceled);
}
export function trackNetworkSessionViewerBackClicked() {
trackEvent(SESSION_RECORDING.network.back_from_preview);
}
export function trackHarFileOpened() {
trackEvent(SESSION_RECORDING.network.har_file_opened);
}
``` | /content/code_sandbox/app/src/modules/analytics/events/features/sessionRecording/networkSessions.ts | xml | 2016-12-01T04:36:06 | 2024-08-16T19:12:19 | requestly | requestly/requestly | 2,121 | 408 |
```xml
/*your_sha256_hash-----------------------------
*your_sha256_hash----------------------------*/
import * as TypeMoq from 'typemoq';
import * as assert from 'assert';
import * as Interfaces from '../../src/models/interfaces';
import ResultsSerializer from '../../src/models/resultsSerializer';
import { SaveResultsAsCsvRequestParams } from '../../src/models/contracts';
import SqlToolsServerClient from '../../src/languageservice/serviceclient';
import VscodeWrapper from '../../src/controllers/vscodeWrapper';
import * as vscode from 'vscode';
import * as os from 'os';
suite('save results tests', () => {
const testFile = 'file:///my/test/file.sql';
let fileUri: vscode.Uri;
let serverClient: TypeMoq.IMock<SqlToolsServerClient>;
let vscodeWrapper: TypeMoq.IMock<VscodeWrapper>;
setup(() => {
serverClient = TypeMoq.Mock.ofType(SqlToolsServerClient, TypeMoq.MockBehavior.Strict);
vscodeWrapper = TypeMoq.Mock.ofType(VscodeWrapper);
vscodeWrapper.setup(x => x.getConfiguration(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(extensionName => {
return vscode.workspace.getConfiguration(extensionName);
});
if (os.platform() === 'win32') {
fileUri = vscode.Uri.file('c:\\test.csv');
} else {
fileUri = vscode.Uri.file('/test.csv');
}
});
test('check if filepath prompt displays and right value is set', (done) => {
// setup mock filepath prompt
vscodeWrapper.setup(x => x.showSaveDialog(TypeMoq.It.isAny())).returns(() => Promise.resolve(fileUri));
// setup mock sql tools server client
serverClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.callback((type, details: SaveResultsAsCsvRequestParams) => {
// check if filepath was set from answered prompt
try {
assert.equal(details.ownerUri, testFile);
assert.equal(details.filePath, fileUri.fsPath);
done();
} catch (error) {
done(error);
}
})
.returns(() => {
// This will come back as null from the service layer, but tslinter doesn't like that
return Promise.resolve({ messages: 'failure' });
});
let saveResults = new ResultsSerializer(serverClient.object, vscodeWrapper.object);
saveResults.onSaveResults(testFile, 0, 0, 'csv', undefined);
});
function testSaveSuccess(format: string): Thenable<void> {
// setup mocks
vscodeWrapper.setup(x => x.showInformationMessage(TypeMoq.It.isAnyString()));
vscodeWrapper.setup(x => x.openTextDocument(TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showTextDocument(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showTextDocument(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showTextDocument(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showSaveDialog(TypeMoq.It.isAny())).returns(() => Promise.resolve(fileUri));
serverClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => {
// This will come back as null from the service layer, but tslinter doesn't like that
return Promise.resolve({ messages: undefined });
});
let saveResults = new ResultsSerializer(serverClient.object, vscodeWrapper.object);
return saveResults.onSaveResults(testFile, 0, 0, format, undefined).then(() => {
// check if information message was displayed
vscodeWrapper.verify(x => x.showInformationMessage(TypeMoq.It.isAnyString()), TypeMoq.Times.once());
});
}
function testSaveFailure(format: string): Thenable<void> {
// setup mocks
vscodeWrapper.setup(x => x.showErrorMessage(TypeMoq.It.isAnyString()));
vscodeWrapper.setup(x => x.showSaveDialog(TypeMoq.It.isAny())).returns(() => Promise.resolve(fileUri));
serverClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => {
return Promise.resolve({ messages: 'failure' });
});
let saveResults = new ResultsSerializer(serverClient.object, vscodeWrapper.object);
return saveResults.onSaveResults(testFile, 0, 0, format, undefined).then(() => {
// check if error message was displayed
vscodeWrapper.verify(x => x.showErrorMessage(TypeMoq.It.isAnyString()), TypeMoq.Times.once());
});
}
test('Save as CSV - test if information message is displayed on success', () => {
return testSaveSuccess('csv');
});
test('Save as CSV - test if error message is displayed on failure to save', () => {
return testSaveFailure('csv');
});
test('Save as JSON - test if information message is displayed on success', () => {
return testSaveSuccess('json');
});
test('Save as JSON - test if error message is displayed on failure to save', () => {
return testSaveFailure('json');
});
test('Save as Excel - test if information message is displayed on success', () => {
return testSaveSuccess('excel');
});
test('Save as Excel - test if error message is displayed on failure to save', () => {
return testSaveFailure('excel');
});
test('Save as with selection - test if selected range is passed in parameters', () => {
let selection: Interfaces.ISlickRange[] = [{
fromCell: 0,
toCell: 1,
fromRow: 0,
toRow: 1
}];
// setup mocks
vscodeWrapper.setup(x => x.showInformationMessage(TypeMoq.It.isAnyString()));
vscodeWrapper.setup(x => x.openTextDocument(TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showTextDocument(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showSaveDialog(TypeMoq.It.isAny())).returns(() => Promise.resolve(fileUri));
serverClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.callback((type, params: SaveResultsAsCsvRequestParams) => {
// check if right parameters were set from the selection
assert.equal(params.columnStartIndex, selection[0].fromCell);
assert.equal(params.columnEndIndex, selection[0].toCell);
assert.equal(params.rowStartIndex, selection[0].fromRow);
assert.equal(params.rowEndIndex, selection[0].toRow);
})
.returns(() => {
// This will come back as null from the service layer, but tslinter doesn't like that
return Promise.resolve({ messages: undefined });
});
let saveResults = new ResultsSerializer(serverClient.object, vscodeWrapper.object);
return saveResults.onSaveResults(testFile, 0, 0, 'csv', selection);
});
test('Save as with selection - test case when right click on single cell - no selection is set in parameters', () => {
let selection: Interfaces.ISlickRange[] = [{
fromCell: 0,
toCell: 0,
fromRow: 0,
toRow: 0
}];
// setup mocks
vscodeWrapper.setup(x => x.showInformationMessage(TypeMoq.It.isAnyString()));
vscodeWrapper.setup(x => x.openTextDocument(TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showTextDocument(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => {
return Promise.resolve(undefined);
});
vscodeWrapper.setup(x => x.showSaveDialog(TypeMoq.It.isAny())).returns(() => Promise.resolve(fileUri));
serverClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.callback((type, params: SaveResultsAsCsvRequestParams) => {
// Check if selection parameters were undefined in the request
// When rightclicking on resultgrid to save entire result set,
// the cell that was clicked on is sent in selection from the front end
assert.equal(params.columnStartIndex, undefined);
assert.equal(params.columnEndIndex, undefined);
assert.equal(params.rowStartIndex, undefined);
assert.equal(params.rowEndIndex, undefined);
})
.returns(() => {
// This will come back as null from the service layer, but tslinter doesn't like that
return Promise.resolve({ messages: undefined });
});
let saveResults = new ResultsSerializer(serverClient.object, vscodeWrapper.object);
return saveResults.onSaveResults(testFile, 0, 0, 'csv', selection);
});
test('canceling out of save file dialog cancels serialization', (done) => {
// setup mock filepath prompt
vscodeWrapper.setup(x => x.showSaveDialog(TypeMoq.It.isAny())).returns(() => Promise.resolve(undefined));
// setup mock sql tools server client
serverClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()));
let saveResults = new ResultsSerializer(serverClient.object, vscodeWrapper.object);
saveResults.onSaveResults(testFile, 0, 0, 'csv', undefined).then(() => {
try {
serverClient.verify(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.never());
done();
} catch (error) {
done(error);
}
}, error => done(error));
});
});
``` | /content/code_sandbox/test/unit/saveResults.test.ts | xml | 2016-06-26T04:38:04 | 2024-08-16T20:04:12 | vscode-mssql | microsoft/vscode-mssql | 1,523 | 2,242 |
```xml
<!-- MSBuild processing -->
<!-- Values -->
<ValueA>True</ValueA>
<ValueB>True</ValueB>
<ValueC>True</ValueC>
<ValueD>True</ValueD>
<!--'$(A)' in condition -->
<TargetFramework>A-true</TargetFramework>
<TargetFramework>B-true</TargetFramework>
<TargetFramework>C-true</TargetFramework>
<TargetFramework>D-true</TargetFramework>
<!--'$(A)' == true in condition -->
<TargetFramework>A-true</TargetFramework>
<TargetFramework>B-true</TargetFramework>
<TargetFramework>C-true</TargetFramework>
<TargetFramework>D-true</TargetFramework>
<!--'$(A)' == 'true' in condition -->
<TargetFramework>A-true</TargetFramework>
<TargetFramework>B-true</TargetFramework>
<TargetFramework>C-true</TargetFramework>
<TargetFramework>D-true</TargetFramework>
<!-- if (A) syntax-->
<TargetFramework>A-true</TargetFramework>
<TargetFramework>B-true</TargetFramework>
<TargetFramework>C-true</TargetFramework>
<TargetFramework>D-true</TargetFramework>
<!-- if (A == true) syntax-->
<TargetFramework>A-true</TargetFramework>
<TargetFramework>B-true</TargetFramework>
<TargetFramework>C-true</TargetFramework>
<TargetFramework>D-true</TargetFramework>
<!-- if (A == "true") syntax-->
<TargetFramework>A-false</TargetFramework>
<TargetFramework>B-false</TargetFramework>
<TargetFramework>C-false</TargetFramework>
<TargetFramework>D-false</TargetFramework>
``` | /content/code_sandbox/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/BooleanConditionsTest.option equals to true.verified/TestAssets.TemplateWithBooleanParameters/bar.props | xml | 2016-06-28T20:54:16 | 2024-08-16T14:39:38 | templating | dotnet/templating | 1,598 | 338 |
```xml
/**
* ParticleSystem.tsx
*
* Lightweight, canvas-based particle system
*
* TODO:
* - Move this to a plugin, and access via the `getPlugin` API
*/
import * as React from "react"
import styled from "styled-components"
import { Overlay, OverlayManager } from "./../Overlay"
export interface Vector {
x: number
y: number
}
export interface ParticleSystemDefinition {
// StartSize: number
// EndSize: number
Position: Vector
Velocity: Vector
PositionVariance: Vector
VelocityVariance: Vector
Color: string
StartOpacity: number
EndOpacity: number
Gravity: Vector
Time: number
}
const ZeroVector = { x: 0, y: 0 }
export const DefaultParticleSystemDefinition: Partial<ParticleSystemDefinition> = {
Color: "white",
StartOpacity: 1,
EndOpacity: 0,
Gravity: { x: 0, y: 500 },
Time: 1,
Position: ZeroVector,
Velocity: ZeroVector,
PositionVariance: ZeroVector,
VelocityVariance: ZeroVector,
}
export interface Particle {
position: Vector
opacity: number
color: string
velocity: Vector
opacityVelocity: number
gravity: Vector
remainingTime: number
}
const StyledCanvas = styled.canvas`
width: 100%;
height: 100%;
`
/**
* Lightweight canvas-based particle system renderer
*/
export class ParticleSystem {
private _activeParticles: Particle[] = []
private _activeOverlay: Overlay
private _activeCanvas: HTMLCanvasElement
private _lastTime: number
private _enabled: boolean = false
constructor(private _overlayManager: OverlayManager) {}
public get enabled(): boolean {
return this._enabled
}
public set enabled(val: boolean) {
this._enabled = val
}
public createParticles(count: number, particleSystem: Partial<ParticleSystemDefinition>): void {
const newParticles: Particle[] = []
const system = {
...DefaultParticleSystemDefinition,
...particleSystem,
}
for (let i = 0; i < count; i++) {
newParticles.push({
position: {
x: system.Position.x + (Math.random() - 0.5) * system.PositionVariance.x,
y: system.Position.y + (Math.random() - 0.5) * system.PositionVariance.y,
},
color: system.Color,
opacity: system.StartOpacity,
velocity: {
x: system.Velocity.x + (Math.random() - 0.5) * system.VelocityVariance.x,
y: system.Velocity.y + (Math.random() - 0.5) * system.VelocityVariance.y,
},
gravity: system.Gravity,
opacityVelocity: (system.EndOpacity - system.StartOpacity) / system.Time,
remainingTime: system.Time,
})
}
this._activeParticles = [...this._activeParticles, ...newParticles]
if (!this._activeOverlay) {
this._activeOverlay = this._overlayManager.createItem()
}
this._activeOverlay.show()
this._activeOverlay.setContents(
<StyledCanvas className="particles" innerRef={elem => (this._activeCanvas = elem)} />,
)
this._start()
}
private _start(): void {
this._lastTime = new Date().getTime()
window.requestAnimationFrame(() => {
this._update()
})
}
private _update(): void {
const currentTime = new Date().getTime()
const deltaTime = (currentTime - this._lastTime) / 1000
this._lastTime = currentTime
const updatedParticles = this._activeParticles.map(p => {
return {
...p,
position: {
x: p.position.x + p.velocity.x * deltaTime,
y: p.position.y + p.velocity.y * deltaTime,
},
velocity: {
x: p.velocity.x + p.gravity.x * deltaTime,
y: p.velocity.y + p.gravity.y * deltaTime,
},
opacity: p.opacity + p.opacityVelocity * deltaTime,
remainingTime: p.remainingTime - deltaTime,
}
})
const filteredParticles = updatedParticles.filter(p => p.remainingTime >= 0)
this._activeParticles = filteredParticles
this._draw()
if (this._activeParticles.length > 0) {
window.requestAnimationFrame(() => this._update())
} else {
if (this._activeOverlay) {
this._activeOverlay.hide()
}
}
}
private _draw(): void {
if (!this._activeCanvas) {
return
}
const context = this._activeCanvas.getContext("2d", { alpha: true })
const width = (this._activeCanvas.width = this._activeCanvas.offsetWidth)
const height = (this._activeCanvas.height = this._activeCanvas.offsetHeight)
context.clearRect(0, 0, width, height)
this._activeParticles.forEach(p => {
context.fillStyle = p.color
context.globalAlpha = p.opacity
context.fillRect(p.position.x, p.position.y, 2, 2)
})
}
}
``` | /content/code_sandbox/browser/src/Services/Particles/ParticleSystem.tsx | xml | 2016-11-16T14:42:55 | 2024-08-14T11:48:05 | oni | onivim/oni | 11,355 | 1,126 |
```xml
<!--
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
path_to_url
Unless required by applicable law or agreed to in writing,
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
specific language governing permissions and limitations
-->
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M18,16.08c-0.76,0 -1.44,0.3 -1.96,0.77L8.91,12.7c0.05,-0.23 0.09,-0.46 0.09,-0.7s-0.04,-0.47 -0.09,-0.7l7.05,-4.11c0.54,0.5 1.25,0.81 2.04,0.81 1.66,0 3,-1.34 3,-3s-1.34,-3 -3,-3 -3,1.34 -3,3c0,0.24 0.04,0.47 0.09,0.7L8.04,9.81C7.5,9.31 6.79,9 6,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3c0.79,0 1.5,-0.31 2.04,-0.81l7.12,4.16c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.61 1.31,2.92 2.92,2.92 1.61,0 2.92,-1.31 2.92,-2.92s-1.31,-2.92 -2.92,-2.92z"/>
</vector>
``` | /content/code_sandbox/playground/android/playground/src/main/res/drawable-v21/ic_menu_share.xml | xml | 2016-03-11T10:18:11 | 2024-08-16T06:43:02 | weex | alibaba/weex | 18,250 | 479 |
```xml
import { ValueObject } from '@standardnotes/domain-core'
import type { ConnectionCloseReasonProps } from './ConnectionCloseReasonProps'
export class ConnectionCloseReason extends ValueObject<ConnectionCloseReasonProps> {
private MAX_WEBSOCKET_FRAME_SIZE = 123
static CODES = {
NORMAL_CLOSURE: 1000,
GOING_AWAY: 1001,
PROTOCOL_ERROR: 1002,
UNSUPPORTED_DATA: 1003,
NO_STATUS_RECEIVED: 1005,
ABNORMAL_CLOSURE: 1006,
INVALID_FRAME_PAYLOAD_DATA: 1007,
POLICY_VIOLATION: 1008,
MESSAGE_TOO_BIG: 1009,
MISSING_EXTENSION: 1010,
INTERNAL_ERROR: 1011,
SERVICE_RESTART: 1012,
TRY_AGAIN_LATER: 1013,
BAD_GATEWAY: 1014,
TLS_HANDSHAKE: 1015,
STALE_COMMIT_ID: 3000,
DOCUMENT_NOT_FOUND: 3001,
INVALID_PARAMETERS: 3002,
UNAUTHORIZED: 3003,
TIMEOUT: 3004,
DOCUMENT_TIMEOUT: 3005,
LEFT: 3006,
TRAFFIC_ABUSE_MAX_BANDWIDTH: 3007,
TRAFFIC_ABUSE_MAX_DU_SIZE: 3008,
KILL_SWITCH_ENABLED: 3009,
DOCUMENT_CAPACITY_REACHED: 3010,
DOCUMENT_RECREATING: 3011,
DOCUMENT_PARTICIPANT_LIMIT_REACHED: 3012,
CLIENT_VERSION_NOT_SUPPORTED: 3013,
}
static messages: Record<number, string> = {
[ConnectionCloseReason.CODES.NORMAL_CLOSURE]: 'Normal closure',
[ConnectionCloseReason.CODES.GOING_AWAY]: 'Going away',
[ConnectionCloseReason.CODES.PROTOCOL_ERROR]: 'Protocol error',
[ConnectionCloseReason.CODES.UNSUPPORTED_DATA]: 'Unsupported data',
[ConnectionCloseReason.CODES.NO_STATUS_RECEIVED]: 'No status received',
[ConnectionCloseReason.CODES.ABNORMAL_CLOSURE]: 'Abnormal closure',
[ConnectionCloseReason.CODES.INVALID_FRAME_PAYLOAD_DATA]: 'Invalid frame payload data',
[ConnectionCloseReason.CODES.POLICY_VIOLATION]: 'Policy violation',
[ConnectionCloseReason.CODES.MESSAGE_TOO_BIG]: 'Message too big',
[ConnectionCloseReason.CODES.MISSING_EXTENSION]: 'Missing extension',
[ConnectionCloseReason.CODES.INTERNAL_ERROR]: 'Internal error',
[ConnectionCloseReason.CODES.SERVICE_RESTART]: 'Service restart',
[ConnectionCloseReason.CODES.TRY_AGAIN_LATER]: 'Try again later',
[ConnectionCloseReason.CODES.BAD_GATEWAY]: 'Bad gateway',
[ConnectionCloseReason.CODES.TLS_HANDSHAKE]: 'TLS handshake',
[ConnectionCloseReason.CODES.STALE_COMMIT_ID]: 'Stale commit ID',
[ConnectionCloseReason.CODES.DOCUMENT_NOT_FOUND]: 'Document not found',
[ConnectionCloseReason.CODES.INVALID_PARAMETERS]: 'Invalid parameters to establish connection',
[ConnectionCloseReason.CODES.UNAUTHORIZED]: 'Unauthorized',
[ConnectionCloseReason.CODES.TIMEOUT]: 'Connection timed out',
[ConnectionCloseReason.CODES.DOCUMENT_TIMEOUT]: 'Document timed out',
[ConnectionCloseReason.CODES.LEFT]: 'User left the room',
[ConnectionCloseReason.CODES.TRAFFIC_ABUSE_MAX_BANDWIDTH]: 'Traffic abuse: max bandwidth exceeded',
[ConnectionCloseReason.CODES.TRAFFIC_ABUSE_MAX_DU_SIZE]: 'Traffic abuse: max DU size exceeded',
[ConnectionCloseReason.CODES.KILL_SWITCH_ENABLED]: 'Server is not accepting new connection.',
[ConnectionCloseReason.CODES.DOCUMENT_CAPACITY_REACHED]: 'Document capacity reached',
[ConnectionCloseReason.CODES.DOCUMENT_RECREATING]: 'Document is being recreated',
[ConnectionCloseReason.CODES.DOCUMENT_PARTICIPANT_LIMIT_REACHED]: 'Document active participants limit reached',
[ConnectionCloseReason.CODES.CLIENT_VERSION_NOT_SUPPORTED]:
'Client version not supported. Please upgrade your client.',
}
static create(props: ConnectionCloseReasonProps): ConnectionCloseReason {
if (Object.values(ConnectionCloseReason.CODES).indexOf(props.code) === -1) {
throw new Error('Invalid close code')
}
if (!props.message) {
props.message = this.messages[props.code]
}
return new ConnectionCloseReason(props)
}
get message(): string {
if (!this.props.message) {
return 'Unknown reason'
}
return this.props.message.length > this.MAX_WEBSOCKET_FRAME_SIZE
? `${this.props.message.slice(0, this.MAX_WEBSOCKET_FRAME_SIZE - 3)}...`
: this.props.message
}
}
``` | /content/code_sandbox/packages/docs-proto/lib/ConnectionCloseReason/ConnectionCloseReason.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,015 |
```xml
<vector xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:width="512dp"
android:height="512dp"
android:viewportWidth="512.0"
android:viewportHeight="512.0"
tools:keep="@drawable/fa_xbox">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M369.9,318.2c44.3,54.3 64.7,98.8 54.4,118.7 -7.9,15.1 -56.7,44.6 -92.6,55.9 -29.6,9.3 -68.4,13.3 -100.4,10.2 -38.2,-3.7 -76.9,-17.4 -110.1,-39C93.3,445.8 87,438.3 87,423.4c0,-29.9 32.9,-82.3 89.2,-142.1 32,-33.9 76.5,-73.7 81.4,-72.6 9.4,2.1 84.3,75.1 112.3,109.5zM188.6,143.8c-29.7,-26.9 -58.1,-53.9 -86.4,-63.4 -15.2,-5.1 -16.3,-4.8 -28.7,8.1 -29.2,30.4 -53.5,79.7 -60.3,122.4 -5.4,34.2 -6.1,43.8 -4.2,60.5 5.6,50.5 17.3,85.4 40.5,120.9 9.5,14.6 12.1,17.3 9.3,9.9 -4.2,-11 -0.3,-37.5 9.5,-64 14.3,-39 53.9,-112.9 120.3,-194.4zM500.2,207.3C483.3,127.3 432.7,77 425.6,77c-7.3,0 -24.2,6.5 -36,13.9 -23.3,14.5 -41,31.4 -64.3,52.8C367.7,197 427.5,283.1 448.2,346c6.8,20.7 9.7,41.1 7.4,52.3 -1.7,8.5 -1.7,8.5 1.4,4.6 6.1,-7.7 19.9,-31.3 25.4,-43.5 7.4,-16.2 15,-40.2 18.6,-58.7 4.3,-22.5 3.9,-70.8 -0.8,-93.4zM141.3,43C189,40.5 251,77.5 255.6,78.4c0.7,0.1 10.4,-4.2 21.6,-9.7 63.9,-31.1 94,-25.8 107.4,-25.2 -63.9,-39.3 -152.7,-50 -233.9,-11.7 -23.4,11.1 -24,11.9 -9.4,11.2z"/>
</vector>
``` | /content/code_sandbox/mobile/src/main/res/drawable/fa_xbox.xml | xml | 2016-10-24T13:23:25 | 2024-08-16T07:20:37 | freeotp-android | freeotp/freeotp-android | 1,387 | 797 |
```xml
import { c, msgid } from 'ttag';
import { Button, Href } from '@proton/atoms';
import { Form, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components';
import { BRAND_NAME, MAIL_APP_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import clsx from '@proton/utils/clsx';
interface Props {
emails: string[];
onSubmit: () => void;
onClose: () => void;
}
const SendWithExpirationModal = ({ emails, onSubmit, onClose, ...rest }: Props) => {
const handleSubmit = () => {
onSubmit();
onClose();
};
return (
<ModalTwo
size="large"
as={Form}
data-testid="composer:send-anyway"
onSubmit={handleSubmit}
onClose={onClose}
{...rest}
>
<ModalTwoHeader title={c('Title').t`Send without expiration?`} />
<ModalTwoContent>
<div className="mb-2">
{c('Info')
.t`Message expiration works out-of-the-box when sending emails to other ${MAIL_APP_NAME} users. To send expiring emails to non-${BRAND_NAME} users, please cancel and add password protection to your email.`}
<br />
<Href href={getKnowledgeBaseUrl('/expiration')}>{c('Info').t`Learn more`}</Href>
</div>
<span>
{c('Send email with warnings').ngettext(
msgid`If you decide to send the message anyway, the following recipient will receive the email without expiration:`,
`If you decide to send the message anyway, the following recipients will receive the email without expiration:`,
emails.length
)}
</span>
<ul>
{emails.map((email, index) => (
<li
key={index} // eslint-disable-line react/no-array-index-key
className={clsx([index !== emails.length && 'mb-2'])}
>
<span className="block max-w-full">{email}</span>
</li>
))}
</ul>
</ModalTwoContent>
<ModalTwoFooter>
<Button onClick={onClose}>{c('Action').t`Cancel`}</Button>
<Button color="norm" type="submit">{c('Action').t`Send anyway`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default SendWithExpirationModal;
``` | /content/code_sandbox/applications/mail/src/app/components/composer/addresses/SendWithExpirationModal.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 541 |
```xml
import '../../methods/get.js';
import '../../methods/nextAll.js';
import '../../methods/nextUntil.js';
import { jQuery, jq, assert, JQStatic, toIdArray } from '../utils.js';
const test = ($: JQStatic, type: string): void => {
describe(`${type} - .nextUntil`, () => {
beforeEach(() => {
document.querySelector('#frame')!.innerHTML = `
<p id="test1">test1</p>
<p id="test2" class="haha">test2</p>
<p id="test3" class="haha">test3</p>
<p id="test4">test4</p>
<p id="test5">test5</p>
<div class="parent">
<div id="child1-1" class="child first"></div>
<div id="child1-2" class="child"></div>
<div id="child1-3" class="child"></div>
<div id="child1-4" class="child last"></div>
</div>
<div class="parent">
<div id="child2-1" class="child first"></div>
<div id="child2-2" class="child last"></div>
</div>
`;
});
it('.nextUntil(selector, filter)', () => {
const $test2 = $('#test2');
const $test1 = $('#test1');
const $test4 = $('#test4');
const $first = $('.first');
assert.sameOrderedMembers(
$test2.nextUntil().get(),
$test2.nextAll().get(),
);
assert.sameOrderedMembers(
$test2.nextUntil('#notfound').get(),
$test2.nextAll().get(),
);
let $nexts = $test1.nextUntil('#test4');
assert.sameOrderedMembers(toIdArray($nexts), ['test2', 'test3']);
$nexts = $first.nextUntil('#child1-4');
assert.sameOrderedMembers(toIdArray($nexts), [
'child1-2',
'child1-3',
'child2-2',
]);
$nexts = $test1.nextUntil('.parent', '.haha');
assert.sameOrderedMembers(toIdArray($nexts), ['test2', 'test3']);
$nexts = $first.nextUntil('.last', '#child1-3');
assert.sameOrderedMembers(toIdArray($nexts), ['child1-3']);
$nexts = $first.nextUntil('.last', '#notfound');
assert.lengthOf($nexts, 0);
$nexts = $test1.nextUntil($test4);
assert.sameOrderedMembers(toIdArray($nexts), ['test2', 'test3']);
$nexts = $test1.nextUntil($test4[0]);
assert.sameOrderedMembers(toIdArray($nexts), ['test2', 'test3']);
});
});
};
test(jq, 'jq');
test(jQuery as unknown as JQStatic, 'jQuery');
``` | /content/code_sandbox/packages/jq/__test__/methods/nextUntil.test.ts | xml | 2016-07-11T17:39:02 | 2024-08-16T07:12:34 | mdui | zdhxiong/mdui | 4,077 | 656 |
```xml
/*
* This software is released under MIT license.
* The full license information can be found in LICENSE in the root directory of this project.
*/
import { renderIcon } from '../icon.renderer.js';
import { IconShapeTuple } from '../interfaces/icon.interfaces.js';
const icon = {
outline:
'<path d="M30,9H16.42L14.11,5.82A2,2,0,0,0,12.49,5H6A2,2,0,0,0,4,7V29a2,2,0,0,0,2,2H30a2,2,0,0,0,2-2V11A2,2,0,0,0,30,9Zm0,20H6V13h7.31a2,2,0,0,0,2-2H6V7h6.49l2.61,3.59a1,1,0,0,0,.81.41H30Z"/>',
outlineAlerted:
'<path d="M30,15.4V29H6V13h7.31a2,2,0,0,0,2-2H6V7h6.49l2.61,3.59a1,1,0,0,0,.81.41h2.73A3.66,3.66,0,0,1,19,9.89L19.56,9H16.42L14.11,5.82A2,2,0,0,0,12.49,5H6A2,2,0,0,0,4,7V29a2,2,0,0,0,2,2H30a2,2,0,0,0,2-2V15.4Z"/>',
outlineBadged:
'<path d="M30,13.5V29H6V13h7.31a2,2,0,0,0,2-2H6V7h6.49l2.61,3.59a1,1,0,0,0,.81.41h8.51a7.5,7.5,0,0,1-1.29-2H16.42L14.11,5.82A2,2,0,0,0,12.49,5H6A2,2,0,0,0,4,7V29a2,2,0,0,0,2,2H30a2,2,0,0,0,2-2V13.22A7.49,7.49,0,0,1,30,13.5Z"/>',
solid:
'<path d="M30,9H16.42L14.11,5.82A2,2,0,0,0,12.49,5H6A2,2,0,0,0,4,7V29a2,2,0,0,0,2,2H30a2,2,0,0,0,2-2V11A2,2,0,0,0,30,9ZM6,11V7h6.49l2.72,4Z"/>',
solidAlerted:
'<path d="M22.23,15.4A3.68,3.68,0,0,1,19,9.89L19.56,9H16.42L14.11,5.82A2,2,0,0,0,12.49,5H6A2,2,0,0,0,4,7V29a2,2,0,0,0,2,2H30a2,2,0,0,0,2-2V15.4ZM6,11V7h6.49l2.72,4Z"/>',
solidBadged:
'<path d="M30,13.5A7.5,7.5,0,0,1,23.13,9H16.42L14.11,5.82A2,2,0,0,0,12.49,5H6A2,2,0,0,0,4,7V29a2,2,0,0,0,2,2H30a2,2,0,0,0,2-2V13.22A7.49,7.49,0,0,1,30,13.5ZM6,11V7h6.49l2.72,4Z"/>',
};
export const folderIconName = 'folder';
export const folderIcon: IconShapeTuple = [folderIconName, renderIcon(icon)];
``` | /content/code_sandbox/packages/core/src/icon/shapes/folder.ts | xml | 2016-09-29T17:24:17 | 2024-08-11T17:06:15 | clarity | vmware-archive/clarity | 6,431 | 1,056 |
```xml
import {
AnyObjectNode,
NodeLifeCycle,
Hook,
escapeJsonPath,
EventHandlers,
IAnyType,
IDisposer,
devMode,
MstError
} from "../../internal"
import { createAtom, IAtom } from "mobx"
type HookSubscribers = {
[Hook.afterAttach]: (node: AnyNode, hook: Hook) => void
[Hook.afterCreate]: (node: AnyNode, hook: Hook) => void
[Hook.afterCreationFinalization]: (node: AnyNode, hook: Hook) => void
[Hook.beforeDestroy]: (node: AnyNode, hook: Hook) => void
[Hook.beforeDetach]: (node: AnyNode, hook: Hook) => void
}
/**
* @internal
* @hidden
*/
export abstract class BaseNode<C, S, T> {
private _escapedSubpath?: string
private _subpath!: string
get subpath() {
return this._subpath
}
private _subpathUponDeath?: string
get subpathUponDeath() {
return this._subpathUponDeath
}
private _pathUponDeath?: string
protected get pathUponDeath() {
return this._pathUponDeath
}
storedValue!: any // usually the same type as the value, but not always (such as with references)
get value(): T {
return (this.type as any).getValue(this)
}
private aliveAtom?: IAtom
private _state = NodeLifeCycle.INITIALIZING
get state() {
return this._state
}
set state(val: NodeLifeCycle) {
const wasAlive = this.isAlive
this._state = val
const isAlive = this.isAlive
if (this.aliveAtom && wasAlive !== isAlive) {
this.aliveAtom.reportChanged()
}
}
private _hookSubscribers?: EventHandlers<HookSubscribers>
protected abstract fireHook(name: Hook): void
protected fireInternalHook(name: Hook) {
if (this._hookSubscribers) {
this._hookSubscribers.emit(name, this, name)
}
}
registerHook<H extends Hook>(hook: H, hookHandler: HookSubscribers[H]): IDisposer {
if (!this._hookSubscribers) {
this._hookSubscribers = new EventHandlers()
}
return this._hookSubscribers.register(hook, hookHandler)
}
private _parent!: AnyObjectNode | null
get parent() {
return this._parent
}
constructor(
readonly type: IAnyType,
parent: AnyObjectNode | null,
subpath: string,
public environment: any
) {
this.environment = environment
this.baseSetParent(parent, subpath)
}
getReconciliationType() {
return this.type
}
private pathAtom?: IAtom
protected baseSetParent(parent: AnyObjectNode | null, subpath: string) {
this._parent = parent
this._subpath = subpath
this._escapedSubpath = undefined // regenerate when needed
if (this.pathAtom) {
this.pathAtom.reportChanged()
}
}
/*
* Returns (escaped) path representation as string
*/
get path(): string {
return this.getEscapedPath(true)
}
protected getEscapedPath(reportObserved: boolean): string {
if (reportObserved) {
if (!this.pathAtom) {
this.pathAtom = createAtom(`path`)
}
this.pathAtom.reportObserved()
}
if (!this.parent) return ""
// regenerate escaped subpath if needed
if (this._escapedSubpath === undefined) {
this._escapedSubpath = !this._subpath ? "" : escapeJsonPath(this._subpath)
}
return this.parent.getEscapedPath(reportObserved) + "/" + this._escapedSubpath
}
get isRoot(): boolean {
return this.parent === null
}
abstract get root(): AnyObjectNode
abstract setParent(newParent: AnyObjectNode | null, subpath: string | null): void
abstract get snapshot(): S
abstract getSnapshot(): S
get isAlive() {
return this.state !== NodeLifeCycle.DEAD
}
get isDetaching() {
return this.state === NodeLifeCycle.DETACHING
}
get observableIsAlive() {
if (!this.aliveAtom) {
this.aliveAtom = createAtom(`alive`)
}
this.aliveAtom.reportObserved()
return this.isAlive
}
abstract die(): void
abstract finalizeCreation(): void
protected baseFinalizeCreation(whenFinalized?: () => void) {
if (devMode()) {
if (!this.isAlive) {
// istanbul ignore next
throw new MstError(
"assertion failed: cannot finalize the creation of a node that is already dead"
)
}
}
// goal: afterCreate hooks runs depth-first. After attach runs parent first, so on afterAttach the parent has completed already
if (this.state === NodeLifeCycle.CREATED) {
if (this.parent) {
if (this.parent.state !== NodeLifeCycle.FINALIZED) {
// parent not ready yet, postpone
return
}
this.fireHook(Hook.afterAttach)
}
this.state = NodeLifeCycle.FINALIZED
if (whenFinalized) {
whenFinalized()
}
}
}
abstract finalizeDeath(): void
protected baseFinalizeDeath() {
if (this._hookSubscribers) {
this._hookSubscribers.clearAll()
}
this._subpathUponDeath = this._subpath
this._pathUponDeath = this.getEscapedPath(false)
this.baseSetParent(null, "")
this.state = NodeLifeCycle.DEAD
}
abstract aboutToDie(): void
protected baseAboutToDie() {
this.fireHook(Hook.beforeDestroy)
}
}
/**
* @internal
* @hidden
*/
export type AnyNode = BaseNode<any, any, any>
``` | /content/code_sandbox/src/core/node/BaseNode.ts | xml | 2016-09-04T18:28:25 | 2024-08-16T08:48:55 | mobx-state-tree | mobxjs/mobx-state-tree | 6,917 | 1,339 |
```xml
declare module 'jsonlines' {
import { Transform } from 'stream';
function parse(): Transform;
}
``` | /content/code_sandbox/packages/cli/types/jsonlines/index.d.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 24 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="20dp"
android:background="#ff0001"
android:gravity="center"
android:text=" bootom_sheet_dialog "
android:textColor="@android:color/white"/>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/activity_dialog.xml | xml | 2016-08-08T08:52:10 | 2024-08-12T19:24:13 | AndroidAnimationExercise | REBOOTERS/AndroidAnimationExercise | 1,868 | 129 |
```xml
/*
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
path_to_url
*/
import './_version.js';
// * * * IMPORTANT! * * *
// your_sha256_hash--------- //
// jdsoc type definitions cannot be declared above TypeScript definitions or
// they'll be stripped from the built `.js` files, and they'll only be in the
// `d.ts` files, which aren't read by the jsdoc generator. As a result we
// have to put declare them below.
/**
* The "match" callback is used to determine if a `Route` should apply for a
* particular URL. When matching occurs in response to a fetch event from the
* client, the `event` object is supplied in addition to the `url`, `request`,
* and `sameOrigin` value. However, since the match callback can be invoked
* outside of a fetch event, matching logic should not assume the `event`
* object will always be available.
*
* If the match callback returns a truthy value, the matching route's
* {@link workbox-routing~handlerCallback} will be
* invoked immediately. If the value returned is a non-empty array or object,
* that value will be set on the handler's `context.params` argument.
*
* @callback ~matchCallback
* @param {Object} context
* @param {Request} context.request The corresponding request.
* @param {URL} context.url The request's URL.
* @param {ExtendableEvent} context.event The corresponding event that triggered
* the request.
* @param {boolean} context.sameOrigin The result of comparing `url.origin`
* against the current origin.
* @return {*} To signify a match, return a truthy value.
*
* @memberof workbox-routing
*/
/**
* The "handler" callback is invoked whenever a `Router` matches a URL to a
* `Route` via its {@link workbox-routing~matchCallback}
* callback. This callback should return a Promise that resolves with a
* `Response`.
*
* If a non-empty array or object is returned by the
* {@link workbox-routing~matchCallback} it
* will be passed in as the handler's `context.params` argument.
*
* @callback ~handlerCallback
* @param {Object} context
* @param {Request|string} context.request The corresponding request.
* @param {URL} context.url The URL that matched, if available.
* @param {ExtendableEvent} context.event The corresponding event that triggered
* the request.
* @param {Object} [context.params] Array or Object parameters returned by the
* Route's {@link workbox-routing~matchCallback}.
* This will be undefined if an empty array or object were returned.
* @return {Promise<Response>} The response that will fulfill the request.
*
* @memberof workbox-routing
*/
``` | /content/code_sandbox/packages/workbox-routing/src/_types.ts | xml | 2016-04-04T15:55:19 | 2024-08-16T08:33:26 | workbox | GoogleChrome/workbox | 12,245 | 621 |
```xml
import * as React from "react";
import styled from "styled-components";
import PlaceholderText from "~/components/PlaceholderText";
function PlaceholderCollections(props: React.HTMLAttributes<HTMLDivElement>) {
return (
<Wrapper {...props}>
<PlaceholderText />
<PlaceholderText delay={0.2} />
<PlaceholderText delay={0.4} />
</Wrapper>
);
}
const Wrapper = styled.div`
margin: 4px 12px;
width: 75%;
`;
export default PlaceholderCollections;
``` | /content/code_sandbox/app/components/Sidebar/components/PlaceholderCollections.tsx | xml | 2016-05-22T21:31:47 | 2024-08-16T19:57:22 | outline | outline/outline | 26,751 | 109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.