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 /* eslint-disable @typescript-eslint/no-explicit-any */ import * as React from "react"; import styles from "./News.module.scss"; import { INewsProps } from "./INewsProps"; import { INewsState } from "./INewsState"; import dataservices from "../../services/dataservices"; import { NewsItem } from "./NewsItem/NewsItem"; import { NoNews } from "./NoNews"; import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle"; import { NewsTile } from "./NewsTile/NewsTile"; import * as strings from "NewsWebPartStrings"; import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder"; import { Spinner, SpinnerSize, MessageBar, MessageBarType} from "office-ui-fabric-react"; import { INewsResults } from "../../services/INewsResults"; import Pagination from "@material-ui/lab/Pagination"; export default class News extends React.Component<INewsProps, INewsState> { constructor(props: INewsProps) { super(props); this.state = { isLoading: false, hasError: false, errorMesage: null, articles: [], currentPage: 1, totalPages: 0 }; } private _onConfigure = () => { this.props.context.propertyPane.open(); } // Component Did Mount public async componentDidMount(): Promise<void> { //await dataservices.init(this.props.context); this._getNews( this.props.newsUrl, this.props.apiKey, this.state.currentPage, ); } // Component Did Update public async componentDidUpdate( prevProps: INewsProps ): Promise<void> { if ( this.props.newsUrl !== prevProps.newsUrl || this.props.apiKey !== prevProps.apiKey ) { this._getNews( this.props.newsUrl, this.props.apiKey, 1 // force current page to 1 because new propeerties defined ); } } // Get News from newsApi.org private _getNews = async (newsUrl: string, apiKey: string, page?: number) => { try { const { pageSize } = this.props; this.setState({ isLoading: true, hasError: false, errorMesage: "" }); const results:any = await dataservices.getNews(newsUrl, apiKey, page); if (results && results.status == "error") { throw new Error(results.message); } // calculate number of pages let _reminder: number = (results as INewsResults).totalResults % pageSize; // get Reminder _reminder = _reminder ? 1 : 0; const _totalPages: number = parseInt((results.totalResults / pageSize).toString()) + _reminder; this.setState({ articles: results ? results.articles : [], isLoading: false, hasError: false, errorMesage: "", totalPages: _totalPages, currentPage: page }); } catch (error) { console.log("error", error); this.setState({ isLoading: false, hasError: true, errorMesage: error.message }); } } // Render WebPart public render(): React.ReactElement<INewsProps> { const { isLoading, errorMesage, articles, hasError } = this.state; const _renderNews: JSX.Element[] = []; if (articles && articles.length > 0) { for (const article of articles) { if (!this.props.viewOption || this.props.viewOption == "list") { _renderNews.push(<NewsItem article={article} key={article.title} />); } else { _renderNews.push(<NewsTile article={article} key={article.title} />); } } } return ( <div className={styles.News}> {!this.props.apiKey || !this.props.newsUrl ? ( <Placeholder iconName="Edit" iconText={strings.ConfigureWebPartMessage} description={strings.configureWebPartTextMessage} buttonLabel={strings.ConfigureWebPartButtonLabel} onConfigure={this._onConfigure} /> ) : ( <> <WebPartTitle displayMode={this.props.displayMode} title={this.props.title} className={styles.title} updateProperty={this.props.updateProperty} /> {isLoading ? ( <Spinner size={SpinnerSize.medium} label="Loading..." /> ) : hasError ? ( <> <MessageBar messageBarType={MessageBarType.error}> {errorMesage} </MessageBar> </> ) : _renderNews.length > 0 ? ( <> <div className={ this.props.viewOption == "tiles" ? styles.cardsTiles : styles.cardsItem } > {_renderNews} </div> <div style={{ display: "flex", marginTop: 10, marginBottom: 20, justifyContent: "center" }} > {this.state.totalPages > 1 && ( <> <Pagination color="primary" count={this.state.totalPages} page={this.state.currentPage} style={{marginTop: 30}} onChange={(event, page) => { this._getNews( this.props.newsUrl, this.props.apiKey, page ); }} /> </> )} </div> </> ) : ( <NoNews /> )} </> )} </div> ); } } ```
/content/code_sandbox/samples/react-global-news-sp2019/src/webparts/components/News.tsx
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
1,199
```xml import {isFunction, Store} from "@tsed/core"; import {DIContext, InjectorService, Provider, runInContext} from "@tsed/di"; import {deserialize} from "@tsed/json-mapper"; import {$log} from "@tsed/logger"; import {Namespace, Socket} from "socket.io"; import {SocketFilters} from "../interfaces/SocketFilters.js"; import {SocketHandlerMetadata} from "../interfaces/SocketHandlerMetadata.js"; import {SocketInjectableNsp} from "../interfaces/SocketInjectableNsp.js"; import {SocketParamMetadata} from "../interfaces/SocketParamMetadata.js"; import {SocketProviderTypes} from "../interfaces/SocketProviderTypes.js"; import {SocketReturnsTypes} from "../interfaces/SocketReturnsTypes.js"; import {SocketProviderMetadata} from "./SocketProviderMetadata.js"; import {SocketSessionData} from "./SocketSessionData.js"; import {v4} from "uuid"; /** * @ignore */ export class SocketHandlersBuilder { private readonly socketProviderMetadata: SocketProviderMetadata; constructor( private readonly provider: Provider, private readonly injector: InjectorService ) { this.socketProviderMetadata = new SocketProviderMetadata(this.provider.store.get("socketIO")); } /** * * @param {SocketHandlerMetadata} handlerMetadata * @param scope * @returns {(data) => void} */ private static bindResponseMiddleware(handlerMetadata: SocketHandlerMetadata, scope: any) { const {returns} = handlerMetadata; return (response: any): void => { if (returns) { switch (returns.type) { case SocketReturnsTypes.BROADCAST: scope.nsp.emit(returns.eventName, response); break; case SocketReturnsTypes.BROADCAST_OTHERS: scope.socket.broadcast.emit(returns.eventName, response); break; case SocketReturnsTypes.EMIT: scope.socket.emit(returns.eventName, response); break; } } else { const cb = scope.args.at(-1); if (cb && isFunction(cb)) { cb(response); } } }; } /** * * @returns {any} */ public build(nsps: Map<string | RegExp, Namespace>) { const instance = this.injector.get(this.provider.token); const {injectNamespaces, namespace} = this.socketProviderMetadata; const nsp = nsps.get(namespace); instance.$onConnection && this.socketProviderMetadata.createHook("$onConnection", "connection"); instance.$onDisconnect && this.socketProviderMetadata.createHook("$onDisconnect", "disconnect"); injectNamespaces.forEach((setting: SocketInjectableNsp) => { instance[setting.propertyKey] = nsps.get(setting.nsp || namespace); }); instance["nsp"] = nsp; if (instance.$onNamespaceInit) { instance.$onNamespaceInit(nsp); } return this; } /** * * @param {Socket} socket * @param {Namespace} nsp */ public async onConnection(socket: Socket, nsp: Namespace) { const {socketProviderMetadata} = this; const instance = this.injector.get(this.provider.token); this.buildHandlers(socket, nsp); if (instance.$onConnection) { const ctx = this.createContext(socket, nsp); await runInContext(ctx, () => this.invoke(instance, socketProviderMetadata.$onConnection, {socket, nsp}), this.injector); } } public async onDisconnect(socket: Socket, nsp: Namespace, reason?: string) { const instance = this.injector.get(this.provider.token); const {socketProviderMetadata} = this; if (instance.$onDisconnect) { const ctx = this.createContext(socket, nsp); await runInContext(ctx, () => this.invoke(instance, socketProviderMetadata.$onDisconnect, {socket, nsp, reason}), this.injector); } } private buildHandlers(socket: Socket, nsp: Namespace) { const {socketProviderMetadata} = this; socketProviderMetadata.getHandlers().forEach((handler) => { const {eventName} = handler; if (eventName) { socket.on(eventName, async (...args) => { const ctx = this.createContext(socket, nsp); await runInContext(ctx, () => this.runQueue(handler, args, socket, nsp), this.injector); }); } }); } private runQueue(handlerMetadata: SocketHandlerMetadata, args: any[], socket: Socket, nsp: Namespace) { const instance = this.injector.get(this.provider.token); const {useBefore, useAfter} = this.socketProviderMetadata; const scope = { args, socket, nsp, eventName: handlerMetadata.eventName }; let promise = Promise.resolve().then(() => this.deserialize(handlerMetadata, scope)); if (useBefore) { useBefore.forEach((target: any) => (promise = this.bindMiddleware(target, scope, promise))); } if (handlerMetadata.useBefore) { handlerMetadata.useBefore.forEach((target) => (promise = this.bindMiddleware(target, scope, promise))); } promise = promise .then(() => this.invoke(instance, handlerMetadata, scope)) .then(SocketHandlersBuilder.bindResponseMiddleware(handlerMetadata, scope)); if (handlerMetadata.useAfter) { handlerMetadata.useAfter.forEach((target) => (promise = this.bindMiddleware(target, scope, promise))); } if (useAfter) { useAfter.forEach((target: any) => (promise = this.bindMiddleware(target, scope, promise))); } return promise.catch((er: any) => { /* istanbul ignore next */ $log.error(handlerMetadata.eventName, er); }); } private deserialize(handlerMetadata: SocketHandlerMetadata, scope: any) { const {parameters} = handlerMetadata; Object.keys(parameters || []).forEach((index: any) => { const {filter, useMapper, mapIndex, type, collectionType} = parameters![index]; let value = scope.args[mapIndex!]; if (filter === SocketFilters.ARGS) { if (useMapper && typeof value !== "function") { value = deserialize(value, { type, collectionType, useAlias: true }); } scope.args[mapIndex!] = value; } }); } private bindMiddleware(target: any, scope: any, promise: Promise<any>): Promise<any> { const instance = this.injector.get(target); if (instance) { const handlerMetadata: SocketProviderMetadata = new SocketProviderMetadata(Store.from(instance).get("socketIO")); if (handlerMetadata.type === SocketProviderTypes.MIDDLEWARE) { if (handlerMetadata.error) { return promise.catch((error: any) => this.invoke(instance, handlerMetadata.useHandler, {error, ...scope})); } return promise .then(() => this.invoke(instance, handlerMetadata.useHandler, scope)) .then((result: any) => { if (result) { scope.args = [].concat(result); } }); } } return promise; } private invoke(instance: any, handlerMetadata: SocketHandlerMetadata, scope: any): Promise<any> { const {methodClassName, parameters} = handlerMetadata; return instance[methodClassName](...this.buildParameters(parameters!, scope)); } private buildParameters(parameters: {[key: number]: SocketParamMetadata}, scope: any): any[] { return Object.keys(parameters || []).map((index: any) => { const param: SocketParamMetadata = parameters[index]; switch (param.filter) { case SocketFilters.ARGS: if (param.mapIndex !== undefined) { return scope.args[param.mapIndex]; } return scope.args; case SocketFilters.EVENT_NAME: return scope.eventName; case SocketFilters.SOCKET: return scope.socket; case SocketFilters.NSP: return scope.nsp; case SocketFilters.ERR: return scope.error; case SocketFilters.SESSION: return new SocketSessionData(scope.socket.data); case SocketFilters.RAW_SESSION: return scope.socket.data; case SocketFilters.SOCKET_NSP: return scope.socket.nsp; case SocketFilters.REASON: return scope.reason; } }); } private createContext(socket: Socket, nsp: Namespace): DIContext { return new DIContext({ injector: this.injector, id: v4().split("-").join(""), logger: this.injector.logger, additionalProps: { module: "socket.io", sid: socket.id, namespace: nsp.name } }); } } ```
/content/code_sandbox/packages/third-parties/socketio/src/class/SocketHandlersBuilder.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
1,878
```xml // See LICENSE in the project root for license information. import type { LoaderContext, LoaderDefinitionFunction } from 'webpack'; import type { NewlineKind } from '@rushstack/node-core-library'; import { Terminal } from '@rushstack/terminal'; import { parseLocFile } from '@rushstack/localization-utilities'; import type { LocalizationPlugin } from '../LocalizationPlugin'; import { createLoader, type IBaseLocLoaderOptions } from './LoaderFactory'; import { LoaderTerminalProvider } from '../utilities/LoaderTerminalProvider'; export interface ILocLoaderOptions extends IBaseLocLoaderOptions { pluginInstance: LocalizationPlugin; resxNewlineNormalization: NewlineKind | undefined; ignoreMissingResxComments: boolean | undefined; } /** * General purpose loader that dispatches based on file extension. */ const loader: LoaderDefinitionFunction<ILocLoaderOptions> = createLoader( (content: string, filePath: string, context: LoaderContext<ILocLoaderOptions>) => { const options: ILocLoaderOptions = context.getOptions(); const terminal: Terminal = new Terminal(LoaderTerminalProvider.getTerminalProviderForLoader(context)); return parseLocFile({ ...options, terminal, content, filePath }); } ); export default loader; ```
/content/code_sandbox/webpack/webpack5-localization-plugin/src/loaders/loc-loader.ts
xml
2016-09-30T00:28:20
2024-08-16T18:54:35
rushstack
microsoft/rushstack
5,790
266
```xml import { fullscreenMegaState } from "../gfx/helpers/GfxMegaStateDescriptorHelpers.js"; import { GfxShaderLibrary } from "../gfx/helpers/GfxShaderLibrary.js"; import { GfxBindingLayoutDescriptor, GfxDevice, GfxFormat, GfxMipFilterMode, GfxTexFilterMode, GfxWrapMode } from "../gfx/platform/GfxPlatform.js"; import { GfxProgram } from "../gfx/platform/GfxPlatformImpl.js"; import { GfxRenderCache } from "../gfx/render/GfxRenderCache.js"; import { GfxrAttachmentSlot, GfxrRenderTargetDescription, GfxrGraphBuilder, GfxrRenderTargetID } from "../gfx/render/GfxRenderGraph.js"; import { GfxRenderInstManager } from "../gfx/render/GfxRenderInstManager.js"; import { DeviceProgram } from "../Program.js"; import { TextureMapping } from "../TextureHolder.js"; /** * A program to transfer the depth buffer to a texture. * * This performs the following functions beyond sampling the depth buffer directly: * - Reverses depth values * - Adjusts near and far planes to be faithful to those expected by the original game's shaders * - Outputs to a color texture to allow for bilinear filtering */ class DepthResamplerProgram extends DeviceProgram { public override frag: string = ` uniform sampler2D u_DepthTexture; in vec2 v_TexCoord; // TODO: implement near-far scaling void main() { float d = 1.0 - texture(SAMPLER_2D(u_DepthTexture), v_TexCoord).r; gl_FragColor = vec4(d); } `; public override vert = GfxShaderLibrary.fullscreenVS; } const bindingLayouts: GfxBindingLayoutDescriptor[] = [{ numUniformBuffers: 0, numSamplers: 1 }]; export class DepthResampler { private program: GfxProgram; private textureMapping = new TextureMapping(); private targetDesc = new GfxrRenderTargetDescription(GfxFormat.U8_RGBA_RT); // FIXME: use R-only format intead? constructor(device: GfxDevice, cache: GfxRenderCache) { this.program = cache.createProgram(new DepthResamplerProgram()); this.textureMapping.gfxSampler = cache.createSampler({ wrapS: GfxWrapMode.Clamp, wrapT: GfxWrapMode.Clamp, minFilter: GfxTexFilterMode.Point, magFilter: GfxTexFilterMode.Point, mipFilter: GfxMipFilterMode.Nearest, minLOD: 0, maxLOD: 100, }) } public render(device: GfxDevice, builder: GfxrGraphBuilder, renderInstManager: GfxRenderInstManager, depthInputTargetID: GfxrRenderTargetID): GfxrRenderTargetID { const inputTargetDesc = builder.getRenderTargetDescription(depthInputTargetID); this.targetDesc.setDimensions(inputTargetDesc.width, inputTargetDesc.height, 1); const depthOutputTargetID = builder.createRenderTargetID(this.targetDesc, 'Depth Resampler Output'); const renderInst = renderInstManager.newRenderInst(); renderInst.setAllowSkippingIfPipelineNotReady(false); renderInst.setGfxProgram(this.program); renderInst.setMegaStateFlags(fullscreenMegaState); renderInst.setBindingLayouts(bindingLayouts); renderInst.setDrawCount(3); builder.pushPass((pass) => { pass.setDebugName('Resample Depth'); pass.attachRenderTargetID(GfxrAttachmentSlot.Color0, depthOutputTargetID); const resolveTextureID = builder.resolveRenderTarget(depthInputTargetID); pass.attachResolveTexture(resolveTextureID); pass.exec((passRenderer, scope) => { this.textureMapping.gfxTexture = scope.getResolveTextureForID(resolveTextureID); renderInst.setSamplerBindingsFromTextureMappings([this.textureMapping]); renderInst.drawOnPass(renderInstManager.gfxRenderCache, passRenderer); }); }); return depthOutputTargetID; } } ```
/content/code_sandbox/src/StarFoxAdventures/depthresampler.ts
xml
2016-10-06T21:43:45
2024-08-16T17:03:52
noclip.website
magcius/noclip.website
3,206
860
```xml /** * @license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * MDCChipActionCssClasses provides the classes to be queried and manipulated on * the root. */ export enum MDCChipActionCssClasses { PRIMARY_ACTION = 'mdc-evolution-chip__action--primary', TRAILING_ACTION = 'mdc-evolution-chip__action--trailing', CHIP_ROOT = 'mdc-evolution-chip', } /** * MDCChipActionInteractionTrigger provides detail of the different triggers for * action interactions. */ export enum MDCChipActionInteractionTrigger { UNSPECIFIED, // Default type CLICK, BACKSPACE_KEY, DELETE_KEY, SPACEBAR_KEY, ENTER_KEY, } /** * MDCChipActionType provides the different types of available actions. */ export enum MDCChipActionType { UNSPECIFIED, // Default type PRIMARY, TRAILING, } /** * MDCChipActionEvents provides the different events emitted by the action. */ export enum MDCChipActionEvents { INTERACTION = 'MDCChipAction:interaction', NAVIGATION = 'MDCChipAction:navigation', } /** * MDCChipActionFocusBehavior provides configurations for focusing or unfocusing * an action. */ export enum MDCChipActionFocusBehavior { FOCUSABLE, FOCUSABLE_AND_FOCUSED, NOT_FOCUSABLE, } /** * MDCChipActionAttributes provides the HTML attributes used by the foundation. */ export enum MDCChipActionAttributes { ARIA_DISABLED = 'aria-disabled', ARIA_HIDDEN = 'aria-hidden', ARIA_SELECTED = 'aria-selected', DATA_DELETABLE = 'data-mdc-deletable', DISABLED = 'disabled', ROLE = 'role', TAB_INDEX = 'tabindex', } ```
/content/code_sandbox/packages/mdc-chips/action/constants.ts
xml
2016-12-05T16:04:09
2024-08-16T15:42:22
material-components-web
material-components/material-components-web
17,119
600
```xml import * as React from 'react'; import { mount, shallow } from 'enzyme'; import { CdsInternalVisualCheckbox } from './index'; describe('CdsInternalVisualCheckbox', () => { it('renders', () => { const wrapper = shallow( <div> <CdsInternalVisualCheckbox /> </div> ); const renderedComponent = wrapper.find(CdsInternalVisualCheckbox); expect(renderedComponent).toBeTruthy(); }); it('snapshot', () => { const wrapper = mount( <div> <CdsInternalVisualCheckbox /> </div> ); expect(wrapper).toMatchSnapshot(); }); }); ```
/content/code_sandbox/packages/react/src/internal-components/visual-checkbox/index.test.tsx
xml
2016-09-29T17:24:17
2024-08-11T17:06:15
clarity
vmware-archive/clarity
6,431
138
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "path_to_url"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">pankaj123</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property> <property name="hibernate.connection.username">pankaj</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <mapping class="com.journaldev.hibernate.model.Cart1" /> <mapping class="com.journaldev.hibernate.model.Item1" /> </session-factory> </hibernate-configuration> ```
/content/code_sandbox/Hibernate/HibernateManyToManyMapping/src/main/resources/hibernate-annotation.cfg.xml
xml
2016-05-02T05:43:21
2024-08-16T06:51:39
journaldev
WebJournal/journaldev
1,314
239
```xml /* * path_to_url * * or in the 'license' file accompanying this file. This file is distributed * on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either */ import { dynamicEndpoints } from 'ask-sdk-model'; export class DynamicEndpointsRequest implements dynamicEndpoints.Request { public version: string; public type: string; public requestId: string; public requestPayload: string; } ```
/content/code_sandbox/ask-sdk-local-debug/lib/request/DynamicEndpointsRequest.ts
xml
2016-06-24T06:26:05
2024-08-14T12:39:19
alexa-skills-kit-sdk-for-nodejs
alexa/alexa-skills-kit-sdk-for-nodejs
3,118
93
```xml <?jelly escape-by-default='true'?> <div> This plugin is a part of Blue Ocean UI </div> ```
/content/code_sandbox/blueocean-rest/src/main/resources/index.jelly
xml
2016-01-23T18:02:45
2024-08-13T04:31:34
blueocean-plugin
jenkinsci/blueocean-plugin
2,874
27
```xml import { TFabricPlatformPageProps } from '../../../interfaces/Platforms'; import { ThemeProviderPageProps as ExternalProps } from '@fluentui/react-examples/lib/react/ThemeProvider/ThemeProvider.doc'; import { ISideRailLink } from '@fluentui/react-docsite-components/lib/index2'; const related: ISideRailLink[] = []; export const ThemeProviderProps: TFabricPlatformPageProps = { web: { ...(ExternalProps as any), related, }, }; ```
/content/code_sandbox/apps/public-docsite/src/pages/Controls/ThemeProviderPage/ThemeProviderPage.doc.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
101
```xml import Plotly, { PlotlyHTMLElement } from "plotly.js-basic-dist-min"; import _ from "lodash"; type Params = { readonly type: "line" | "scatter" | "bar" | "area" | "pie"; readonly stacking: 0 | string; readonly groupBy: string[]; readonly rows: (string | number)[][]; readonly fields: string[]; readonly x: string; readonly y: string[]; }; export default class Chart { private readonly params: Params; constructor(params: Params) { this.params = params; } drawTo(dom: HTMLElement): Promise<PlotlyHTMLElement> { return Plotly.newPlot(dom, this.getData(), this.getLayout(), { displayModeBar: false, responsive: true, }); } async toSVG({ width }: { width: number }): Promise<string | null> { const data = this.getData(); const layout = this.getLayout(); const div = document.createElement("div"); if (data.length === 0) { return Promise.resolve(null); } const gd = await Plotly.plot(div, data, layout); // aspect ratio (450:700) is default of plotly.js // path_to_url#layout-width // path_to_url#layout-height const height = Math.floor((width * 450) / 700); return Plotly.toImage(gd, { format: "svg", width, height }).then((svg) => { const dataURI = decodeURIComponent(svg); return dataURI.substr(dataURI.indexOf(",") + 1).replace(/"Open Sans"/g, "'Open Sans'"); }); } getData(): Partial<Plotly.PlotData>[] { return this[this.params.type](); } getLayout(): Partial<Plotly.Layout> { const layout: Partial<Plotly.Layout> = { showlegend: true, margin: { l: 50, r: 50, t: 10, b: 10, pad: 4 }, hoverlabel: { namelength: -1 }, xaxis: { automargin: true }, yaxis: { automargin: true }, }; if (this.params.stacking === "enable") { layout.barmode = "stack"; } if (this.params.stacking === "percent") { layout.barmode = "stack"; layout.barnorm = "percent"; } return layout; } // TODO: Performance tuning generateChartData(): { x: (string | number)[]; y: (string | number)[]; name: string }[] { if (!this.params.y) return []; if (this.params.groupBy.length === 0 || _.difference(this.params.groupBy, this.params.fields).length > 0) { return this.params.y.map((y) => { return { x: this.dataByField(this.params.x), y: this.dataByField(y), name: y, }; }); } // NOTE: Can delete sort? const groupValues = this.params.groupBy.map((field) => _.uniq(this.dataByField(field)).sort()); const indices = this.params.groupBy.map((field) => this.rowIndexByFieldName(field)); const x = _.groupBy(this.params.rows, (row) => indices.map((idx) => row[idx])); // The cartesian product of group values const groupPairs = groupValues.reduce( (a: any[][], b: any[]) => _.flatMap(a, (x) => b.map((y) => x.concat([y]))), [[]] ); return _.flatMap(this.params.y, (y) => { const yIdx = this.rowIndexByFieldName(y); return groupPairs.map((g) => { const key = g.join(","); return { name: `${y} (${key})`, x: this.valuesByField(Object.prototype.hasOwnProperty.call(x, key) ? x[key] : [], this.params.x), y: this.params.rows .filter((row) => // For all group by indices, the values in row and g match. indices.reduce((a: boolean, b: number, i) => a && row[b] === g[i], true) ) .map((row) => row[yIdx]), }; }); }); } rowIndexByFieldName(field: string): number { return this.params.fields.findIndex((f) => f === field); } valuesByField(rows: (string | number)[][], field: string): (string | number)[] { const idx = this.rowIndexByFieldName(field); return rows.map((row) => row[idx]); } dataByField(field: string): (string | number)[] { return this.valuesByField(this.params.rows, field); } line(): Partial<Plotly.PlotData>[] { return this.generateChartData().map((data) => ({ type: "scatter", x: data.x, y: data.y, name: data.name, mode: "lines", })); } scatter(): Partial<Plotly.PlotData>[] { return this.generateChartData().map((data) => ({ type: "scatter", x: data.x, y: data.y, name: data.name, mode: "markers", marker: { size: 10 }, })); } bar(): Partial<Plotly.PlotData>[] { return this.generateChartData().map((data) => ({ type: "bar", x: data.x, y: data.y, name: data.name, })); } area(): Partial<Plotly.PlotData>[] { return this.generateChartData().map((data) => ({ type: "scatter", x: data.x, y: data.y, name: data.name, mode: "lines", fill: "tozeroy", })); } pie(): Partial<Plotly.PlotData>[] { return [ { type: "pie", direction: "clockwise", labels: this.dataByField(this.params.x), values: this.dataByField(this.params.y[0]), }, ]; } } ```
/content/code_sandbox/src/lib/Chart.ts
xml
2016-08-23T12:20:03
2024-08-14T08:26:34
bdash
bdash-app/bdash
1,488
1,347
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>BuildMachineOSBuild</key> <string>15C50</string> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>GPUSensors</string> <key>CFBundleIdentifier</key> <string>org.hwsensors.driver.GPUSensors</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>GPUSensors</string> <key>CFBundlePackageType</key> <string>KEXT</string> <key>CFBundleShortVersionString</key> <string>6.18-313-g671f31c.1707</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>CFBundleVersion</key> <string>1707</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string>7C68</string> <key>DTPlatformVersion</key> <string>GM</string> <key>DTSDKBuild</key> <string>12D75</string> <key>DTSDKName</key> <string>macosx10.8</string> <key>DTXcode</key> <string>0720</string> <key>DTXcodeBuild</key> <string>7C68</string> <key>IOKitPersonalities</key> <dict> <key>AMD Radeon Monitoring Plugin</key> <dict> <key>CFBundleIdentifier</key> <string>org.hwsensors.driver.GPUSensors</string> <key>IOClass</key> <string>RadeonSensors</string> <key>IOMatchCategory</key> <string>FakeSMCPlugin</string> <key>IOPCIClassMatch</key> <string>0x03000000&amp;0xff000000</string> <key>IOPCIMatch</key> <string>0x00001002&amp;0x0000ffff</string> <key>IOProbeScore</key> <string>40000</string> <key>IOProviderClass</key> <string>IOPCIDevice</string> <key>IOResourceMatch</key> <string>FakeSMCKeyStore</string> </dict> <key>Intel GMA X3100 Monitoring Plugin</key> <dict> <key>CFBundleIdentifier</key> <string>org.hwsensors.driver.GPUSensors</string> <key>IOClass</key> <string>GmaSensors</string> <key>IOMatchCategory</key> <string>FakeSMCPlugin</string> <key>IOPCIClassMatch</key> <string>0x03000000&amp;0xff0000000</string> <key>IOPCIMatch</key> <string>0x2a028086&amp;0xffffffff 0x2a128086&amp;0xffffffff</string> <key>IOProbeScore</key> <string>30000</string> <key>IOProviderClass</key> <string>IOPCIDevice</string> <key>IOResourceMatch</key> <string>FakeSMCKeyStore</string> </dict> <key>nVidia GeForce Monitoring Plugin</key> <dict> <key>CFBundleIdentifier</key> <string>org.hwsensors.driver.GPUSensors</string> <key>IOClass</key> <string>GeforceSensors</string> <key>IOMatchCategory</key> <string>FakeSMCPlugin</string> <key>IOPCIClassMatch</key> <string>0x03000000&amp;0xff000000</string> <key>IOPCIMatch</key> <string>0x000010de&amp;0x0000ffff</string> <key>IOProbeScore</key> <string>50000</string> <key>IOProviderClass</key> <string>IOPCIDevice</string> <key>IOResourceMatch</key> <string>FakeSMCKeyStore</string> </dict> </dict> <key>OSBundleLibraries</key> <dict> <key>com.apple.iokit.IOACPIFamily</key> <string>1.0.0d1</string> <key>com.apple.iokit.IOPCIFamily</key> <string>1.0.0b1</string> <key>com.apple.kpi.iokit</key> <string>10.6</string> <key>com.apple.kpi.libkern</key> <string>10.6</string> <key>com.apple.kpi.mach</key> <string>10.6</string> <key>com.apple.kpi.unsupported</key> <string>10.6</string> <key>org.netkas.driver.FakeSMC</key> <string>1212</string> </dict> <key>OSBundleRequired</key> <string>Root</string> <key>Source Code</key> <string>"path_to_url"</string> </dict> </plist> ```
/content/code_sandbox/Clover-Configs/Lenovo/Y480/CLOVER/kexts/10.11/FakeSMC_GPUSensors.kext/Contents/Info.plist
xml
2016-11-05T04:22:54
2024-08-12T19:25:53
Hackintosh-Installer-University
huangyz0918/Hackintosh-Installer-University
3,937
1,357
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsPackable>false</IsPackable> <OutputType>exe</OutputType> <DefineConstants Condition="'$(IsWindows)' == 'true'">$(DefineConstants);TEST_D3D11;TEST_VULKAN;TEST_OPENGL;TEST_OPENGLES</DefineConstants> <DefineConstants Condition="'$(IsLinux)' == 'true'">$(DefineConstants);TEST_VULKAN;TEST_OPENGL;TEST_OPENGLES</DefineConstants> <DefineConstants Condition="'$(IsMacOS)' == 'true'">$(DefineConstants);TEST_METAL;TEST_OPENGL</DefineConstants> <StartupObject>Program</StartupObject> </PropertyGroup> <ItemGroup> <PackageReference Include="Veldrid.SPIRV" Version="$(VeldridSpirvVersion)" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" /> <PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit.console" Version="2.4.2" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" /> <PackageReference Include="Xunit.SkippableFact" Version="1.4.13" /> <ProjectReference Include="..\Veldrid.RenderDoc\Veldrid.RenderDoc.csproj" /> <ProjectReference Include="..\Veldrid.SDL2\Veldrid.SDL2.csproj" /> <ProjectReference Include="..\Veldrid.StartupUtilities\Veldrid.StartupUtilities.csproj" /> <ProjectReference Include="..\Veldrid.Utilities\Veldrid.Utilities.csproj" /> <ProjectReference Include="..\Veldrid\Veldrid.csproj" /> </ItemGroup> <ItemGroup> <Content Include="$(MSBuildThisFileDirectory)..\Veldrid.SDL2\native\win-x64\SDL2.dll"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="$(MSBuildThisFileDirectory)..\Veldrid.SDL2\native\osx-x64\libsdl2.dylib"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="xunit.runner.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="Shaders/*" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> <ItemGroup> <None Remove="Shaders\ComputeCubemapGenerator.comp" /> <None Remove="Shaders\ComputeImage2DArrayGenerator.comp" /> <None Remove="Shaders\ComputeTextureGenerator.comp" /> <None Remove="Shaders\F16VertexAttribs.frag" /> <None Remove="Shaders\F16VertexAttribs.vert" /> <None Remove="Shaders\FullScreenBlit.frag" /> <None Remove="Shaders\FullScreenBlit.vert" /> <None Remove="Shaders\FullScreenTriSampleTexture2D.frag" /> <None Remove="Shaders\FullScreenTriSampleTexture2D.vert" /> <None Remove="Shaders\FullScreenTriSampleTextureArray.vert" /> <None Remove="Shaders\FullScreenWriteDepth.frag" /> <None Remove="Shaders\FullScreenWriteDepth.vert" /> <None Remove="Shaders\VertexLayoutTestShader.frag" /> <None Remove="Shaders\VertexLayoutTestShader.vert" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/Veldrid.Tests/Veldrid.Tests.csproj
xml
2016-02-25T23:00:28
2024-08-16T12:32:21
veldrid
veldrid/veldrid
2,456
808
```xml import type { ReactNode } from 'react'; interface Props { label: ReactNode; className?: string; children: ReactNode; } const RecipientType = ({ label, className = 'flex items-start flex-nowrap message-recipient-item-expanded max-w-full', children, }: Props) => { return ( <span className={className} data-testid={`message-header-expanded:${label}`}> <span className="container-to pt-2 text-semibold">{label}</span> <span className="self-center message-recipient-item-expanded-content">{children}</span> </span> ); }; export default RecipientType; ```
/content/code_sandbox/applications/mail/src/app/components/message/recipients/RecipientType.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
135
```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 /** * Computes the cosine of a double-precision floating-point number on `[-/4, /4]`. * * ## Notes * * - For increased accuracy, the number for which the cosine should be evaluated can be supplied as a double-double number (i.e., a non-evaluated sum of two double-precision floating-point numbers `x` and `y`). * - The two numbers must satisfy `|y| < 0.5 * ulp( x )`. * * @param x - input value (in radians, assumed to be bounded by ~pi/4 in magnitude) * @param y - tail of `x` * @returns cosine * * @example * var v = kernelCos( 0.0, 0.0 ); * // returns ~1.0 * * @example * var v = kernelCos( 3.141592653589793/6.0, 0.0 ); * // returns ~0.866 * * @example * var v = kernelCos( 0.785, -1.144e-17 ); * // returns ~0.707 * * @example * var v = kernelCos( NaN, 0.0 ); * // returns NaN */ declare function kernelCos( x: number, y: number ): number; // EXPORTS // export = kernelCos; ```
/content/code_sandbox/lib/node_modules/@stdlib/math/base/special/kernel-cos/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
351
```xml <vector xmlns:android="path_to_url" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <path android:fillColor="#FFBDBDBD" android:pathData="M11,18c0,1.1 -0.9,2 -2,2s-2,-0.9 -2,-2 0.9,-2 2,-2 2,0.9 2,2zM9,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM9,4c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM15,8c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM15,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM15,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"/> </vector> ```
/content/code_sandbox/Android/app/src/main/res/drawable/ic_drag_indicator_grey_400_24dp.xml
xml
2016-01-30T13:42:30
2024-08-12T19:21:10
Travel-Mate
project-travel-mate/Travel-Mate
1,292
374
```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 { CellActionDescriptor, DateEntityTableColumn, EntityTableColumn, EntityTableConfig } from '@home/models/entity/entities-table-config.models'; import { EntityType, EntityTypeResource, entityTypeTranslations } from '@shared/models/entity-type.models'; import { DatePipe } from '@angular/common'; import { Direction } from '@shared/models/page/sort-order'; import { Notification, NotificationStatus, NotificationTemplateTypeTranslateMap } from '@shared/models/notification.models'; import { NotificationService } from '@core/http/notification.service'; import { InboxTableHeaderComponent } from '@home/pages/notification/inbox/inbox-table-header.component'; import { TranslateService } from '@ngx-translate/core'; import { take } from 'rxjs/operators'; import { MatDialog } from '@angular/material/dialog'; import { InboxNotificationDialogComponent, InboxNotificationDialogData } from '@home/pages/notification/inbox/inbox-notification-dialog.component'; import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve } from '@angular/router'; import { UtilsService } from '@core/services/utils.service'; @Injectable() export class InboxTableConfigResolver implements Resolve<EntityTableConfig<Notification>> { private readonly config: EntityTableConfig<Notification> = new EntityTableConfig<Notification>(); constructor(private notificationService: NotificationService, private translate: TranslateService, private dialog: MatDialog, private datePipe: DatePipe, private utilsService: UtilsService) { this.config.entityType = EntityType.NOTIFICATION; this.config.detailsPanelEnabled = false; this.config.addEnabled = false; this.config.rowPointer = true; this.config.entityTranslations = entityTypeTranslations.get(EntityType.NOTIFICATION); this.config.entityResources = {} as EntityTypeResource<Notification>; this.config.deleteEntityTitle = () => this.translate.instant('notification.delete-notification-title'); this.config.deleteEntityContent = () => this.translate.instant('notification.delete-notification-text'); this.config.deleteEntitiesTitle = count => this.translate.instant('notification.delete-notifications-title', {count}); this.config.deleteEntitiesContent = () => this.translate.instant('notification.delete-notifications-text'); this.config.deleteEntity = id => this.notificationService.deleteNotification(id.id); this.config.entitiesFetchFunction = pageLink => this.notificationService.getNotifications(pageLink, this.config.componentsData.unreadOnly); this.config.defaultSortOrder = {property: 'createdTime', direction: Direction.DESC}; this.config.handleRowClick = ($event, notification) => { this.showNotification($event, notification); return true; }; this.config.componentsData = { unreadOnly: true }; this.config.cellActionDescriptors = this.configureCellActions(); this.config.headerComponent = InboxTableHeaderComponent; this.config.headerActionDescriptors = [{ name: this.translate.instant('notification.mark-all-as-read'), icon: 'done_all', isEnabled: () => true, onAction: $event => this.markAllRead($event) }]; this.config.columns.push( new DateEntityTableColumn<Notification>('createdTime', 'common.created-time', this.datePipe, '170px'), new EntityTableColumn<Notification>('type', 'notification.type', '10%', (notification) => this.translate.instant(NotificationTemplateTypeTranslateMap.get(notification.type).name)), new EntityTableColumn<Notification>('subject', 'notification.subject', '30%', (entity) => this.utilsService.customTranslation(entity.subject, entity.subject)), new EntityTableColumn<Notification>('text', 'notification.message', '60%', (entity) => this.utilsService.customTranslation(entity.text, entity.text)) ); } resolve(route: ActivatedRouteSnapshot): EntityTableConfig<Notification> { return this.config; } private configureCellActions(): Array<CellActionDescriptor<Notification>> { return [{ name: this.translate.instant('notification.mark-as-read'), icon: 'check_circle_outline', isEnabled: (notification) => notification.status !== NotificationStatus.READ, onAction: ($event, entity) => this.markAsRead($event, entity) }]; } private markAllRead($event: Event) { if ($event) { $event.stopPropagation(); } this.notificationService.markAllNotificationsAsRead().subscribe(() => { if (this.config.componentsData.unreadOnly) { this.config.getTable().resetSortAndFilter(true); } else { this.config.updateData(); } }); } private markAsRead($event, entity){ if ($event) { $event.stopPropagation(); } this.notificationService.markNotificationAsRead(entity.id.id).subscribe(() => { if (this.config.componentsData.unreadOnly) { this.config.getTable().dataSource.pageData$.pipe(take(1)).subscribe( (value) => { if (value.data.length === 1 && this.config.getTable().pageLink.page) { this.config.getTable().paginator.previousPage(); } else { this.config.updateData(); } } ); } else { entity.status = NotificationStatus.READ; this.config.getTable().detectChanges(); } }); } private showNotification($event: Event, notification: Notification) { if ($event) { $event.stopPropagation(); } this.dialog.open<InboxNotificationDialogComponent, InboxNotificationDialogData, string>(InboxNotificationDialogComponent, { disableClose: false, panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], data: { notification } }).afterClosed().subscribe(res => { if (res) { this.markAsRead(null, notification); } }); } } ```
/content/code_sandbox/ui-ngx/src/app/modules/home/pages/notification/inbox/inbox-table-config.resolver.ts
xml
2016-12-01T09:33:30
2024-08-16T19:58:25
thingsboard
thingsboard/thingsboard
16,820
1,219
```xml <?xml version="1.0" encoding="utf-8"?> <data> <messages> <ccp_dialog_title translation=" " /> <ccp_dialog_search_hint_message translation="..." /> <ccp_dialog_no_result_ack_message translation=" " /> </messages> <countries> <country name="" english_name="Andorra" name_code="ad" phone_code="376" /> <country name=" " english_name="United Arab Emirates (UAE)" name_code="ae" phone_code="971" /> <country name="" english_name="Afghanistan" name_code="af" phone_code="93" /> <country name=" " english_name="Antigua and Barbuda" name_code="ag" phone_code="1" /> <country name="" english_name="Anguilla" name_code="ai" phone_code="1" /> <country name="" english_name="Albania" name_code="al" phone_code="355" /> <country name="" english_name="Armenia" name_code="am" phone_code="374" /> <country name="" english_name="Angola" name_code="ao" phone_code="244" /> <country name="" english_name="Antarctica" name_code="aq" phone_code="672" /> <country name="" english_name="Argentina" name_code="ar" phone_code="54" /> <country name="" english_name="Austria" name_code="at" phone_code="43" /> <country name=" " english_name="American Samoa" name_code="as" phone_code="1" /> <country name=" ()" english_name="Australia" name_code="au" phone_code="61" /> <country name="" english_name="Aruba" name_code="aw" phone_code="297" /> <country name=" " english_name="land Islands" name_code="ax" phone_code="358" /> <country name="" english_name="Azerbaijan" name_code="az" phone_code="994" /> <country name=" " english_name="Bosnia And Herzegovina" name_code="ba" phone_code="387" /> <country name="Barbados" english_name="Barbados" name_code="bb" phone_code="1"/> <country name="" english_name="Bangladesh" name_code="bd" phone_code="880" /> <country name="" english_name="Belgium" name_code="be" phone_code="32" /> <country name="" english_name="Burkina Faso" name_code="bf" phone_code="226" /> <country name="" english_name="Bulgaria" name_code="bg" phone_code="359" /> <country name="" english_name="Bahrain" name_code="bh" phone_code="973" /> <country name="" english_name="Burundi" name_code="bi" phone_code="257" /> <country name="Benin" english_name="Benin" name_code="bj" phone_code="229" /> <country name="" english_name="Saint Barthlemy" name_code="bl" phone_code="590" /> <country name="" english_name="Bermuda" name_code="bm" phone_code="1"/> <country name="" english_name="Brunei Darussalam" name_code="bn" phone_code="673" /> <country name="" english_name="Bolivia, Plurinational State Of" name_code="bo" phone_code="591" /> <country name="" english_name="Brazil" name_code="br" phone_code="55" /> <country name="" english_name="Bahamas" name_code="bs" phone_code="1" /> <country name="" english_name="Bhutan" name_code="bt" phone_code="975" /> <country name="" english_name="Botswana" name_code="bw" phone_code="267" /> <country name="" english_name="Belarus" name_code="by" phone_code="375" /> <country name="Belize" english_name="Belize" name_code="bz" phone_code="501" /> <country name="" english_name="Canada" name_code="ca" phone_code="1" /> <country name=" " english_name="Cocos (keeling) Islands" name_code="cc" phone_code="61" /> <country name=" " english_name="Congo, The Democratic Republic Of The" name_code="cd" phone_code="243" /> <country name="" english_name="Central African Republic" name_code="cf" phone_code="236" /> <country name="" english_name="Congo" name_code="cg" phone_code="242" /> <country name="" english_name="Switzerland" name_code="ch" phone_code="41" /> <country name=" " english_name="Cte D'ivoire" name_code="ci" phone_code="225" /> <country name=" " english_name="Cook Islands" name_code="ck" phone_code="682" /> <country name="" english_name="Chile" name_code="cl" phone_code="56" /> <country name="" english_name="Cameroon" name_code="cm" phone_code="237" /> <country name="" english_name="China" name_code="cn" phone_code="86" /> <country name="" english_name="Colombia" name_code="co" phone_code="57" /> <country name="" english_name="Costa Rica" name_code="cr" phone_code="506" /> <country name="" english_name="Cuba" name_code="cu" phone_code="53" /> <country name="" english_name="Cape Verde" name_code="cv" phone_code="238" /> <country name=" " english_name="Curaao" name_code="cw" phone_code="599" /> <country name=" " english_name="Christmas Island" name_code="cx" phone_code="61" /> <country name="" english_name="Cyprus" name_code="cy" phone_code="357" /> <country name="" english_name="Czech Republic" name_code="cz" phone_code="420" /> <country name="" english_name="Germany" name_code="de" phone_code="49" /> <country name="" english_name="Djibouti" name_code="dj" phone_code="253" /> <country name="" english_name="Denmark" name_code="dk" phone_code="45" /> <country name="" english_name="Dominica" name_code="dm" phone_code="1" /> <country name=" " english_name="Dominican Republic" name_code="do" phone_code="1" /> <country name="" english_name="Algeria" name_code="dz" phone_code="213" /> <country name="" english_name="Ecuador" name_code="ec" phone_code="593" /> <country name="" english_name="Estonia" name_code="ee" phone_code="372" /> <country name="" english_name="Egypt" name_code="eg" phone_code="20" /> <country name="" english_name="Eritrea" name_code="er" phone_code="291" /> <country name="" english_name="Spain" name_code="es" phone_code="34" /> <country name="" english_name="Ethiopia" name_code="et" phone_code="251" /> <country name="" english_name="Finland" name_code="fi" phone_code="358" /> <country name="" english_name="Fiji" name_code="fj" phone_code="679" /> <country name=" ( )" english_name="Falkland Islands (malvinas)" name_code="fk" phone_code="500" /> <country name=" " english_name="Micronesia, Federated States Of" name_code="fm" phone_code="691" /> <country name=" " english_name="Faroe Islands" name_code="fo" phone_code="298" /> <country name="" english_name="France" name_code="fr" phone_code="33" /> <country name="" english_name="Gabon" name_code="ga" phone_code="241" /> <country name="" english_name="United Kingdom" name_code="gb" phone_code="44" /> <country name="" english_name="Grenada" name_code="gd" phone_code="1" /> <country name="" english_name="Georgia" name_code="ge" phone_code="995" /> <country name=" " english_name="French Guyana" name_code="gf" phone_code="594" /> <country name=" " english_name="Guernsey" name_code="gg" phone_code="44" /> <country name="" english_name="Ghana" name_code="gh" phone_code="233" /> <country name="" english_name="Gibraltar" name_code="gi" phone_code="350" /> <country name="" english_name="Greenland" name_code="gl" phone_code="299" /> <country name="" english_name="Gambia" name_code="gm" phone_code="220" /> <country name="" english_name="Guinea" name_code="gn" phone_code="224" /> <country name="" english_name="Guadeloupe" name_code="gp" phone_code="590" /> <country name=" " english_name="Equatorial Guinea" name_code="gq" phone_code="240" /> <country name="" english_name="Greece" name_code="gr" phone_code="30" /> <country name="" english_name="Guatemala" name_code="gt" phone_code="502" /> <country name="" english_name="Guinea-bissau" name_code="gw" phone_code="245" /> <country name="" english_name="Guyana" name_code="gy" phone_code="592" /> <country name="" english_name="Guam" name_code="gu" phone_code="1" /> <country name="" english_name="Hong Kong" name_code="hk" phone_code="852" /> <country name="" english_name="Honduras" name_code="hn" phone_code="504" /> <country name="" english_name="Croatia" name_code="hr" phone_code="385" /> <country name="" english_name="Haiti" name_code="ht" phone_code="509" /> <country name="" english_name="Hungary" name_code="hu" phone_code="36" /> <country name="" english_name="Indonesia" name_code="id" phone_code="62" /> <country name="" english_name="Ireland" name_code="ie" phone_code="353" /> <country name="" english_name="Israel" name_code="il" phone_code="972" /> <country name="" english_name="Isle Of Man" name_code="im" phone_code="44" /> <country name="" english_name="Iceland" name_code="is" phone_code="354" /> <country name="" english_name="India" name_code="in" phone_code="91" /> <country name=" " english_name="British Indian Ocean Territory" name_code="io" phone_code="246" /> <country name="" english_name="Iraq" name_code="iq" phone_code="964" /> <country name="" english_name="Iran, Islamic Republic Of" name_code="ir" phone_code="98" /> <country name="()" english_name="Italy" name_code="it" phone_code="39" /> <country name="" english_name="Jersey" name_code="je" phone_code="44" /> <country name="" english_name="Jamaica" name_code="jm" phone_code="1" /> <country name="" english_name="Jordan" name_code="jo" phone_code="962" /> <country name="" english_name="Japan" name_code="jp" phone_code="81" /> <country name="" english_name="Kenya" name_code="ke" phone_code="254" /> <country name="" english_name="Kyrgyzstan" name_code="kg" phone_code="996" /> <country name="" english_name="Cambodia" name_code="kh" phone_code="855" /> <country name="" english_name="Kiribati" name_code="ki" phone_code="686" /> <country name="" english_name="Comoros" name_code="km" phone_code="269" /> <country name=" " english_name="Saint Kitts and Nevis" name_code="kn" phone_code="1" /> <country name="" english_name="North Korea" name_code="kp" phone_code="850" /> <country name=" ()" english_name="South Korea" name_code="kr" phone_code="82" /> <country name="" english_name="Kuwait" name_code="kw" phone_code="965" /> <country name=" " english_name="Cayman Islands" name_code="ky" phone_code="1" /> <country name="" english_name="Kazakhstan" name_code="kz" phone_code="7" /> <country name="" english_name="Lao People's Democratic Republic" name_code="la" phone_code="856" /> <country name="" english_name="Lebanon" name_code="lb" phone_code="961" /> <country name="" english_name="Saint Lucia" name_code="lc" phone_code="1" /> <country name="" english_name="Liechtenstein" name_code="li" phone_code="423" /> <country name="" english_name="Sri Lanka" name_code="lk" phone_code="94" /> <country name="" english_name="Liberia" name_code="lr" phone_code="231" /> <country name="" english_name="Lesotho" name_code="ls" phone_code="266" /> <country name="" english_name="Lithuania" name_code="lt" phone_code="370" /> <country name="" english_name="Luxembourg" name_code="lu" phone_code="352" /> <country name="" english_name="Latvia" name_code="lv" phone_code="371" /> <country name="" english_name="Libya" name_code="ly" phone_code="218" /> <country name="" english_name="Morocco" name_code="ma" phone_code="212" /> <country name="" english_name="Monaco" name_code="mc" phone_code="377" /> <country name="" english_name="Moldova, Republic Of" name_code="md" phone_code="373" /> <country name="" english_name="Montenegro" name_code="me" phone_code="382" /> <country name=" " english_name="Saint Martin" name_code="mf" phone_code="590" /> <country name="" english_name="Madagascar" name_code="mg" phone_code="261" /> <country name=" " english_name="Marshall Islands" name_code="mh" phone_code="692" /> <country name="" english_name="Macedonia (FYROM)" name_code="mk" phone_code="389" /> <country name="" english_name="Mali" name_code="ml" phone_code="223" /> <country name="" english_name="Myanmar" name_code="mm" phone_code="95" /> <country name="" english_name="Mongolia" name_code="mn" phone_code="976" /> <country name="" english_name="Macau" name_code="mo" phone_code="853" /> <country name=" " english_name="Northern Mariana Islands" name_code="mp" phone_code="1" /> <country name="" english_name="Martinique" name_code="mq" phone_code="596" /> <country name="" english_name="Mauritania" name_code="mr" phone_code="222" /> <country name="" english_name="Montserrat" name_code="ms" phone_code="1" /> <country name="" english_name="Malta" name_code="mt" phone_code="356" /> <country name="" english_name="Mauritius" name_code="mu" phone_code="230" /> <country name="" english_name="Maldives" name_code="mv" phone_code="960" /> <country name="" english_name="Malawi" name_code="mw" phone_code="265" /> <country name="" english_name="Mexico" name_code="mx" phone_code="52" /> <country name="" english_name="Malaysia" name_code="my" phone_code="60" /> <country name="" english_name="Mozambique" name_code="mz" phone_code="258" /> <country name="" english_name="Namibia" name_code="na" phone_code="264" /> <country name=" " english_name="New Caledonia" name_code="nc" phone_code="687" /> <country name="" english_name="Niger" name_code="ne" phone_code="227" /> <country name=" " english_name="Norfolk Islands" name_code="nf" phone_code="672" /> <country name="" english_name="Nigeria" name_code="ng" phone_code="234" /> <country name="" english_name="Nicaragua" name_code="ni" phone_code="505" /> <country name="" english_name="Netherlands" name_code="nl" phone_code="31" /> <country name="" english_name="Norway" name_code="no" phone_code="47" /> <country name="" english_name="Nepal" name_code="np" phone_code="977" /> <country name="" english_name="Nauru" name_code="nr" phone_code="674" /> <country name="" english_name="Niue" name_code="nu" phone_code="683" /> <country name="" english_name="New Zealand" name_code="nz" phone_code="64" /> <country name="" english_name="Oman" name_code="om" phone_code="968" /> <country name="" english_name="Panama" name_code="pa" phone_code="507" /> <country name="" english_name="Peru" name_code="pe" phone_code="51" /> <country name=" " english_name="French Polynesia" name_code="pf" phone_code="689" /> <country name="" english_name="Papua New Guinea" name_code="pg" phone_code="675" /> <country name="" english_name="Philippines" name_code="ph" phone_code="63" /> <country name="" english_name="Pakistan" name_code="pk" phone_code="92" /> <country name="" english_name="Poland" name_code="pl" phone_code="48" /> <country name=" " english_name="Saint Pierre And Miquelon" name_code="pm" phone_code="508" /> <country name=" " english_name="Pitcairn Islands" name_code="pn" phone_code="870" /> <country name="" english_name="Puerto Rico" name_code="pr" phone_code="1" /> <country name="" english_name="Palestine" name_code="ps" phone_code="970" /> <country name="" english_name="Portugal" name_code="pt" phone_code="351" /> <country name="" english_name="Palau" name_code="pw" phone_code="680" /> <country name="" english_name="Paraguay" name_code="py" phone_code="595" /> <country name="" english_name="Qatar" name_code="qa" phone_code="974" /> <country name="" english_name="Runion" name_code="re" phone_code="262" /> <country name="" english_name="Romania" name_code="ro" phone_code="40" /> <country name="" english_name="Serbia" name_code="rs" phone_code="381" /> <country name="" english_name="Russian Federation" name_code="ru" phone_code="7" /> <country name="" english_name="Rwanda" name_code="rw" phone_code="250" /> <country name=" " english_name="Saudi Arabia" name_code="sa" phone_code="966" /> <country name=" " english_name="Solomon Islands" name_code="sb" phone_code="677" /> <country name="" english_name="Seychelles" name_code="sc" phone_code="248" /> <country name="" english_name="Sudan" name_code="sd" phone_code="249" /> <country name="" english_name="Sweden" name_code="se" phone_code="46" /> <country name="" english_name="Singapore" name_code="sg" phone_code="65" /> <country name=" " english_name="Saint Helena, Ascension And Tristan Da Cunha" name_code="sh" phone_code="290" /> <country name="" english_name="Slovenia" name_code="si" phone_code="386" /> <country name="" english_name="Slovakia" name_code="sk" phone_code="421" /> <country name="" english_name="Sierra Leone" name_code="sl" phone_code="232" /> <country name=" " english_name="San Marino" name_code="sm" phone_code="378" /> <country name="" english_name="Senegal" name_code="sn" phone_code="221" /> <country name="" english_name="Somalia" name_code="so" phone_code="252" /> <country name="" english_name="Suriname" name_code="sr" phone_code="597" /> <country name=" " english_name="South Sudan" name_code="ss" phone_code="211" /> <country name=" " english_name="Sao Tome And Principe" name_code="st" phone_code="239" /> <country name=" " english_name="El Salvador" name_code="sv" phone_code="503" /> <country name="" english_name="Sint Maarten" name_code="sx" phone_code="1" /> <country name="" english_name="Syrian Arab Republic" name_code="sy" phone_code="963" /> <country name="" english_name="Swaziland" name_code="sz" phone_code="268" /> <country name=" " english_name="Turks and Caicos Islands" name_code="tc" phone_code="1" /> <country name="" english_name="Chad" name_code="td" phone_code="235" /> <country name="" english_name="Togo" name_code="tg" phone_code="228" /> <country name="" english_name="Thailand" name_code="th" phone_code="66" /> <country name="" english_name="Tajikistan" name_code="tj" phone_code="992" /> <country name=" " english_name="Tokelau" name_code="tk" phone_code="690" /> <country name="" english_name="Timor-leste" name_code="tl" phone_code="670" /> <country name=" " english_name="Turkmenistan" name_code="tm" phone_code="993" /> <country name="" english_name="Tunisia" name_code="tn" phone_code="216" /> <country name="" english_name="Tonga" name_code="to" phone_code="676" /> <country name="" english_name="Turkey" name_code="tr" phone_code="90" /> <country name=" " english_name="Trinidad &amp; Tobago" name_code="tt" phone_code="1" /> <country name="" english_name="Tuvalu" name_code="tv" phone_code="688" /> <country name="" english_name="Taiwan" name_code="tw" phone_code="886" /> <country name="" english_name="Tanzania, United Republic Of" name_code="tz" phone_code="255" /> <country name="" english_name="Ukraine" name_code="ua" phone_code="380" /> <country name="" english_name="Uganda" name_code="ug" phone_code="256" /> <country name="" english_name="United States (USA)" name_code="us" phone_code="1" /> <country name="" english_name="Uruguay" name_code="uy" phone_code="598" /> <country name="" english_name="Uzbekistan" name_code="uz" phone_code="998" /> <country name=" " english_name="Holy See (vatican City State)" name_code="va" phone_code="379" /> <country name=" " english_name="Saint Vincent &amp; The Grenadines" name_code="vc" phone_code="1" /> <country name="" english_name="Venezuela, Bolivarian Republic Of" name_code="ve" phone_code="58" /> <country name=" " english_name="British Virgin Islands" name_code="vg" phone_code="1" /> <country name=" " english_name="US Virgin Islands" name_code="vi" phone_code="1" /> <country name="" english_name="Vietnam" name_code="vn" phone_code="84" /> <country name="" english_name="Vanuatu" name_code="vu" phone_code="678" /> <country name=" " english_name="Wallis And Futuna" name_code="wf" phone_code="681" /> <country name="" english_name="Samoa" name_code="ws" phone_code="685" /> <country name="" english_name="Kosovo" name_code="xk" phone_code="383" /> <country name="" english_name="Yemen" name_code="ye" phone_code="967" /> <country name="" english_name="Mayotte" name_code="yt" phone_code="262" /> <country name=" " english_name="South Africa" name_code="za" phone_code="27" /> <country name="" english_name="Zambia" name_code="zm" phone_code="260" /> <country name="" english_name="Zimbabwe" name_code="zw" phone_code="263" /> </countries> </data> ```
/content/code_sandbox/ccp/src/main/res/raw/ccp_korean.xml
xml
2016-01-20T10:28:34
2024-08-13T16:24:01
CountryCodePickerProject
hbb20/CountryCodePickerProject
1,506
6,895
```xml <?xml version="1.0" encoding="utf-8"?> <!-- 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 --> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="path_to_url" xmlns:app="path_to_url" xmlns:tools="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="org.apache.tvm.tvmrpc.MainActivity"> <com.google.android.material.appbar.AppBarLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </com.google.android.material.appbar.AppBarLayout> <include layout="@layout/content_main"/> </androidx.coordinatorlayout.widget.CoordinatorLayout> ```
/content/code_sandbox/apps/android_deploy/app/src/main/res/layout/activity_main.xml
xml
2016-10-12T22:20:28
2024-08-16T11:24:08
tvm
apache/tvm
11,517
289
```xml <vector xmlns:android="path_to_url" android:width="96dp" android:height="96dp" android:viewportWidth="96" android:viewportHeight="96"> <path android:pathData="m63.025,52.358c-6.812,5.195 -10.217,7.794 -16.284,7.073 -6.074,-0.726 -11.767,-4.408 -14.063,-10.689 3.775,-5.562 10.216,-7.79 16.289,-7.073 6.065,0.724 8.73,4.049 14.059,10.688z" android:fillColor="#77b255"/> <path android:pathData="m77.67,31.855c-6.13,5.168 -10.874,7.673 -16.59,7.273 -5.718,-0.404 -11.228,-3.594 -13.669,-9.373 3.27,-5.374 9.192,-7.757 14.91,-7.357 5.713,0.409 10.047,3.477 15.348,9.456z" android:fillColor="#77b255"/> <path android:pathData="m74.251,43.429c11.268,0.702 19.367,7.709 15.002,17.84 -5.158,1.143 -9.177,-0.298 -12.584,-4.198 -3.405,-3.898 -3.075,-7.147 -2.418,-13.642z" android:fillColor="#5c913b"/> <path android:pathData="m46,71.049c-3.163,7.549 -4.747,11.325 -10.197,13.561 -5.456,2.232 -12.669,0.213 -17.679,-3.987" android:fillColor="#5c913b"/> <path android:pathData="m62.266,57.861c8.394,4.364 12.594,6.546 14.556,12.82 1.964,6.279 0.706,13.511 -4.747,18.562 -7.415,-1.224 -12.594,-6.542 -14.558,-12.825 -1.959,-6.272 0.278,-10.367 4.75,-18.558z" android:fillColor="#77b255"/> <path android:pathData="m62.266,57.861c-0.536,-7.244 15.512,7.131 16.338,11.795 2.885,8.055 -6.529,19.587 -6.529,19.587" android:fillColor="#5c913b"/> <path android:pathData="m74.25,43.429c-2.513,-4.757 4.554,-3.963 8.961,-0.439 9.216,8.237 11.233,7.007 6.043,18.278" android:fillColor="#77b255"/> <path android:pathData="m62.17,53.148c-4.216,-0.234 -21.08,-0.579 -29.492,-4.405 1.345,7.371 13.508,16.796 21.937,11.524 5.902,-4.056 7.554,-7.119 7.554,-7.119" android:fillColor="#5c913b"/> <path android:pathData="m77.67,31.855c-5.754,0.525 -17.932,3.891 -30.258,-2.099 1.517,6.55 14.383,15.422 22.24,8.881 5.402,-4.729 8.019,-6.782 8.019,-6.782" android:fillColor="#5c913b"/> <path android:pathData="m45.947,70.676c-3.378,2.162 -18.325,11.636 -26.022,10.98 -7.693,-0.658 4.266,-20.753 22.239,-15.893 5.243,1.417 3.784,4.913 3.784,4.913" android:fillColor="#77b255"/> <path android:pathData="m85.201,14.213c1.309,0.199 3.055,1.817 2.853,3.096 -1.222,7.79 -6.406,26.603 -41.012,54.121 -1.027,0.82 -2.188,1.443 -3.06,0.463 -0.874,-0.975 0.117,-2.075 1.116,-2.927 29.784,-25.296 34.774,-45.33 35.915,-52.613 0.204,-1.279 2.876,-2.335 4.187,-2.14" android:fillColor="#a06253"/> <path android:pathData="m6.983,7.625c-0.016,0.046 -0.033,0.092 -0.049,0.137l-1.048,5.075c-0.084,1.734 0.11,3.481 0.573,5.167 2.321,8.253 10.442,13.188 18.139,11.024 7.442,-2.112 11.79,-10.124 9.875,-18.193l-2.664,-5.885 -0.01,-0.013 -2.107,8.461 -8.499,-4.843 -5.506,8.733z" android:strokeAlpha="0.2" android:strokeWidth="12.371" android:fillColor="#b5a171"/> <path android:pathData="m5.842,13.021c0.043,1.996 0.309,4 0.853,5.934 2.977,10.585 11.093,15.485 18.796,13.318s12.075,-10.578 9.098,-21.164l-5.721,-2.889 -0.912,7.26 -5.905,3.635 -6.286,-6.4 -5.161,5.193z" android:strokeAlpha="0.2" android:strokeWidth="12" android:fillColor="#fae9be"/> <path android:pathData="m33.498,9.118c1.901,7.825 -0.544,16.623 -9.07,19.332 -8.492,2.698 -16.016,-5.76 -17.812,-11.767 0.106,1.618 -0.18,1.307 0.261,2.875 2.977,10.585 11.093,15.485 18.796,13.318s12.077,-10.579 9.1,-21.164c-0.44,-1.565 -0.522,-1.153 -1.275,-2.593z" android:strokeAlpha="0.2" android:strokeWidth="12" android:fillColor="#f0d895"/> <path android:pathData="m45.715,52.33c-19.33,-3.017 -18.082,13.219 -18.643,18.552l-19.701,-18.616c9.729,4.309 18.185,3.12 19.738,-16.757z" android:fillColor="#cfc06b"/> <path android:pathData="m40.8,41.616s-9.246,-8.478 -10.201,-12.136c-0.955,-3.658 1.168,-7.029 4.805,-7.544 3.637,-0.515 7.478,2.017 8.433,5.674s-3.037,14.005 -3.037,14.005z" android:strokeWidth="1.1724" android:fillColor="#83bf4f"/> <path android:pathData="m38.749,41.638c2.928,-3.395 10.033,-7.32 18.569,0.035l-1.77,2.053c-7.736,-6.665 -13.942,-0.728 -14.487,-0.096z" android:strokeWidth=".95369" android:fillColor="#947151"/> <path android:pathData="m36.529,38.051c-3.512,-2.956 -9.64,-4.646 -13.913,-2.584 0.485,7.374 7.968,4.749 8.745,8.955 8.506,7.854 7.45,2.672 15.342,10.349 1.592,-5.454 -2.098,-11.117 -6.463,-12.524 -0.816,-1.439 -2.115,-2.852 -3.711,-4.195zM18.348,56.315c-4.005,-0.268 -4.563,-1.936 -10.206,-4.048 -2.325,7.175 -1.405,10.727 1.662,13.37 2.756,2.375 3.757,1.79 5.447,3.245 1.6,1.379 -0.22,0.935 3.337,4 3.068,2.643 8.881,3.265 10.991,-2.203 -7.058,-4.409 -5.51,-8.043 -11.231,-14.364z" android:strokeWidth=".95369" android:fillColor="#d16340"/> <path android:pathData="M24.816,51.277a2.974,1.487 135,1 0,2.103 2.103a2.974,1.487 135,1 0,-2.103 -2.103z" android:strokeAlpha="0.2" android:strokeWidth="12.66" android:fillColor="#644c37"/> </vector> ```
/content/code_sandbox/app/src/main/res/drawable/ic_recycling_green_waste.xml
xml
2016-07-02T10:44:04
2024-08-16T18:55:54
StreetComplete
streetcomplete/StreetComplete
3,781
2,476
```xml import {test, expect} from 'vitest'; import ensure from './enum.js'; test('false for no params', () => { const actual = (ensure as () => boolean)(); expect(actual).toBe(false); }); test('false for not array enums', () => { const actual = ensure('a', 'a' as any); expect(actual).toBe(false); }); test('true for a against a', () => { const actual = ensure('a', ['a']); expect(actual).toBe(true); }); test('false for a against b', () => { const actual = ensure('a', ['b']); expect(actual).toBe(false); }); test('true for a against a, b', () => { const actual = ensure('a', ['a', 'b']); expect(actual).toBe(true); }); test('false for b against a', () => { const actual = ensure('b', ['a']); expect(actual).toBe(false); }); test('true for b against b', () => { const actual = ensure('b', ['b']); expect(actual).toBe(true); }); test('true for b against a, b', () => { const actual = ensure('b', ['a', 'b']); expect(actual).toBe(true); }); test('false for c against a, b', () => { const actual = ensure('c', ['a', 'b']); expect(actual).toBe(false); }); ```
/content/code_sandbox/@commitlint/ensure/src/enum.test.ts
xml
2016-02-12T08:37:56
2024-08-16T13:28:33
commitlint
conventional-changelog/commitlint
16,499
288
```xml // Type definitions for ag-grid v6.2.1 // Project: path_to_url // Definitions by: Niall Crosby <path_to_url // Definitions: path_to_url export interface ICellRenderer { /** Params for rendering. The same params that are passed to the cellRenderer function. */ init?(params: any): void; /** Return the DOM element of your editor, this is what the grid puts into the DOM */ getGui(): HTMLElement; /** Gets called once by grid after editing is finished - if your editor needs to do any cleanup, do it here */ destroy?(): void; /** Get the cell to refresh. If this method is not provided, then when refresh is needed, the grid * will remove the component from the DOM and create a new component in it's place with the new values. */ refresh?(params: any): void; } export interface ICellRendererFunc { (params: any): HTMLElement | string; } ```
/content/code_sandbox/services/dashboard/assets-dev/js/vendor/ag-grid/dist/lib/rendering/cellRenderers/iCellRenderer.d.ts
xml
2016-06-21T19:39:58
2024-08-12T19:23:26
mylg
mehrdadrad/mylg
2,691
209
```xml import { StorageArea, ToolkitStorage } from './index'; import { getBrowser } from 'toolkit/core/common/web-extensions'; import { setupWithWebExtensionStorage } from 'toolkit/test/utils/setup'; interface SetupOptions { storageArea: StorageArea; } const setup = setupWithWebExtensionStorage((overrides: Partial<SetupOptions> = {}) => { const options: SetupOptions = { storageArea: StorageArea.Local, ...overrides, }; const storage = new ToolkitStorage(options.storageArea); return { browser: getBrowser(), storage, }; }); describe('ToolkitStorage', () => { describe('constructor', () => { it("should attach to the storage's onChanged event", () => { const { browser } = setup(); expect(browser.storage.onChanged.addListener).toHaveBeenCalled(); }); }); describe('getFeatureSetting', () => { it('should call getStorageItem with a feature-namespaced key', () => { const { storage } = setup(); const getStorageItemSpy = jest.spyOn(storage, 'getStorageItem'); storage.getFeatureSetting('testSetting' as FeatureName); expect(getStorageItemSpy).toHaveBeenCalledWith('toolkit-feature:testSetting', { parse: false, }); }); }); describe('getFeatureSettings', () => { it('should call getStorageItem with feature-namespaced keys', () => { const { storage } = setup(); const getStorageItemSpy = jest.spyOn(storage, 'getStorageItem'); storage.getFeatureSettings(['test' as FeatureName, 'setting' as FeatureName]); expect(getStorageItemSpy).toHaveBeenCalledTimes(2); expect(getStorageItemSpy).toHaveBeenCalledWith('toolkit-feature:test', { parse: false, }); expect(getStorageItemSpy).toHaveBeenCalledWith('toolkit-feature:setting', { parse: false }); }); it('should resolve a list of values', async () => { const { storage } = setup(); jest.spyOn(storage, 'getStorageItem').mockReturnValue(Promise.resolve('result')); const results = await storage.getFeatureSettings([ 'test' as FeatureName, 'setting' as FeatureName, ]); expect(Array.isArray(results)).toEqual(true); expect(results).toHaveLength(2); results.forEach((result) => { expect(result).toEqual('result'); }); }); }); describe('setFeatureSetting', () => { it('should call setStorageItem with feature-namespaced key', () => { const { storage } = setup(); const setStorageItemSpy = jest.spyOn(storage, 'setStorageItem'); storage.setFeatureSetting('testSetting' as FeatureName, 'ynab'); expect(setStorageItemSpy).toHaveBeenCalledWith('toolkit-feature:testSetting', 'ynab', {}); }); }); describe('removeFeatureSetting', () => { it('should call removeStorageItem with feature-namespaced key', () => { const { storage } = setup(); const removeStorageItemSpy = jest.spyOn(storage, 'removeStorageItem'); storage.removeFeatureSetting('testSetting' as FeatureName); expect(removeStorageItemSpy).toHaveBeenCalledWith('toolkit-feature:testSetting', {}); }); }); describe('getStorageItem', () => { it('should return the value from web-extensions storage', async () => { const { storage } = setup({ storage: { item: 'mock-value', }, }); const actual = await storage.getStorageItem('item'); expect(actual).toEqual('mock-value'); }); it('should parse the data by default', async () => { const { storage } = setup({ storage: { item: 'true', }, }); const actual = await storage.getStorageItem('item'); expect(typeof actual).toEqual('boolean'); expect(actual).toEqual(true); }); it('should not parse the data when fetching all storage items', async () => { const { storage } = setup({ storage: { item: 'true', }, }); const actual = await storage.getStorageItem(null); expect(actual).toEqual({ item: 'true' }); }); it("shouldn't parse if parse option is false", async () => { const { storage } = setup({ storage: { item: 'true', }, }); const actual = await storage.getStorageItem('item', { parse: false }); expect(actual).toEqual('true'); }); it('should return the default if specified and there is no value in storage', async () => { const { storage } = setup(); const actual = await storage.getStorageItem('not-there', { default: 'mock-default', }); expect(actual).toEqual('mock-default'); }); }); describe('removeStorageItem', () => { it('should call remove on the storage area', () => { const { storage } = setup(); storage.removeStorageItem('item'); expect(getBrowser().storage.local.remove).toHaveBeenCalledWith('item', expect.any(Function)); }); }); describe('setStorageItem', () => { it('should call set on the storage area', () => { const { storage } = setup(); storage.setStorageItem('item', 'test'); expect(getBrowser().storage.local.set).toHaveBeenCalledWith( { item: 'test' }, expect.any(Function) ); }); }); describe('getStoredFeatureSettings', () => { it('should return the names of stored feature settings without the feature prefix', async () => { const { storage } = setup({ storage: { 'toolkit-feature:test': 'value', someOtherSetting: 'thing', }, }); const actual = await storage.getStoredFeatureSettings(); expect(actual).toHaveLength(1); expect(actual[0]).toEqual('test'); }); }); describe('onStorageItemChanged', () => { it('registers a callback which is called when the registered key changes', () => { const { storage } = setup(); const callback = jest.fn(); storage.onStorageItemChanged('mock', callback); getBrowser().storage.mock.triggerOnChangedListeners({ mock: 'newValue' }, 'local'); expect(callback).toHaveBeenCalled(); }); it('should call all registered callbacks', () => { const { storage } = setup(); const callback = jest.fn(); const callback2 = jest.fn(); storage.onStorageItemChanged('mock', callback); storage.onStorageItemChanged('mock', callback2); getBrowser().storage.mock.triggerOnChangedListeners({ mock: 'newValue' }, 'local'); expect(callback).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled(); }); it("should ignore changes to storageAreas we're not created for", () => { const { storage } = setup(); const callback = jest.fn(); storage.onStorageItemChanged('mock', callback); getBrowser().storage.mock.triggerOnChangedListeners({ mock: 'newValue' }, 'sync'); expect(callback).not.toHaveBeenCalled(); }); it("should ignore changes to keys that don't have a registered callback", () => { setup(); expect(() => { getBrowser().storage.mock.triggerOnChangedListeners({ mock: 'data' }, 'local'); }).not.toThrow(); }); }); describe('offStorageItemChanged', () => { it('should remove the provided callback from registered callbacks for the given key', () => { const { storage } = setup(); const callback = jest.fn(); storage.onStorageItemChanged('mock', callback); getBrowser().storage.mock.triggerOnChangedListeners({ mock: 'newValue' }, 'local'); expect(callback).toHaveBeenCalled(); callback.mockReset(); storage.offStorageItemChanged('mock', callback); getBrowser().storage.mock.triggerOnChangedListeners({ mock: 'newValue' }, 'local'); expect(callback).not.toHaveBeenCalled(); }); it('should allow remove even if no listener exists', () => { const { storage } = setup(); expect(() => { storage.offStorageItemChanged('mock', jest.fn()); }).not.toThrow(); }); }); describe('onFeatureSettingChanged', () => { it('should call onStorageItemChanged with a feature-namespaced key', () => { const { storage } = setup(); const onStorageItemChangedSpy = jest.spyOn(storage, 'onStorageItemChanged'); const mockCallback = jest.fn(); storage.onFeatureSettingChanged('test' as FeatureName, mockCallback); expect(onStorageItemChangedSpy).toHaveBeenCalledWith('toolkit-feature:test', mockCallback); }); }); describe('offFeatureSettingChanged', () => { it('should call offStorageItemChanged with a feature-namespaced key', () => { const { storage } = setup(); const offStorageItemChangedSpy = jest.spyOn(storage, 'offStorageItemChanged'); const mockCallback = jest.fn(); storage.offFeatureSettingChanged('test' as FeatureName, mockCallback); expect(offStorageItemChangedSpy).toHaveBeenCalledWith('toolkit-feature:test', mockCallback); }); }); }); ```
/content/code_sandbox/src/core/common/storage/index.test.ts
xml
2016-01-03T05:38:10
2024-08-13T16:08:09
toolkit-for-ynab
toolkit-for-ynab/toolkit-for-ynab
1,418
1,944
```xml import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { SharedModule } from '@app/shared'; import { SignalrComponent } from './signalr.component'; import { ChatComponent } from './chat/chat.component'; import { MoveShapeComponent } from './move-shape/move-shape.component'; import { DraggableDirective } from './move-shape/draggable.directive'; import { routes } from './signalr.routes'; @NgModule({ imports: [ SharedModule, RouterModule.forChild(routes) ], declarations: [ SignalrComponent, ChatComponent, MoveShapeComponent, DraggableDirective ] }) export class SignalrModule { } ```
/content/code_sandbox/src/Presentation/Web/ClientApp/src/app/+examples/examples/signalr/signalr.module.ts
xml
2016-06-03T17:49:56
2024-08-14T02:53:24
AspNetCoreSpa
fullstackproltd/AspNetCoreSpa
1,472
143
```xml <RelativeLayout xmlns:android="path_to_url" xmlns:tools="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" <ScrollView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="@+id/scrollView2"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/main_v_layout"> <TextView android:text="@string/end_user_license_agreement" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15sp" android:textStyle="bold" /> <TextView android:text="@string/pref_I_understand_summery" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:textSize="11sp" android:id="@+id/summary" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_horizontal"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/pref_I_understand_title" android:id="@+id/agreeCheckBox" android:checked="false" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/save" android:id="@+id/saveButton" android:layout_marginTop="20dp" /> <Button android:layout_marginTop="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/view_important_warning" android:id="@+id/warningButton4" android:onClick="viewWarning" android:layout_gravity="right" android:backgroundTint="#2c2c2c" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="" android:id="@+id/translator_credits" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" android:paddingStart="10dp" android:gravity="right" android:textColor="#ffe57f" android:paddingTop="7dp" /> <Button style="?android:attr/buttonStyleSmall" android:background="@android:color/transparent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/view_google_licenses" android:id="@+id/googlelicenses" android:layout_gravity="right" /> </LinearLayout> <WebView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/webView" android:visibility="invisible" android:background="@android:color/transparent" android:layout_alignParentBottom="true" android:layout_alignEnd="@+id/scrollView2" android:layout_alignParentStart="true" /> </LinearLayout> </ScrollView> </RelativeLayout> ```
/content/code_sandbox/app/src/main/res/layout/activity_license_agreement.xml
xml
2016-09-23T13:33:17
2024-08-15T09:51:19
xDrip
NightscoutFoundation/xDrip
1,365
758
```xml <!-- *********************************************************************************************** Microsoft.NET.ClickOnce.targets WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have created a backup copy. Incorrect changes to this file will make it impossible to load or build your projects from the command-line or the IDE. *********************************************************************************************** --> <Project xmlns="path_to_url"> <PropertyGroup> <PublishDirName>app.publish</PublishDirName> <PublishDir>$(OutputPath)app.publish\</PublishDir> <GenerateManifests>true</GenerateManifests> <_DeploymentSignClickOnceManifests Condition="'$(SignManifests)' == 'true'">true</_DeploymentSignClickOnceManifests> <PublishProtocolProviderTargets>ClickOncePublish</PublishProtocolProviderTargets> </PropertyGroup> <!-- .NET Core ClickOnce manifest generation needs to run after this list of targets so that all json files are generated and files to publish are computed. --> <PropertyGroup> <PublishDepsFilePath>$(PublishDir)$(ProjectDepsFileName)</PublishDepsFilePath> <DeploymentComputeClickOnceManifestInfoDependsOn> $(DeploymentComputeClickOnceManifestInfoDependsOn); GenerateBuildDependencyFile; GenerateBuildRuntimeConfigurationFiles; ComputeFilesToPublish; GetNetCoreRuntimeJsonFilesForClickOnce; </DeploymentComputeClickOnceManifestInfoDependsOn> </PropertyGroup> <Target Name="GetNetCoreRuntimeJsonFilesForClickOnce" Condition="'$(GenerateDependencyFile)' == 'true'"> <!-- Get correct deps json files based on _UseBuildDependencyFile --> <ItemGroup> <ProjectDepsFilesForClickOnce Condition="'$(_UseBuildDependencyFile)' == 'true'" Include="$(ProjectDepsFilePath)"/> <ProjectDepsFilesForClickOnce Condition="'$(_UseBuildDependencyFile)' != 'true'" Include="$(IntermediateDepsFilePath)"/> </ItemGroup> <ItemGroup Condition="'$(GenerateRuntimeConfigurationFiles)'=='true'"> <ProjectRuntimeConfigFilesForClickOnce Include="$(ProjectRuntimeConfigFilePath)"/> </ItemGroup> <!-- Add runtimeconfig and deps json file to item group that's included in files for clickonce publishing --> <ItemGroup> <NetCoreRuntimeJsonFilesForClickOnce Include="@(ProjectRuntimeConfigFilesForClickOnce);@(ProjectDepsFilesForClickOnce)"/> </ItemGroup> </Target> <!-- Add necessary clickonce targets that need to run during publish process. These targets are defined in MS.Common.CurrentVersion.targets in the msbuild repo. --> <PropertyGroup> <ClickOncePublishDependsOn> $(ClickOncePublishDependsOn); _CopyFilesToPublishFolder; _DeploymentGenerateBootstrapper; ResolveKeySource; _DeploymentSignClickOnceDeployment; AfterPublish </ClickOncePublishDependsOn> </PropertyGroup> <Target Name="ClickOncePublish" Condition="'$(PublishableProject)'=='true'" DependsOnTargets="$(ClickOncePublishDependsOn)" /> </Project> ```
/content/code_sandbox/src/Tasks/Microsoft.NET.Build.Tasks/targets/Microsoft.NET.ClickOnce.targets
xml
2016-07-22T21:26:02
2024-08-16T17:23:58
sdk
dotnet/sdk
2,627
662
```xml <?xml version="1.0"?> <?mso-application progid="Excel.Sheet"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="path_to_url"> <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> <LastAuthor>Owen Leibman</LastAuthor> <Created>2023-05-31T15:52:55Z</Created> <LastSaved>2023-06-02T02:15:24Z</LastSaved> <Version>16.00</Version> </DocumentProperties> <CustomDocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> <MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_Enabled dt:dt="string">true</MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_Enabled> <MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_SetDate dt:dt="string">2023-06-02T02:15:24Z</MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_SetDate> <MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_Method dt:dt="string">Standard</MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_Method> <MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_Name dt:dt="string">defa4170-0d19-0005-0004-bc88714345d2</MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_Name> <MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_SiteId dt:dt="string">f9465cb1-7889-4d9a-b552-fdd0addf0eb1</MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_SiteId> <MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_ActionId dt:dt="string">a9441577-fd50-4686-b29c-06250a20f19e</MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_ActionId> <MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_ContentBits dt:dt="string">0</MSIP_Label_b002e552-5bac-4e77-a8f2-1e8fdcadcedf_ContentBits> </CustomDocumentProperties> <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"> <AllowPNG/> </OfficeDocumentSettings> <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> <WindowHeight>6780</WindowHeight> <WindowWidth>19160</WindowWidth> <WindowTopX>32767</WindowTopX> <WindowTopY>32767</WindowTopY> <ProtectStructure>False</ProtectStructure> <ProtectWindows>False</ProtectWindows> </ExcelWorkbook> <Styles> <Style ss:ID="Default" ss:Name="Normal"> <Alignment ss:Vertical="Bottom"/> <Borders/> <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/> <Interior/> <NumberFormat/> <Protection/> </Style> </Styles> <Worksheet ss:Name="Tabelle1"> <Table ss:ExpandedColumnCount="5" ss:ExpandedRowCount="6" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="14.5"> <Column ss:Index="2" ss:Width="120.5"/> <Row ss:AutoFitHeight="0"> <Cell ss:Index="2"><Data ss:Type="String">decimal numbers below:</Data></Cell> <Cell ss:Index="5"><Data ss:Type="String">a</Data></Cell> </Row> <Row ss:AutoFitHeight="0"> <Cell ss:Index="5"><Data ss:Type="String">bb</Data></Cell> </Row> <Row ss:AutoFitHeight="0"> <Cell ss:Index="5"><Data ss:Type="String">ccc</Data></Cell> </Row> <Row ss:AutoFitHeight="0"> <Cell ss:Index="5"><Data ss:Type="String">dddd</Data></Cell> </Row> <Row ss:AutoFitHeight="0"> <Cell ss:Index="5"><Data ss:Type="String">eeeee</Data></Cell> </Row> <Row ss:AutoFitHeight="0"> <Cell ss:Index="5"><Data ss:Type="String">ffffff</Data></Cell> </Row> </Table> <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> <Unsynced/> <Selected/> <Panes> <Pane> <Number>3</Number> <ActiveRow>1</ActiveRow> <ActiveCol>2</ActiveCol> </Pane> </Panes> <ProtectObjects>False</ProtectObjects> <ProtectScenarios>False</ProtectScenarios> </WorksheetOptions> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>C1</Range> <Type>Whole</Type> <Min>1</Min> <Max>9</Max> <InputTitle>Enter a digit</InputTitle> <InputMessage>Please enter a single digit from 1 to 9</InputMessage> <ErrorMessage>Sorry, only digits from 1 to 9 are allowed</ErrorMessage> <ErrorTitle>Wrong number</ErrorTitle> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R2C2:R1048576C2</Range> <Type>Decimal</Type> <Qualifier>Greater</Qualifier> <Value>10</Value> <InputMessage>Decimal number bigger than 10</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R1C2</Range> <Qualifier>Greater</Qualifier> <InputHide/> <InputMessage>Decimal number bigger than 10</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R1C3</Range> <Type>Date</Type> <Qualifier>GreaterOrEqual</Qualifier> <Value>44927</Value> <InputMessage>date from 2023-01-01</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R2C3</Range> <Type>Time</Type> <Min>0.333333333333333</Min> <Max>0.583333333333333</Max> <InputMessage>time from 8:00 to 14:00</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R3C3</Range> <Type>TextLength</Type> <Qualifier>Less</Qualifier> <Value>8</Value> <InputMessage>text &lt; 8 characters</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R4C3</Range> <Type>List</Type> <UseBlank/> <CellRangeList/> <Value>&quot;a,b,c,d,e&quot;</Value> <InputMessage>letters a to e</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R1C4</Range> <Type>Whole</Type> <Min>1+1</Min> <Max>2+2</Max> <InputMessage>integer from 2 to 4</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R2C4</Range> <Type>List</Type> <Value>R[-1]C[1]:R[3]C[1]</Value> <InputMessage>any of the texts in E1:E5</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R7C6</Range> <Type>Whole</Type> <Qualifier>GreaterOrEqual</Qualifier> <Value>-6</Value> <InputMessage>Integer greater than or equal to -6</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R6C6</Range> <Type>Whole</Type> <Qualifier>LessOrEqual</Qualifier> <Value>12</Value> <InputMessage>Integer less than or equal to 12</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R5C6</Range> <Type>Whole</Type> <Qualifier>Less</Qualifier> <Value>8</Value> <InputMessage>Integer less than 8</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R4C6</Range> <Type>Whole</Type> <Qualifier>Equal</Qualifier> <Value>-3</Value> <InputMessage>Negative 3 is only valid input</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R3C6</Range> <Type>Whole</Type> <Qualifier>NotEqual</Qualifier> <Value>7</Value> <InputMessage>Any integer except 7</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R2C6</Range> <Type>Whole</Type> <Qualifier>NotBetween</Qualifier> <Min>-5</Min> <Max>5</Max> <InputMessage>Integer not between -5 and 5</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R1C6</Range> <Type>Whole</Type> <Min>2</Min> <Max>5</Max> <InputMessage>Integer between 2 and 5</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R8C6</Range> <Type>Whole</Type> <Qualifier>Greater</Qualifier> <Value>5</Value> <InputMessage>Integer greater than 5</InputMessage> </DataValidation> <DataValidation xmlns="urn:schemas-microsoft-com:office:excel"> <Range>R1C7</Range> <Type>Decimal</Type> <Min>2</Min> <Max>5</Max> <InputMessage>Float between 2 and 5</InputMessage> </DataValidation> </Worksheet> </Workbook> ```
/content/code_sandbox/tests/data/Reader/Xml/datavalidations.xml
xml
2016-06-19T16:58:48
2024-08-16T14:51:45
PhpSpreadsheet
PHPOffice/PhpSpreadsheet
13,180
2,767
```xml import { useCallback } from 'react'; import type { WebChatActivity } from 'botframework-webchat-core'; import useMarkActivity from './internal/useMarkActivity'; export default function useMarkActivityAsSpoken(): (activity: WebChatActivity) => void { const markActivity = useMarkActivity(); return useCallback(activity => markActivity(activity, 'speak', false), [markActivity]); } ```
/content/code_sandbox/packages/api/src/hooks/useMarkActivityAsSpoken.ts
xml
2016-07-07T23:16:57
2024-08-16T00:12:37
BotFramework-WebChat
microsoft/BotFramework-WebChat
1,567
84
```xml <?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../LocalizableStrings.resx"> <body> <trans-unit id="PackageIdArgumentDescription"> <source>The workload ID(s) to uninstall.</source> <target state="translated">Identyfikatory obcienia do odinstalowania.</target> <note /> </trans-unit> <trans-unit id="CommandDescription"> <source>Uninstall one or more workloads.</source> <target state="translated">Odinstaluj co najmniej jedno obcienie.</target> <note /> </trans-unit> <trans-unit id="PackageIdArgumentName"> <source>WORKLOAD_ID</source> <target state="translated">WORKLOAD_ID</target> <note /> </trans-unit> <trans-unit id="RemovingWorkloadInstallationRecord"> <source>Removing workload installation record for {0}...</source> <target state="translated">Trwa usuwanie rekordu instalacji pakietu roboczego dla {0}...</target> <note /> </trans-unit> <trans-unit id="SpecifyExactlyOnePackageId"> <source>Specify one workload ID to uninstall.</source> <target state="translated">Okrel jeden identyfikator obcienia do odinstalowania.</target> <note /> </trans-unit> <trans-unit id="UninstallSucceeded"> <source>Successfully uninstalled workload(s): {0}</source> <target state="translated">Pomylnie odinstalowane pakiety robocze: {0}</target> <note /> </trans-unit> <trans-unit id="WorkloadNotInstalled"> <source>Couldn't find workload ID(s): {0}</source> <target state="translated">Nie mona znale identyfikatorw obcienia: {0}</target> <note /> </trans-unit> <trans-unit id="WorkloadUninstallFailed"> <source>Workload uninstallation failed: {0}</source> <target state="translated">Niepowodzenie odinstalowania pakietw roboczych: {0}</target> <note /> </trans-unit> </body> </file> </xliff> ```
/content/code_sandbox/src/Cli/dotnet/commands/dotnet-workload/uninstall/xlf/LocalizableStrings.pl.xlf
xml
2016-07-22T21:26:02
2024-08-16T17:23:58
sdk
dotnet/sdk
2,627
588
```xml import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { GlobalService } from './global.service'; @Injectable() export class ApiService { API = environment.api_endpoint; HEADERS = { 'Content-Type': 'application/json' }; HTTP_OPTIONS: any; /** * Constructor. * @param http Http Injection. * @param globalService GlobalService Injection. */ constructor(private http: HttpClient, private globalService: GlobalService) {} /** * Prepares headers for each request to API. * @param fileHeaders Set to true when uploading a file. */ prepareHttpOptions(fileHeaders = false) { const TOKEN = this.globalService.getAuthToken(); if (TOKEN) { this.HEADERS['Authorization'] = 'Token ' + TOKEN; } else { delete this.HEADERS['Authorization']; } const TEMP = Object.assign({}, this.HEADERS); if (fileHeaders) { delete TEMP['Content-Type']; } this.HTTP_OPTIONS = { headers: new HttpHeaders(TEMP), }; return TEMP; } /** * HTTP GET wrapper. * @param path path of API call. * @param isJson set to false when fetching some non-JSON content. */ getUrl(path: string, isJson = true, isLoader = true) { if (isJson) { this.prepareHttpOptions(); return this.loadingWrapper(this.http.get(this.API + path, this.HTTP_OPTIONS), isLoader); } else { this.prepareHttpOptions(true); const TEMP = Object.assign({}, this.HTTP_OPTIONS, { observe: 'response', responseType: 'text' }); return this.loadingWrapper(this.http.get(this.API + path, TEMP)); } } /** * HTTP POST wrapper. * @param path path of API call. * @param body stringified json body. */ postUrl(path: string, body: any) { this.prepareHttpOptions(); return this.loadingWrapper(this.http.post(this.API + path, body, this.HTTP_OPTIONS)); } /** * HTTP PATCH wrapper. * @param path path of API call. * @param body stringified json body. */ patchUrl(path: string, body: any) { this.prepareHttpOptions(); return this.loadingWrapper(this.http.patch(this.API + path, body, this.HTTP_OPTIONS)); } /** * HTTP PUT wrapper. * @param path path of API call. * @param body stringified json body. */ putUrl(path: string, body: any) { this.prepareHttpOptions(); return this.loadingWrapper(this.http.put(this.API + path, body, this.HTTP_OPTIONS)); } /** * HTTP POST (file upload) wrapper. * @param path path of API call. * @param body stringified json body. */ postFileUrl(path: string, formData: any) { this.prepareHttpOptions(true); return this.loadingWrapper(this.http.post(this.API + path, formData, this.HTTP_OPTIONS)); } /** * HTTP PATCH (file upload) wrapper. * @param path path of API call. * @param body stringified json body. */ patchFileUrl(path: string, formData: any) { this.prepareHttpOptions(true); return this.loadingWrapper(this.http.patch(this.API + path, formData, this.HTTP_OPTIONS)); } /** * HTTP DELETE wrapper. * @param path path of API call. */ deleteUrl(path: string) { this.prepareHttpOptions(); return this.loadingWrapper(this.http.delete(this.API + path, this.HTTP_OPTIONS)); } /** * Wrapper to display Loading-component during each network request. * @param path path of API call. * @param body stringified json body. */ loadingWrapper(httpCall, isLoader = true) { if (isLoader) { setTimeout(() => { this.globalService.toggleLoading(true); }, 100); } let success = (params) => {}; let error = (params) => {}; let final = () => {}; const RETURN_WRAPPER = { subscribe: (fa, fb, fc) => { success = fa; error = fb; final = fc; }, }; httpCall.subscribe( (data) => { success(data); }, (err) => { setTimeout(() => { this.globalService.toggleLoading(false); }, 100); error(err); }, () => { setTimeout(() => { this.globalService.toggleLoading(false); }, 100); final(); } ); return RETURN_WRAPPER; } /** * Utility for appending extra headers */ appendHeaders(headers) { // TODO: Add Headers to this.HEADERS and update this.HTTP_OPTIONS } } ```
/content/code_sandbox/frontend_v2/src/app/services/api.service.ts
xml
2016-10-21T00:51:45
2024-08-16T14:41:56
EvalAI
Cloud-CV/EvalAI
1,736
1,076
```xml import { Validators } from '@angular/forms'; import { ConfigStateService } from '@abp/ng.core'; import { getPasswordValidators } from '@abp/ng.theme.shared'; import { ePropType, FormProp } from '@abp/ng.components/extensible'; import { IdentityUserDto } from '@abp/ng.identity/proxy'; export const DEFAULT_USERS_CREATE_FORM_PROPS = FormProp.createMany<IdentityUserDto>([ { type: ePropType.String, name: 'userName', displayName: 'AbpIdentity::UserName', id: 'user-name', validators: () => [Validators.required, Validators.maxLength(256)], }, { type: ePropType.PasswordInputGroup, name: 'password', displayName: 'AbpIdentity::Password', id: 'password', autocomplete: 'new-password', validators: data => [Validators.required, ...getPasswordValidators({ get: data.getInjected })], }, { type: ePropType.String, name: 'name', displayName: 'AbpIdentity::DisplayName:Name', id: 'name', validators: () => [Validators.maxLength(64)], }, { type: ePropType.String, name: 'surname', displayName: 'AbpIdentity::DisplayName:Surname', id: 'surname', validators: () => [Validators.maxLength(64)], }, { type: ePropType.Email, name: 'email', displayName: 'AbpIdentity::EmailAddress', id: 'email', validators: () => [Validators.required, Validators.maxLength(256), Validators.email], }, { type: ePropType.String, name: 'phoneNumber', displayName: 'AbpIdentity::PhoneNumber', id: 'phone-number', validators: () => [Validators.maxLength(16)], }, { type: ePropType.Boolean, name: 'isActive', displayName: 'AbpIdentity::DisplayName:IsActive', id: 'active-checkbox', defaultValue: true, }, { type: ePropType.Boolean, name: 'lockoutEnabled', displayName: 'AbpIdentity::DisplayName:LockoutEnabled', id: 'lockout-checkbox', defaultValue: true, }, ]); export const DEFAULT_USERS_EDIT_FORM_PROPS = DEFAULT_USERS_CREATE_FORM_PROPS.map(prop => { if (prop.name === 'password') { return { ...prop, validators: (data: any) => [...getPasswordValidators({ get: data.getInjected })], }; } if (prop.name === 'isActive') { return { ...prop, visible: data => { const configState = data.getInjected(ConfigStateService); const currentUserId = configState.getDeep('currentUser.id'); return currentUserId !== data.record.id; }, }; } return prop; }); ```
/content/code_sandbox/npm/ng-packs/packages/identity/src/lib/defaults/default-users-form-props.ts
xml
2016-12-03T22:56:24
2024-08-16T16:24:05
abp
abpframework/abp
12,657
610
```xml <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="path_to_url"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion> </ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{2822DD41-90C5-46F4-9A75-BC9D65C513E7}</ProjectGuid> <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>UpgradeSample.Web</RootNamespace> <AssemblyName>UpgradeSample.Web</AssemblyName> <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <UseIISExpress>true</UseIISExpress> <IISExpressSSLPort /> <IISExpressAnonymousAuthentication /> <IISExpressWindowsAuthentication /> <IISExpressUseClassicPipelineMode /> <UseGlobalApplicationHostFile /> <NuGetPackageImportStamp> </NuGetPackageImportStamp> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Web.DynamicData" /> <Reference Include="System.Web.Entity" /> <Reference Include="System.Web.ApplicationServices" /> <Reference Include="System.ComponentModel.DataAnnotations" /> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Core" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Web.Extensions" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Drawing" /> <Reference Include="System.Web" /> <Reference Include="System.Xml" /> <Reference Include="System.Configuration" /> <Reference Include="System.Web.Services" /> <Reference Include="System.EnterpriseServices" /> </ItemGroup> <ItemGroup> <Content Include="Default.aspx" /> <None Include="Properties\PublishProfiles\local.pubxml" /> <None Include="Web.Debug.config"> <DependentUpon>Web.config</DependentUpon> </None> <None Include="Web.Release.config"> <DependentUpon>Web.config</DependentUpon> </None> </ItemGroup> <ItemGroup> <Content Include="Global.asax" /> <Content Include="Web.config" /> </ItemGroup> <ItemGroup> <Compile Include="Global.asax.cs"> <DependentUpon>Global.asax</DependentUpon> </Compile> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <Folder Include="App_Data\" /> <Folder Include="Models\" /> </ItemGroup> <PropertyGroup> <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath> </PropertyGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /> <ProjectExtensions> <VisualStudio> <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"> <WebProjectProperties> <UseIIS>True</UseIIS> <AutoAssignPort>True</AutoAssignPort> <DevelopmentServerPort>50134</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> <IISUrl>path_to_url <NTLMAuthentication>False</NTLMAuthentication> <UseCustomServer>False</UseCustomServer> <CustomServerUrl> </CustomServerUrl> <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile> </WebProjectProperties> </FlavorProperties> </VisualStudio> </ProjectExtensions> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> ```
/content/code_sandbox/windows/modernize-traditional-apps/modernize-aspnet-ops/v1.2/src/UpgradeSample.Web/UpgradeSample.Web.csproj
xml
2016-04-20T23:52:34
2024-08-16T14:15:54
labs
docker/labs
11,512
1,316
```xml import { graphql } from "react-relay"; import { Environment } from "relay-runtime"; import { getViewer } from "coral-framework/helpers"; import { commitMutationPromiseNormalized, createMutation, } from "coral-framework/lib/relay"; let clientMutationId = 0; import { AcknowledgeModMessageMutation as MutationTypes } from "coral-stream/__generated__/AcknowledgeModMessageMutation.graphql"; const AcknowledgeModMessageMutation = createMutation( "acknowledgeModMessage", (environment: Environment) => { const viewer = getViewer(environment)!; return commitMutationPromiseNormalized<MutationTypes>(environment, { mutation: graphql` mutation AcknowledgeModMessageMutation( $input: AcknowledgeModMessageInput! ) { acknowledgeModMessage(input: $input) { user { id status { modMessage { active } } } clientMutationId } } `, variables: { input: { clientMutationId: clientMutationId.toString(), }, }, optimisticResponse: { acknowledgeModMessage: { user: { id: viewer.id, status: { modMessage: { active: false, }, }, }, clientMutationId: (clientMutationId++).toString(), }, }, }); } ); export default AcknowledgeModMessageMutation; ```
/content/code_sandbox/client/src/core/client/stream/tabs/Comments/Stream/ModMessage/AcknowledgeModMessageMutation.ts
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
298
```xml import { connectionDetails } from './connectionDetails' import { Client } from 'pg' import Connectors from '../../../connectors' import { DatabaseType, DefaultRenderer } from 'prisma-datamodel' export default async function testSchema( schemaSql: string, schemaName: string = 'DatabaseIntrospector', createSchema: boolean = true, ) { checkSnapshot(await createAndIntrospect(schemaSql, schemaName, createSchema)) } export async function createAndIntrospect( schemaSql: string, schemaName: string = 'DatabaseIntrospector', createSchema: boolean = true, ) { const client = new Client(connectionDetails) await client.connect() await client.query(`DROP SCHEMA IF EXISTS "${schemaName}" cascade;`) if (createSchema) { await client.query(`CREATE SCHEMA "${schemaName}";`) await client.query(`SET search_path TO "${schemaName}";`) } await client.query(schemaSql) const connector = Connectors.create(DatabaseType.postgres, client) const dml = (await connector.introspect(schemaName)).getNormalizedDatamodel() const metadata = await connector.getMetadata(schemaName) // Snapshot would never match // console.log(metadata) // V2 rendering const renderer = DefaultRenderer.create(DatabaseType.postgres, true) const rendered = renderer.render(dml) // V1 rendering const legacyRenderer = DefaultRenderer.create(DatabaseType.postgres, false) const legacyRendered = legacyRenderer.render(dml) await client.end() return { v1: legacyRendered, v2: rendered } } export function checkSnapshot(res: { v1: string; v2: string }) { expect(res.v1).toMatchSnapshot() expect(res.v2).toMatchSnapshot() } ```
/content/code_sandbox/cli/packages/prisma-db-introspection/src/__tests__/postgres/blackbox/common.ts
xml
2016-09-25T12:54:40
2024-08-16T11:41:23
prisma1
prisma/prisma1
16,549
385
```xml /* your_sha256_hash------------- |your_sha256_hash------------*/ import { program as commander } from 'commander'; import * as path from 'path'; import * as os from 'os'; import { handlePackage } from './update-dist-tag'; import * as utils from './utils'; /** * Sleep for a specified period. * * @param wait The time in milliseconds to wait. */ async function sleep(wait: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, wait)); } // Specify the program signature. commander .description('Publish the JS packages') .option( '--skip-build', 'Skip the build step (if there was a network error during a JS publish' ) .option('--skip-publish', 'Skip publish and only handle tags') .option('--skip-tags', 'publish assets but do not handle tags') .option('--yes', 'Publish without confirmation') .option('--dry-run', 'Do not actually push any assets') .action(async (options: any) => { utils.exitOnUncaughtException(); // No-op if we're in release helper dry run if (process.env.RH_DRY_RUN === 'true') { return; } if (!options.skipPublish) { if (!options.skipBuild) { utils.run('jlpm run build:all'); } if (!options.dryRun) { // Make sure we are logged in. if (utils.checkStatus('npm whoami') !== 0) { console.error('Please run `npm login`'); process.exit(1); } } // Ensure a clean git environment try { utils.run('git commit -am "[ci skip] bump version"'); } catch (e) { // do nothing } // Publish JS to the appropriate tag. const curr = utils.getPythonVersion(); let cmd = 'lerna publish from-package '; if (options.dryRun) { cmd += '--no-git-tag-version --no-push '; } if (options.yes) { cmd += ' --yes '; } let tag = 'latest'; if (!/\d+\.\d+\.\d+$/.test(curr)) { tag = 'next'; } utils.run(`${cmd} --dist-tag=${tag} -m "Publish"`); } // Fix up any tagging issues. if (!options.skipTags && !options.dryRun) { const basePath = path.resolve('.'); const paths = utils.getLernaPaths(basePath).sort(); const cmds = await Promise.all(paths.map(handlePackage)); cmds.forEach(cmdList => { cmdList.forEach(cmd => { if (!options.dryRun) { utils.run(cmd); } else { throw new Error(`Tag is out of sync: ${cmd}`); } }); }); } // Make sure all current JS packages are published. // Try and install them into a temporary local npm package. console.log('Checking for published packages...'); const installDir = os.tmpdir(); utils.run('npm init -y', { cwd: installDir, stdio: 'pipe' }, true); const specifiers: string[] = []; utils.getCorePaths().forEach(async pkgPath => { const pkgJson = path.join(pkgPath, 'package.json'); const pkgData = utils.readJSONFile(pkgJson); specifiers.push(`${pkgData.name}@${pkgData.version}`); }); let attempt = 0; while (attempt < 10) { try { utils.run(`npm install ${specifiers.join(' ')}`, { cwd: installDir }); break; } catch (e) { console.error(e); console.log('Sleeping for one minute...'); await sleep(1 * 60 * 1000); attempt += 1; } } if (attempt == 10) { console.error('Could not install packages'); process.exit(1); } // Emit a system beep. process.stdout.write('\x07'); }); commander.parse(process.argv); ```
/content/code_sandbox/buildutils/src/publish.ts
xml
2016-06-03T20:09:17
2024-08-16T19:12:44
jupyterlab
jupyterlab/jupyterlab
14,019
880
```xml import { logger } from 'storybook/internal/node-logger'; import { dedent } from 'ts-dedent'; export const checkWebpackVersion = ( webpack: { version?: string }, specifier: string, caption: string ) => { if (!webpack.version) { logger.info('Skipping webpack version check, no version available'); return; } if (webpack.version !== specifier) { logger.warn(dedent` Unexpected webpack version in ${caption}: - Received '${webpack.version}' - Expected '${specifier}' If you're using Webpack 5 in SB6.2 and upgrading, consider: path_to_url#webpack-5-manager-build For more info about Webpack 5 support: path_to_url#troubleshooting `); } }; ```
/content/code_sandbox/code/lib/core-webpack/src/check-webpack-version.ts
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
171
```xml // DO NOT EDIT. Generated from templates/neuroglancer/util/linked_list.template.ts. /** * @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. */ interface Node<T> { next0: T | null; prev0: T | null; } export default class { static insertAfter<T extends Node<T>>(head: T, x: T) { const next = <T>head.next0; x.next0 = next; x.prev0 = head; head.next0 = x; next.prev0 = x; } static insertBefore<T extends Node<T>>(head: T, x: T) { const prev = <T>head.prev0; x.prev0 = prev; x.next0 = head; head.prev0 = x; prev.next0 = x; } static front<T extends Node<T>>(head: T) { const next = head.next0; if (next === head) { return null; } return next; } static back<T extends Node<T>>(head: T) { const next = head.prev0; if (next === head) { return null; } return next; } static pop<T extends Node<T>>(x: T) { const next = <T>x.next0; const prev = <T>x.prev0; next.prev0 = prev; prev.next0 = next; x.next0 = null; x.prev0 = null; return x; } static *iterator<T extends Node<T>>(head: T) { for (let x = <T>head.next0; x !== head; x = <T>x.next0) { yield x; } } static *reverseIterator<T extends Node<T>>(head: T) { for (let x = <T>head.prev0; x !== head; x = <T>x.prev0) { yield x; } } static initializeHead<T extends Node<T>>(head: T) { head.next0 = head.prev0 = head; } } ```
/content/code_sandbox/src/util/linked_list.0.ts
xml
2016-05-27T02:37:25
2024-08-16T07:24:25
neuroglancer
google/neuroglancer
1,045
481
```xml /* * Squidex Headless CMS * * @license */ import { AsyncPipe } from '@angular/common'; import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { DateTimeEditorComponent, DropdownComponent, HighlightPipe, TranslatePipe } from '@app/framework'; import { ContributorsState, FilterableField, FilterComparison, FilterFieldUI, FilterNegation, getFilterUI, isNegation, LanguageDto, QueryModel } from '@app/shared/internal'; import { UserDtoPicture } from '../../pipes'; import { ReferenceInputComponent } from '../../references/reference-input.component'; import { QueryPathComponent } from './query-path.component'; import { FilterOperatorPipe } from './query.pipes'; @Component({ standalone: true, selector: 'sqx-filter-comparison', styleUrls: ['./filter-comparison.component.scss'], templateUrl: './filter-comparison.component.html', changeDetection: ChangeDetectionStrategy.OnPush, imports: [ AsyncPipe, DateTimeEditorComponent, DropdownComponent, FilterOperatorPipe, FormsModule, HighlightPipe, QueryPathComponent, ReferenceInputComponent, TranslatePipe, UserDtoPicture, ], }) export class FilterComparisonComponent { @Output() public filterChange = new EventEmitter<FilterComparison | FilterNegation>(); @Output() public remove = new EventEmitter(); @Input({ required: true }) public language!: LanguageDto; @Input({ required: true }) public languages!: ReadonlyArray<LanguageDto>; @Input({ required: true }) public model!: QueryModel; @Input({ required: true }) public filter!: FilterComparison | FilterNegation; public actualComparison!: FilterComparison; public actualNegated = false; public field?: FilterableField; public fieldUI?: FilterFieldUI; public operators: ReadonlyArray<string> = []; constructor( public readonly contributorsState: ContributorsState, ) { } public ngOnChanges() { if (isNegation(this.filter)) { this.actualComparison = this.filter.not; this.actualNegated = true; } else { this.actualComparison = this.filter; this.actualNegated = false; } this.field = this.model.schema.fields.find(x => x.path === this.actualComparison.path); this.fieldUI = getFilterUI(this.actualComparison, this.field!); this.operators = this.model.operators[this.field?.schema.type!] || []; if (!this.operators.includes(this.actualComparison.op)) { this.actualComparison = { ...this.actualComparison, op: this.operators[0] }; } } public changeValue(value: any) { this.change({ value }); } public changeOp(op: string) { this.change({ op }); } public changePath(path: string) { this.change({ path, value: null }); } private change(update: Partial<FilterComparison>) { this.emitChange({ ...this.actualComparison, ...update }, this.actualNegated); } public toggleNot() { this.emitChange(this.actualComparison, !this.actualNegated); } private emitChange(filter: FilterComparison, not: boolean) { this.filterChange.emit(not ? { not: filter } : filter); } } ```
/content/code_sandbox/frontend/src/app/shared/components/search/queries/filter-comparison.component.ts
xml
2016-08-29T05:53:40
2024-08-16T17:39:38
squidex
Squidex/squidex
2,222
704
```xml import { Card, CardBody, CardHeader, Grid } from '@chakra-ui/react'; import { InputField } from 'renderer/components/fields'; export const TerminologyCard = () => { return ( <Card variant="elevated"> <CardHeader>Terminology</CardHeader> <CardBody> <Grid templateColumns="repeat(1, 1fr)" gap={6}> <InputField id="terminology.singular" label="Singular" placeholder="Singular" type="text" size="sm" isRequired inSubCard helpText="How you call single item?" /> <InputField id="terminology.plural" label="Plural" placeholder="Plural" type="text" size="sm" isRequired inSubCard helpText="How you call multiple items?" /> </Grid> </CardBody> </Card> ); }; ```
/content/code_sandbox/src/renderer/views/admin/views/add/components/terminology-card.tsx
xml
2016-05-14T02:18:49
2024-08-16T02:46:28
ElectroCRUD
garrylachman/ElectroCRUD
1,538
214
```xml // Type definitions for iview 3.3.1 // Project: path_to_url // Definitions by: yangdan // Definitions: path_to_url import Vue, { VNode } from 'vue'; export declare class Drawer extends Vue { /** * v-model * @default false */ value?: boolean; /** * slot title * @default center */ title?: string; /** * 100 100 * @default 256 */ width?: number | string; /** * * @default true */ closable?: boolean; /** * * @default true */ 'mask-closable'?: boolean; /** * * @default true */ mask?: boolean; /** * */ 'mask-style'?: object; /** * */ styles?: object; /** * * @default false */ scrollable?: boolean; /** * left right * @default right */ placement?: 'left' | 'right'; /** * * @default true */ transfer?: boolean; /** * */ 'class-name'?: string; /** * transfer * @default false */ 'inner'?: boolean; /** * * @default false */ 'draggable'?: boolean; /** * Promise */ 'before-close'?: () => void | Promise<any>; /** * */ $emit(eventName: 'on-close'): this; /** * */ $emit(eventName: 'on-visible-change', value: boolean): this; /** * */ $emit(eventName: 'on-resize-width'): number; /** * slot */ $slots: { /** * */ '': VNode[]; /** * */ header: VNode[]; /** * */ close: VNode[]; /** * */ trigger: VNode[]; }; } ```
/content/code_sandbox/types/drawer.d.ts
xml
2016-07-28T01:52:59
2024-08-16T10:15:08
iview
iview/iview
23,980
483
```xml import os from 'os' import pathlib from 'path' import { CLI_ROOT_DIR } from './root' // configurable export const defaultBotpressHome = pathlib.join(os.homedir(), '.botpress') export const defaultOutputFolder = '.botpress' export const defaultEntrypoint = pathlib.join('src', 'index.ts') export const defaultBotpressApiUrl = 'path_to_url export const defaultBotpressAppUrl = 'path_to_url export const defaultTunnelUrl = 'path_to_url // not configurable export const cliRootDir = CLI_ROOT_DIR export const echoBotDirName = 'echo-bot' export const emptyIntegrationDirName = 'empty-integration' export const helloWorldIntegrationDirName = 'hello-world' export const webhookMessageIntegrationDirName = 'webhook-message' export const fromCliRootDir = { echoBotTemplate: pathlib.join('templates', echoBotDirName), emptyIntegrationTemplate: pathlib.join('templates', emptyIntegrationDirName), helloWorldIntegrationTemplate: pathlib.join('templates', helloWorldIntegrationDirName), webhookMessageIntegrationTemplate: pathlib.join('templates', webhookMessageIntegrationDirName), } export const fromHomeDir = { globalCacheFile: 'global.cache.json', } export const fromWorkDir = { integrationDefinition: 'integration.definition.ts', interfaceDefinition: 'interface.definition.ts', } export const fromOutDir = { distDir: 'dist', outFile: pathlib.join('dist', 'index.js'), installDir: 'installations', implementationDir: 'implementation', secretsDir: 'secrets', projectCacheFile: 'project.cache.json', } ```
/content/code_sandbox/packages/cli/src/consts.ts
xml
2016-11-16T21:57:59
2024-08-16T18:45:35
botpress
botpress/botpress
12,401
347
```xml import { MessengerTypes } from 'messaging-api-messenger' import * as bp from '.botpress' export type InstagramPayload = { object: string entry: InstagramEntry[] } export type InstagramEntry = { id: string time: number messaging: InstagramMessage[] } export type InstagramMessage = { sender: { id: string } recipient: { id: string } timestamp: number message?: { mid: string text: string quick_reply?: { payload: string } attachments?: { type: string; payload: { url: string } }[] } postback?: { mid: string payload: string title: string } } export type IntegrationLogger = bp.Logger export type InstagramUserProfile = MessengerTypes.User & { username: string } export type Carousel = bp.channels.channel.carousel.Carousel export type Card = bp.channels.channel.card.Card export type Choice = bp.channels.channel.choice.Choice export type Dropdown = bp.channels.channel.dropdown.Dropdown export type Location = bp.channels.channel.location.Location export type InstagramAttachment = InstagramPostbackAttachment | InstagramSayAttachment | InstagramUrlAttachment type InstagramPostbackAttachment = { type: 'postback' title: string payload: string } type InstagramSayAttachment = { type: 'postback' title: string payload: string } type InstagramUrlAttachment = { type: 'web_url' title: string url: string } ```
/content/code_sandbox/integrations/instagram/src/misc/types.ts
xml
2016-11-16T21:57:59
2024-08-16T18:45:35
botpress
botpress/botpress
12,401
322
```xml import * as React from 'react'; import { ColorPalette, MarkdownHeader } from '@fluentui/react-docsite-components/lib/index2'; import { WXPNeutrals } from './WXPNeutrals'; export const Excel = () => { return ( <> <MarkdownHeader as="h2">Excel</MarkdownHeader> <ColorPalette colors={[ { name: 'Excel Shade 30', hex: '#094624', }, { name: 'Excel Shade 20', hex: '#0c5f32', }, { name: 'Excel Shade 10', hex: '#0f703b', }, { name: 'Excel Primary', hex: '#107c41', }, { name: 'Excel Tint 10', hex: '#218d51', }, { name: 'Excel Tint 20', hex: '#55b17e', }, { name: 'Excel Tint 30', hex: '#a0d8b9', }, { name: 'Excel Tint 40', hex: '#caead8', }, ]} /> <WXPNeutrals /> </> ); }; ```
/content/code_sandbox/apps/public-docsite/src/pages/Styles/Colors/palettes/Excel.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
273
```xml const appValue = await Promise.resolve('hello') export default function Page() { return <p id="app-router-value">{appValue}</p> } ```
/content/code_sandbox/test/e2e/async-modules-app/app/app-router/page.tsx
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
33
```xml import type { WithOptimisticReducer, WrappedOptimisticState } from '../types'; import getWithoutFailed from './get-without-failed'; import type { TestState } from './testing.utils'; import { createTestDeterministicAction, createTestOptimisticHistoryItem, testReducer } from './testing.utils'; describe('getWithoutFailed', () => { test('should early return same state if optimistic history or checkpoint are empty', () => { const emptyCheckpoint: WrappedOptimisticState<TestState> = { items: [], optimistic: { checkpoint: undefined, history: [createTestDeterministicAction()], }, }; const stateEmptyHistory: WrappedOptimisticState<TestState> = { items: [], optimistic: { checkpoint: { items: [], }, history: [], }, }; expect(getWithoutFailed(emptyCheckpoint, {} as any)).toEqual(emptyCheckpoint); expect(getWithoutFailed(stateEmptyHistory, {} as any)).toEqual(stateEmptyHistory); }); test('should apply every non-failed action in history to the current checkpoint', () => { const failedAction = createTestOptimisticHistoryItem('add', 2); failedAction.failed = true; const state: WrappedOptimisticState<TestState> = { items: [1, 2, 3], optimistic: { checkpoint: { items: [] }, history: [ createTestOptimisticHistoryItem('add', 1), failedAction, createTestDeterministicAction('add', 3), ], }, }; const withOptimistic = { innerReducer: testReducer } as WithOptimisticReducer<TestState>; expect(getWithoutFailed(state, withOptimistic)).toEqual({ items: [1, 3], optimistic: { checkpoint: undefined, history: [] }, }); }); }); ```
/content/code_sandbox/packages/pass/store/optimistic/utils/get-without-failed.spec.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
401
```xml /** @example 'Something done (#123)' => 'Something done' */ export default function cleanPrCommitTitle(commitTitle: string, pr: number): string { return commitTitle.replace(new RegExp(`\\(#${pr}\\)\\s*$`), '').trim(); } ```
/content/code_sandbox/source/helpers/pr-commit-cleaner.ts
xml
2016-02-15T16:45:02
2024-08-16T18:39:26
refined-github
refined-github/refined-github
24,013
55
```xml import * as React from 'react'; import styles from './ScatterChartDemo.module.scss'; import { IScatterChartDemoProps } from './IScatterChartDemo.types'; // used to add a chart control import { ChartControl, ChartType } from '@pnp/spfx-controls-react/lib/ChartControl'; import * as strings from 'ScatterChartDemoWebPartStrings'; export class ScatterChartDemo extends React.Component<IScatterChartDemoProps, {}> { public render(): React.ReactElement<IScatterChartDemoProps> { return ( <div className={styles.scatterChartDemo}> <ChartControl type={ChartType.Scatter} data={ { datasets: [{ borderColor: styles.color1, backgroundColor: styles.color2, label: strings.DataSetLabel, data: [{ x: 1, y: -1.711e-2, }, { x: 1.26, y: -2.708e-2, }, { x: 1.58, y: -4.285e-2, }, { x: 2.0, y: -6.772e-2, }, { x: 2.51, y: -1.068e-1, }, { x: 3.16, y: -1.681e-1, }, { x: 3.98, y: -2.635e-1, }, { x: 5.01, y: -4.106e-1, }, { x: 6.31, y: -6.339e-1, }, { x: 7.94, y: -9.659e-1, }, { x: 10.00, y: -1.445, }, { x: 12.6, y: -2.110, }, { x: 15.8, y: -2.992, }, { x: 20.0, y: -4.102, }, { x: 25.1, y: -5.429, }, { x: 31.6, y: -6.944, }, { x: 39.8, y: -8.607, }, { x: 50.1, y: -1.038e1, }, { x: 63.1, y: -1.223e1, }, { x: 79.4, y: -1.413e1, }, { x: 100.00, y: -1.607e1, }, { x: 126, y: -1.803e1, }, { x: 158, y: -2e1, }, { x: 200, y: -2.199e1, }, { x: 251, y: -2.398e1, }, { x: 316, y: -2.597e1, }, { x: 398, y: -2.797e1, }, { x: 501, y: -2.996e1, }, { x: 631, y: -3.196e1, }, { x: 794, y: -3.396e1, }, { x: 1000, y: -3.596e1, }] }] }} options={{ title: { display: true, text: strings.ChartTitle }, scales: { xAxes: [{ type: 'logarithmic', position: 'bottom', ticks: { callback: (tick) => { var remain = tick / (Math.pow(10, Math.floor(this._log10(tick)))); if (remain === 1 || remain === 2 || remain === 5) { return tick.toString() + strings.xAxisUnit; } return ''; }, }, scaleLabel: { labelString: strings.xAxisLabel, display: true, } }], yAxes: [{ type: 'linear', ticks: { callback: (tick) => { return tick.toString() + strings.yAxisUnit; } }, scaleLabel: { labelString: strings.yAxisLabel, display: true } }] } }} /> </div> ); } private _log10 = (x: number): number => { const exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10. // Check for whole powers of 10, // which due to floating point rounding error should be corrected. const powerOf10 = Math.round(exponent); const isPowerOf10 = x === Math.pow(10, powerOf10); return isPowerOf10 ? powerOf10 : exponent; } } ```
/content/code_sandbox/samples/react-chartcontrol/src/webparts/scatterChartDemo/components/ScatterChartDemo.tsx
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
1,128
```xml import * as React from 'react' import { IAutocompletionProvider } from './index' import { compare } from '../../lib/compare' import { DefaultMaxHits } from './common' import { Emoji } from '../../lib/emoji' const sanitizeEmoji = (emoji: string) => emoji.replaceAll(':', '') /** * Interface describing a autocomplete match for the given search * input passed to EmojiAutocompletionProvider#getAutocompletionItems. */ export interface IEmojiHit { /** A human-readable markdown representation of the emoji, ex :heart: */ readonly emoji: string /** * The offset into the emoji string where the * match started, used for highlighting matches. */ readonly matchStart: number /** * The length of the match or zero if the filter * string was empty, causing the provider to return * all possible matches. */ readonly matchLength: number } /** Autocompletion provider for emoji. */ export class EmojiAutocompletionProvider implements IAutocompletionProvider<IEmojiHit> { public readonly kind = 'emoji' private readonly allEmoji: Map<string, Emoji> public constructor(emoji: Map<string, Emoji>) { this.allEmoji = emoji } public getRegExp(): RegExp { return /(?:^|\n| )(?::)([a-z\d\\+-][a-z\d_]*)?/g } public async getAutocompletionItems( text: string, maxHits = DefaultMaxHits ): Promise<ReadonlyArray<IEmojiHit>> { // This is the happy path to avoid sorting and matching // when the user types a ':'. We want to open the popup // with suggestions as fast as possible. if (text.length === 0) { return [...this.allEmoji.keys()] .map(emoji => ({ emoji, matchStart: 0, matchLength: 0 })) .slice(0, maxHits) } const results = new Array<IEmojiHit>() const needle = text.toLowerCase() for (const emoji of this.allEmoji.keys()) { const index = emoji.indexOf(needle) if (index !== -1) { results.push({ emoji, matchStart: index, matchLength: needle.length }) } } // Naive emoji result sorting // // Matches closer to the start of the string are sorted // before matches further into the string // // Longer matches relative to the emoji length is sorted // before the same match in a longer emoji // (:heart over :heart_eyes) // // If both those start and length are equal we sort // alphabetically return results .sort( (x, y) => compare(x.matchStart, y.matchStart) || compare(x.emoji.length, y.emoji.length) || compare(x.emoji, y.emoji) ) .slice(0, maxHits) } public getItemAriaLabel(hit: IEmojiHit): string { const emoji = this.allEmoji.get(hit.emoji) const sanitizedEmoji = sanitizeEmoji(hit.emoji) const emojiDescription = emoji?.description ?? sanitizedEmoji return emojiDescription === sanitizedEmoji ? emojiDescription : `${emojiDescription}, ${sanitizedEmoji}` } public renderItem(hit: IEmojiHit) { const emoji = this.allEmoji.get(hit.emoji) return ( <div className="emoji" key={hit.emoji}> <img className="icon" src={emoji?.url} alt={emoji?.description ?? hit.emoji} /> {this.renderHighlightedTitle(hit)} </div> ) } private renderHighlightedTitle(hit: IEmojiHit) { const emoji = sanitizeEmoji(hit.emoji) if (!hit.matchLength) { return <div className="title">{emoji}</div> } // Offset the match start by one to account for the leading ':' that was // removed from the emoji string const matchStart = hit.matchStart - 1 return ( <div className="title"> {emoji.substring(0, matchStart)} <mark>{emoji.substring(matchStart, matchStart + hit.matchLength)}</mark> {emoji.substring(matchStart + hit.matchLength)} </div> ) } public getCompletionText(item: IEmojiHit) { return item.emoji } } ```
/content/code_sandbox/app/src/ui/autocompletion/emoji-autocompletion-provider.tsx
xml
2016-05-11T15:59:00
2024-08-16T17:00:41
desktop
desktop/desktop
19,544
958
```xml class MemberCreationValidationError extends Error { public trace = false; } export default MemberCreationValidationError; ```
/content/code_sandbox/packages/account/members/errors/MemberCreationValidationError.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
21
```xml <?xml version="1.0" encoding="utf-8"?> <feed xmlns="path_to_url"><title>skidl</title><link href="path_to_url" rel="alternate"></link><link href="path_to_url" rel="self"></link><id>path_to_url Test Post</title><link href="path_to_url" rel="alternate"></link><published>2021-07-12T16:30:00-04:00</published><updated>2021-07-12T16:30:00-04:00</updated><author><name>Dave Vandenbout</name></author><id>tag:devbisme.github.io,2021-07-12:/skidl/first-test-post.html</id><summary type="html">&lt;p&gt;First test post.&lt;/p&gt;</summary><content type="html">&lt;p&gt;&lt;em&gt;This&lt;/em&gt; is my first test post!&lt;/p&gt;</content><category term="posts"></category><category term="test"></category></entry></feed> ```
/content/code_sandbox/docsrc/pelicansite/output/feeds/all.atom.xml
xml
2016-08-16T19:21:55
2024-08-13T22:10:15
skidl
devbisme/skidl
1,012
232
```xml import type { TreeItemPersonaLayoutSlots, TreeItemPersonaLayoutState } from './TreeItemPersonaLayout.types'; import type { SlotClassNames } from '@fluentui/react-utilities'; import { makeResetStyles, makeStyles, mergeClasses } from '@griffel/react'; import { tokens, typographyStyles } from '@fluentui/react-theme'; import { treeItemLevelToken } from '../../utils/tokens'; import { useTreeItemContext_unstable } from '../../contexts/treeItemContext'; export const treeItemPersonaLayoutClassNames: SlotClassNames<TreeItemPersonaLayoutSlots> = { root: 'fui-TreeItemPersonaLayout', media: 'fui-TreeItemPersonaLayout__media', description: 'fui-TreeItemPersonaLayout__description', main: 'fui-TreeItemPersonaLayout__main', expandIcon: 'fui-TreeItemPersonaLayout__expandIcon', aside: 'fui-TreeItemPersonaLayout__aside', actions: 'fui-TreeItemPersonaLayout__actions', selector: 'fui-TreeItemPersonaLayout__selector', }; const useRootBaseStyles = makeResetStyles({ display: 'grid', gridTemplateRows: '1fr auto', gridTemplateColumns: 'auto auto 1fr auto', gridTemplateAreas: ` "expandIcon media main aside" "expandIcon media description aside" `, alignItems: 'center', ...typographyStyles.body1, ':active': { color: tokens.colorNeutralForeground2Pressed, backgroundColor: tokens.colorSubtleBackgroundPressed, // TODO: stop using treeItemPersonaLayoutClassNames.expandIcon for styling [`& .${treeItemPersonaLayoutClassNames.expandIcon}`]: { color: tokens.colorNeutralForeground3Pressed, }, }, ':hover': { color: tokens.colorNeutralForeground2Hover, backgroundColor: tokens.colorSubtleBackgroundHover, // TODO: stop using treeItemPersonaLayoutClassNames.expandIcon for styling [`& .${treeItemPersonaLayoutClassNames.expandIcon}`]: { color: tokens.colorNeutralForeground3Hover, }, }, }); /** * Styles for the root slot */ const useRootStyles = makeStyles({ leaf: { paddingLeft: `calc(var(${treeItemLevelToken}, 1) * ${tokens.spacingHorizontalXXL})`, }, branch: { paddingLeft: `calc((var(${treeItemLevelToken}, 1) - 1) * ${tokens.spacingHorizontalXXL})`, }, }); /** * Styles for the expand icon slot */ const useMediaBaseStyles = makeResetStyles({ display: 'flex', alignItems: 'center', width: '32px', height: '32px', gridArea: 'media', padding: `0 ${tokens.spacingHorizontalXS} 0 ${tokens.spacingHorizontalXXS}`, }); const useMainBaseStyles = makeResetStyles({ gridArea: 'main', padding: `${tokens.spacingVerticalMNudge} ${tokens.spacingHorizontalXS} ${tokens.spacingVerticalMNudge} ${tokens.spacingHorizontalS}`, }); const useMainStyles = makeStyles({ withDescription: { padding: `${tokens.spacingVerticalMNudge} ${tokens.spacingHorizontalXS} 0 ${tokens.spacingHorizontalS}`, }, }); const useDescriptionBaseStyles = makeResetStyles({ gridArea: 'description', ...typographyStyles.caption1, padding: `0 ${tokens.spacingHorizontalXS} ${tokens.spacingVerticalMNudge} ${tokens.spacingHorizontalS}`, }); /** * Styles for the action icon slot */ const useActionsBaseStyles = makeResetStyles({ display: 'flex', marginLeft: 'auto', position: 'relative', zIndex: 1, gridArea: 'aside', padding: `0 ${tokens.spacingHorizontalS}`, }); /** * Styles for the action icon slot */ const useAsideBaseStyles = makeResetStyles({ display: 'flex', marginLeft: 'auto', alignItems: 'center', zIndex: 0, gridArea: 'aside', padding: `0 ${tokens.spacingHorizontalM}`, gap: tokens.spacingHorizontalXS, }); /** * Styles for the expand icon slot */ const useExpandIconBaseStyles = makeResetStyles({ display: 'flex', alignItems: 'center', justifyContent: 'center', minWidth: '24px', boxSizing: 'border-box', color: tokens.colorNeutralForeground3, gridArea: 'expandIcon', flex: `0 0 auto`, padding: `${tokens.spacingVerticalXS} 0`, }); /** * Apply styling to the TreeItemPersonaLayout slots based on the state */ export const useTreeItemPersonaLayoutStyles_unstable = ( state: TreeItemPersonaLayoutState, ): TreeItemPersonaLayoutState => { 'use no memo'; const rootBaseStyles = useRootBaseStyles(); const rootStyles = useRootStyles(); const mediaBaseStyles = useMediaBaseStyles(); const descriptionBaseStyles = useDescriptionBaseStyles(); const actionsBaseStyles = useActionsBaseStyles(); const asideBaseStyles = useAsideBaseStyles(); const expandIconBaseStyles = useExpandIconBaseStyles(); const mainBaseStyles = useMainBaseStyles(); const mainStyles = useMainStyles(); const itemType = useTreeItemContext_unstable(ctx => ctx.itemType); state.root.className = mergeClasses( treeItemPersonaLayoutClassNames.root, rootBaseStyles, rootStyles[itemType], state.root.className, ); state.media.className = mergeClasses(treeItemPersonaLayoutClassNames.media, mediaBaseStyles, state.media.className); if (state.main) { state.main.className = mergeClasses( treeItemPersonaLayoutClassNames.main, mainBaseStyles, state.description && mainStyles.withDescription, state.main.className, ); } if (state.description) { state.description.className = mergeClasses( treeItemPersonaLayoutClassNames.description, descriptionBaseStyles, state.description.className, ); } if (state.actions) { state.actions.className = mergeClasses( treeItemPersonaLayoutClassNames.actions, actionsBaseStyles, state.actions.className, ); } if (state.aside) { state.aside.className = mergeClasses(treeItemPersonaLayoutClassNames.aside, asideBaseStyles, state.aside.className); } if (state.expandIcon) { state.expandIcon.className = mergeClasses( treeItemPersonaLayoutClassNames.expandIcon, expandIconBaseStyles, state.expandIcon.className, ); } if (state.selector) { state.selector.className = mergeClasses(treeItemPersonaLayoutClassNames.selector, state.selector.className); } return state; }; ```
/content/code_sandbox/packages/react-components/react-tree/library/src/components/TreeItemPersonaLayout/useTreeItemPersonaLayoutStyles.styles.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
1,438
```xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="path_to_url"> <response> <result code="1000"> <msg>Command completed successfully</msg> </result> <resData> <domain:infData xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"> <domain:name>example.tld</domain:name> <domain:roid>%ROID%</domain:roid> <domain:status s="ok"/> <domain:registrant>jd1234</domain:registrant> <domain:contact type="admin">sh8013</domain:contact> <domain:contact type="tech">sh8013</domain:contact> <domain:ns> <domain:hostObj>ns1.example.tld</domain:hostObj> <domain:hostObj>ns2.example.tld</domain:hostObj> </domain:ns> <domain:host>ns1.example.tld</domain:host> <domain:host>ns2.example.tld</domain:host> <domain:clID>NewRegistrar</domain:clID> <domain:crID>TheRegistrar</domain:crID> <domain:crDate>1999-04-03T22:00:00.0Z</domain:crDate> <domain:upID>NewRegistrar</domain:upID> <domain:upDate>1999-12-03T09:00:00.0Z</domain:upDate> <domain:exDate>2005-04-03T22:00:00.0Z</domain:exDate> <domain:trDate>2000-04-08T09:00:00.0Z</domain:trDate> <domain:authInfo> <domain:pw>2fooBAR</domain:pw> </domain:authInfo> </domain:infData> </resData> <extension> <secDNS:infData xmlns:secDNS="urn:ietf:params:xml:ns:secDNS-1.1"> <secDNS:dsData> <secDNS:keyTag>12345</secDNS:keyTag> <secDNS:alg>3</secDNS:alg> <secDNS:digestType>1</secDNS:digestType> <secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest> </secDNS:dsData> </secDNS:infData> </extension> <trID> <clTRID>ABC-12345</clTRID> <svTRID>server-trid</svTRID> </trID> </response> </epp> ```
/content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_info_response_dsdata.xml
xml
2016-02-29T20:16:48
2024-08-15T19:49:29
nomulus
google/nomulus
1,685
636
```xml import { assert, expect } from 'chai'; import { buildFilter } from '../buildFilter'; import { ParentType, ParserOptions, PropItem } from '../parser'; function createProp( name: string, required: boolean = false, defaultValue?: any, description: string = '', type = { name: 'string' }, parent?: ParentType ): PropItem { return { defaultValue, description, name, parent, required, type }; } describe('buildFilter', () => { describe('default behaviour', () => { it('should skip "children" property if no description is set', () => { const prop1 = createProp('prop1', false, undefined, 'prop1 description'); const prop2 = createProp('prop2', false, undefined, 'prop2 description'); const children = createProp('children', false, undefined, ''); const opts: ParserOptions = {}; const filterFn = buildFilter(opts); expect( [prop1, prop2, children].filter(prop => filterFn(prop, { name: prop.name }) ) ).to.eql([prop1, prop2]); }); it('should not skip "children" property if description is set', () => { const prop1 = createProp('prop1', false, undefined, 'prop1 description'); const prop2 = createProp('prop2', false, undefined, 'prop2 description'); const children = createProp( 'children', false, undefined, 'children description' ); const opts: ParserOptions = {}; const filterFn = buildFilter(opts); expect( [prop1, prop2, children].filter(prop => filterFn(prop, { name: prop.name }) ) ).to.eql([prop1, prop2, children]); }); }); describe('static prop filter', () => { describe('skipPropsWithName', () => { it('should skip single prop by name', () => { const prop1 = createProp( 'prop1', false, undefined, 'prop1 description' ); const prop2 = createProp( 'prop2', false, undefined, 'prop2 description' ); const opts: ParserOptions = { propFilter: { skipPropsWithName: 'prop1' } }; const filterFn = buildFilter(opts); expect( [prop1, prop2].filter(prop => filterFn(prop, { name: prop.name })) ).to.eql([prop2]); }); it('should skip multiple props by name', () => { const prop1 = createProp( 'prop1', false, undefined, 'prop1 description' ); const prop2 = createProp( 'prop2', false, undefined, 'prop2 description' ); const prop3 = createProp( 'prop3', false, undefined, 'prop3 description' ); const opts: ParserOptions = { propFilter: { skipPropsWithName: ['prop1', 'prop3'] } }; const filterFn = buildFilter(opts); expect( [prop1, prop2, prop3].filter(prop => filterFn(prop, { name: prop.name }) ) ).to.eql([prop2]); }); }); describe('skipPropsWithoutDoc', () => { it('should skip children props with no documentation', () => { const prop1 = createProp( 'prop1', false, undefined, 'prop1 description' ); const prop2 = createProp('prop2', false, undefined, ''); const opts: ParserOptions = { propFilter: { skipPropsWithoutDoc: true } }; const filterFn = buildFilter(opts); expect( [prop1, prop2].filter(prop => filterFn(prop, { name: prop.name })) ).to.eql([prop1]); }); }); }); describe('dynamic prop filter', () => { it('should skip props based on dynamic filter rule', () => { const prop1 = createProp('foo', false, undefined, 'foo description'); const prop2 = createProp('bar', false, undefined, 'bar description'); const prop3 = createProp( 'foobar', false, undefined, 'foobar description' ); const opts: ParserOptions = { propFilter: (prop, component) => prop.name.indexOf('foo') === -1 }; const filterFn = buildFilter(opts); expect( [prop1, prop2, prop3].filter(prop => filterFn(prop, { name: prop.name }) ) ).to.eql([prop2]); }); it('should get be possible to filter by component name', () => { const prop1 = createProp('foo', false, undefined, 'foo description'); const prop2 = createProp('bar', false, undefined, 'bar description'); const prop3 = createProp( 'foobar', false, undefined, 'foobar description' ); const opts: ParserOptions = { propFilter: (prop, component) => component.name.indexOf('BAR') === -1 }; const filterFn = buildFilter(opts); expect( [prop1, prop2, prop3].filter(prop => filterFn(prop, { name: prop.name.toUpperCase() }) ) ).to.eql([prop1]); }); it('should be possible to filter by interface in which prop was declared.', () => { const stringType = { name: 'string' }; const htmlAttributesInterface = { fileName: 'node_modules/@types/react/index.d.ts', name: 'HTMLAttributes' }; const excludedType = { name: 'ExcludedType', fileName: 'src/types.ts' }; const prop1 = createProp( 'foo', false, undefined, 'foo description', stringType ); const prop2 = createProp( 'bar', false, undefined, 'bar description', stringType, excludedType ); const prop3 = createProp( 'onFocus', false, undefined, 'onFocus description', stringType, htmlAttributesInterface ); const opts: ParserOptions = { propFilter: (prop, component) => { if (prop.parent == null) { return true; } if (prop.parent.fileName.indexOf('@types/react/index.d.ts') > -1) { return false; } return prop.parent.name !== 'ExcludedType'; } }; const filterFn = buildFilter(opts); expect( [prop1, prop2, prop3].filter(prop => filterFn(prop, { name: 'SomeComponent' }) ) ).to.eql([prop1]); }); }); }); ```
/content/code_sandbox/src/__tests__/buildFilter.ts
xml
2016-05-06T14:40:29
2024-08-15T13:51:56
react-docgen-typescript
styleguidist/react-docgen-typescript
1,176
1,494
```xml export { default as ApprovalDialog, IApprovalDialog } from './ApprovalDialog'; export { default as ApproversPanel, IApproversPanel } from './ApproversPanel'; export { default as ConfigureApproversPanel, IConfigureApproversPanel } from './ConfigureApproversPanel'; export { default as MyApprovalsPanel, IMyApprovalsPanel } from './MyApprovalsPanel'; export { MyApprovalsFilter } from './MyApprovalsFilter'; ```
/content/code_sandbox/samples/react-rhythm-of-business-calendar/src/components/approvals/index.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
94
```xml import { $ } from '../$.js'; import { removeAttribute } from '../shared/attributes.js'; import { eachArray } from '../shared/helper.js'; import './each.js'; import type { JQ } from '../shared/core.js'; declare module '../shared/core.js' { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface JQ<T = HTMLElement> { /** * * @param attributeName * @example ```js // $('div').removeAttr('title') ``` * @example ```js // $('div').removeAttr('title label'); ``` */ removeAttr(attributeName: string): this; } } $.fn.removeAttr = function (this: JQ, attributeName: string): JQ { const names = attributeName.split(' ').filter((name) => name); return this.each(function () { eachArray(names, (name) => { removeAttribute(this, name); }); }); }; ```
/content/code_sandbox/packages/jq/src/methods/removeAttr.ts
xml
2016-07-11T17:39:02
2024-08-16T07:12:34
mdui
zdhxiong/mdui
4,077
208
```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"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:background="@mipmap/pop_bg" android:paddingTop="25dp" android:paddingLeft="20dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1,this is tip1" android:textColor="@android:color/white" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2,this is tip2" android:layout_marginTop="5dp" android:textColor="@android:color/white" /> </LinearLayout> </LinearLayout> ```
/content/code_sandbox/app/src/main/res/layout/pop_layout1.xml
xml
2016-11-30T15:02:37
2024-08-06T06:46:04
CustomPopwindow
pinguo-zhouwei/CustomPopwindow
1,419
216
```xml import { ApolloError } from "apollo-server-express"; import { DocumentNode, GraphQLFormattedError, OperationDefinitionNode, OperationTypeNode, } from "graphql"; import { merge } from "lodash"; import { CoralError, InternalDevelopmentError, WrappedInternalError, } from "coral-server/errors"; import { PersistedQuery } from "coral-server/models/queries"; import GraphContext from "../context"; export interface OperationMetadata { operationName: string; operation: OperationTypeNode; } /** * getOperationMetadata will extract the operation metadata from the document * node. * @param doc the document node that can be used to extract operation metadata * from */ export const getOperationMetadata = ( doc: DocumentNode ): Partial<OperationMetadata> => { if (doc.kind === "Document") { const operationDefinition = doc.definitions.find( ({ kind }) => kind === "OperationDefinition" ) as OperationDefinitionNode | undefined; if (operationDefinition) { let operationName: string | undefined; if (operationDefinition.name) { operationName = operationDefinition.name.value; } return { operationName, operation: operationDefinition.operation, }; } } return {}; }; interface PersistedQueryOperationMetadata extends OperationMetadata { persistedQueryID: string; persistedQueryBundle: string; persistedQueryVersion: string; } /** * getPersistedQueryMetadata will remap the persisted query to the operation * metadata. * @param persisted persisted query to remap to operation metadata */ export const getPersistedQueryMetadata = ({ id: persistedQueryID, operation, operationName, bundle: persistedQueryBundle, version: persistedQueryVersion, }: PersistedQuery): PersistedQueryOperationMetadata => ({ persistedQueryID, persistedQueryBundle, persistedQueryVersion, operation, operationName, }); /** * getOriginalError tries to return the original error from a * formatted GraphQL error. * @param err A GraphQL Formatted Error */ export const getOriginalError = (err: GraphQLFormattedError) => { if ((err as any).originalError) { return (err as any).originalError as Error; } return null; }; function hoistCoralErrorExtensions( ctx: GraphContext, err: GraphQLFormattedError ): void { // Grab or wrap the originalError so that it's a CoralError. const originalError = getWrappedOriginalError(err, ctx); if (!originalError) { return; } // Get the translation bundle. const bundle = ctx.i18n.getBundle(ctx.tenant ? ctx.tenant.locale : ctx.lang); // Translate the extensions. const extensions = originalError.serializeExtensions(bundle, ctx.id); // Hoist the message from the original error into the message of the base // error. (err as any).message = extensions.message; // Re-hoist the extensions. merge(err.extensions, extensions); return; } /** * getWrappedOriginalError will pull out the original error if available. * @param err the error to have their original error extracted from. * @param ctx the Context to extract the environment state. */ export function getWrappedOriginalError( err: GraphQLFormattedError, ctx?: GraphContext ): CoralError | undefined { if (err instanceof ApolloError) { // ApolloError's don't need to be hoisted as they contain validation // messages about the graph. return; } const originalError = getOriginalError(err); if (!originalError) { // Only errors that have an originalError need to be hoisted. return; } if (originalError instanceof CoralError) { return originalError; } // If the context is provided, and we aren't in production, then return an // internal development error instead of a wrapped internal error. if (ctx && ctx.config.get("env") !== "production") { return new InternalDevelopmentError( originalError, "wrapped internal development error" ); } return new WrappedInternalError(originalError, "wrapped internal error"); } /** * enrichAndLogError will enrich and then log out the error. * @param ctx the GraphQL context for the request * @param err the error that occurred */ export function enrichError( ctx: GraphContext, err: GraphQLFormattedError ): GraphQLFormattedError { if (err.extensions) { // Delete the exception field from the error extension, we never need to // provide that data. if (err.extensions.exception) { delete err.extensions.exception; } if (getOriginalError(err)) { // Hoist the extensions onto the error. hoistCoralErrorExtensions(ctx, err); } } return err; } ```
/content/code_sandbox/server/src/core/server/graph/plugins/helpers.ts
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
1,035
```xml import { HttpClientModule } from '@angular/common/http'; import { TestBed } from '@angular/core/testing'; import { InMemoryCache } from '@apollo/client/core'; import { mockSingleLink } from '@apollo/client/testing'; import { Apollo, APOLLO_OPTIONS, ApolloModule } from '../src'; describe('Integration', () => { describe('default', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [ApolloModule, HttpClientModule], providers: [ { provide: APOLLO_OPTIONS, useFactory: () => { return { link: mockSingleLink(), cache: new InMemoryCache(), }; }, }, ], }); }); test('apollo should be initialized', () => { const apollo = TestBed.inject(Apollo); expect(() => apollo.client).not.toThrow(); }); }); }); ```
/content/code_sandbox/packages/apollo-angular/tests/integration.spec.ts
xml
2016-04-16T00:10:50
2024-08-15T11:41:24
apollo-angular
kamilkisiela/apollo-angular
1,497
183
```xml import React from 'react'; import { TouchableOpacity, Modal, View, StatusBar, I18nManager, ViewStyle, StyleProp, ColorValue, Platform, Dimensions, Pressable, } from 'react-native'; import Triangle from './components/Triangle'; import { ScreenWidth, isIOS, RneFunctionComponent } from '../helpers'; import { getElementVisibleWidth } from './helpers/getTooltipCoordinate'; import { getTooltipStyle } from './helpers/getTooltipStyle'; export interface TooltipProps { /** To show the tooltip. */ visible?: boolean; /** Flag to determine whether or not to display the pointer. */ withPointer?: boolean; /** Component to be rendered as the display container. */ popover?: React.ReactElement<{}>; /** Flag to determine to toggle or not the tooltip on press. */ toggleOnPress?: boolean; /** Define type of action that should trigger tooltip. Available options _onPress_, _onLongPress_ */ toggleAction?: | string | 'onPress' | 'onLongPress' | 'onPressIn' | 'onPressOut'; /** Tooltip container height. Necessary in order to render the container in the correct place. Pass height according to the size of the content rendered inside the container. */ height?: number; /** Tooltip container width. Necessary in order to render the container in the correct place. Pass height according to the size of the content rendered inside the container. */ width?: number; /** Passes style object to tooltip container */ containerStyle?: StyleProp<ViewStyle>; /** Color of tooltip pointer, it defaults to the [`backgroundColor`](#backgroundcolor) if none is passed. */ pointerColor?: ColorValue; /** Function which gets called on closing the tooltip. */ onClose?(): void; /** Function which gets called on opening the tooltip. */ onOpen?(): void; /** Color of overlay shadow when tooltip is open. */ overlayColor?: ColorValue; /** Flag to determine whether or not display overlay shadow when tooltip is open. */ withOverlay?: boolean; /** Sets backgroundColor of the tooltip and pointer. */ backgroundColor?: ColorValue; /** Color to highlight the item the tooltip is surrounding. */ highlightColor?: ColorValue; /** Force skip StatusBar height when calculating element position. Pass `true` if Tooltip used inside react-native Modal component. */ skipAndroidStatusBar?: boolean; /** Flag to determine whether to disable auto hiding of tooltip when touching/scrolling anywhere inside the active tooltip popover container. When `true`, Tooltip closes only when overlay backdrop is pressed (or) highlighted tooltip button is pressed. */ closeOnlyOnBackdropPress?: boolean; /** Override React Native `Modal` component (usable for web-platform). */ ModalComponent?: typeof React.Component; /** Style to be applied on the pointer. */ pointerStyle?: StyleProp<ViewStyle>; /** */ animationType?: 'fade' | 'none'; } /** Tooltips display informative text when users tap on an element. * @usage * ### Example *```tsx live function RNETooltip() { const [open, setOpen] = React.useState(false); return ( <Stack row align="center"> <Tooltip visible={open} onOpen={() => setOpen(true)} onClose={() => setOpen(false)} popover={<Text style={{color:'#fff'}}>Tooltip text</Text>} > Click me </Tooltip> </Stack> ); } * ``` */ export const Tooltip: RneFunctionComponent<TooltipProps> = ({ withOverlay = true, overlayColor = '#fafafa14', highlightColor = 'transparent', withPointer = true, toggleOnPress = true, toggleAction = 'onPress', height = 40, width = 150, containerStyle = {}, backgroundColor = '#617080', pointerColor = backgroundColor, pointerStyle, onClose = () => {}, onOpen = () => {}, visible = false, skipAndroidStatusBar = false, ModalComponent = Modal, closeOnlyOnBackdropPress = false, animationType = 'fade', ...props }) => { const isMounted = React.useRef(false); const renderedElement = React.useRef<View>(null); const [dimensions, setDimensions] = React.useState({ yOffset: 0, xOffset: 0, elementWidth: 0, elementHeight: 0, }); const getElementPosition = React.useCallback(() => { renderedElement.current?.measure( ( _frameOffsetX, _frameOffsetY, _width = 0, _height = 0, pageOffsetX = 0, pageOffsetY = 0 ) => { isMounted.current && setDimensions({ xOffset: pageOffsetX, yOffset: isIOS || skipAndroidStatusBar ? pageOffsetY : pageOffsetY - Platform.select({ android: StatusBar.currentHeight, ios: 20, default: 0, }), elementWidth: _width, elementHeight: _height, }); } ); }, [skipAndroidStatusBar]); const handleOnPress = React.useCallback(() => { getElementPosition(); isMounted.current && toggleOnPress && (visible ? onClose?.() : onOpen?.()); }, [getElementPosition, onClose, onOpen, toggleOnPress, visible]); const Pointer: React.FC<{ tooltipY: number | string; }> = ({ tooltipY }) => { const { yOffset, xOffset, elementHeight, elementWidth } = dimensions; const pastMiddleLine = yOffset > (tooltipY || 0); if (!withPointer) { return null; } return ( <View style={{ position: 'absolute', top: pastMiddleLine ? yOffset - 13 : yOffset + elementHeight - 2, [I18nManager.isRTL ? 'right' : 'left']: xOffset + getElementVisibleWidth(elementWidth, xOffset, ScreenWidth) / 2 - 7.5, }} > <Triangle style={pointerStyle} pointerColor={pointerColor} isDown={pastMiddleLine} /> </View> ); }; const TooltipHighlightedButtonStyle = React.useMemo<ViewStyle>(() => { const { yOffset, xOffset, elementWidth, elementHeight } = dimensions; return { position: 'absolute', top: yOffset, [I18nManager.isRTL ? 'right' : 'left']: xOffset, backgroundColor: highlightColor, overflow: 'visible', width: elementWidth, height: elementHeight, }; }, [dimensions, highlightColor]); const HighlightedButton: React.FC = () => { if (!closeOnlyOnBackdropPress) { return ( <Pressable testID="tooltipTouchableHighlightedButton" onPress={handleOnPress} style={TooltipHighlightedButtonStyle} > {props.children} </Pressable> ); } else { return ( <View testID="tooltipTouchableHighlightedButton" style={TooltipHighlightedButtonStyle} > {props.children} </View> ); } }; /** * Listen for change in layout, i.e. Portrait or Landscape */ React.useEffect(() => { isMounted.current = true; // Wait till element's position is calculated requestAnimationFrame(getElementPosition); const dimensionsListener = Dimensions.addEventListener( 'change', getElementPosition ); return () => { isMounted.current = false; if (dimensionsListener?.remove) { // react-native >= 0.65.* dimensionsListener.remove(); } else { // react-native < 0.65.* Dimensions.removeEventListener('change', getElementPosition); } }; }, [getElementPosition]); /** * Calculate position of tooltip */ const tooltipStyle = React.useMemo( () => getTooltipStyle({ ...dimensions, backgroundColor, containerStyle, height, width, withPointer, }), [backgroundColor, containerStyle, dimensions, height, width, withPointer] ); return ( <View collapsable={false} ref={renderedElement}> <Pressable {...{ [toggleAction]: handleOnPress }} delayLongPress={250}> {props.children} </Pressable> <ModalComponent transparent visible={visible} onShow={onOpen} animationType={animationType} > <TouchableOpacity style={{ backgroundColor: withOverlay ? overlayColor : 'transparent', flex: 1, }} onPress={handleOnPress} activeOpacity={1} > <View> <HighlightedButton /> <Pointer tooltipY={tooltipStyle.top} /> <View style={tooltipStyle} testID="tooltipPopoverContainer"> {props.popover} </View> </View> </TouchableOpacity> </ModalComponent> </View> ); }; Tooltip.displayName = 'Tooltip'; ```
/content/code_sandbox/packages/base/src/Tooltip/Tooltip.tsx
xml
2016-09-08T14:21:41
2024-08-16T10:11:29
react-native-elements
react-native-elements/react-native-elements
24,875
1,955
```xml export interface IMeeting { id: string; subject: string; start: Date; end: Date; webLink: string; isAllDay: boolean; location: string; organizer: string; status: string; } ```
/content/code_sandbox/samples/react-aad-implicitflow/src/webparts/upcomingMeetings/components/IMeeting.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
56
```xml import * as React from 'react'; import { styled } from '@fluentui/react/lib/Utilities'; import { IHorizontalBarChartProps, IHorizontalBarChartStyleProps, IHorizontalBarChartStyles, } from './HorizontalBarChart.types'; import { HorizontalBarChartBase } from './HorizontalBarChart.base'; import { getHorizontalBarChartStyles } from './HorizontalBarChart.styles'; // Create a HorizontalBarChart variant which uses these default styles and this styled subcomponent. /** * HorizontalBarchart component. * {@docCategory HorizontalBarChart} */ export const HorizontalBarChart: React.FunctionComponent<IHorizontalBarChartProps> = styled< IHorizontalBarChartProps, IHorizontalBarChartStyleProps, IHorizontalBarChartStyles >(HorizontalBarChartBase, getHorizontalBarChartStyles); ```
/content/code_sandbox/packages/react-charting/src/components/HorizontalBarChart/HorizontalBarChart.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
171
```xml import { addProjectConfiguration, ProjectType, stripIndents, writeJson } from '@nx/devkit'; import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing'; import { execSync, spawnSync, SpawnSyncReturns } from 'child_process'; import { workspacePaths } from '../../utils'; import epicGenerator from './index'; jest.mock('child_process'); const execSyncMock = execSync as unknown as jest.Mock<string>; const spawnSyncMock = spawnSync as unknown as jest.Mock<Partial<SpawnSyncReturns<string[]>>>; type Package = { name: string; version: string; projectType: ProjectType; owners: string[]; }; function setupTest(packages: Package[]) { const tree = createTreeWithEmptyWorkspace(); // Initialize NX package structure packages.forEach(pckg => { // package.json initialization writeJson(tree, `packages/${pckg.name}/package.json`, { name: pckg.name, version: pckg.version, }); // workspace.json initialization addProjectConfiguration(tree, pckg.name, { root: `packages/${pckg.name}`, projectType: pckg.projectType, }); }); // set mock CODEOWNERS file const codeownersContent = packages .map(pckg => { const rootPath = pckg.projectType === 'application' ? 'apps' : 'packages'; return `${rootPath}/${pckg.name} ${pckg.owners.join(' ')}`; }) .join('\n'); tree.write(workspacePaths.github.codeowners, codeownersContent); // response to 'gh auth' spawnSyncMock.mockReturnValueOnce({ output: [['Logged in to github.com']], }); // response to epic creation execSyncMock.mockReturnValueOnce('epicUrl'); /** * Responses for each of the packages created * Mimics implementation and adds an "unknown" owner to mock * for packages with no owner * Only accepts teams as owners (discards owners with no '/') */ packages .filter(pckg => pckg.projectType === 'library') .flatMap(pckg => (pckg.owners.length > 0 ? pckg.owners : ['unknown'])) .reduce<string[]>((acc, owner) => { if (owner.includes('/') && !acc.includes(owner)) { acc.push(owner); } return acc; }, []) .forEach(owner => { execSyncMock.mockReturnValueOnce(`issueUrl-${owner}`); }); // response to editing the epic execSyncMock.mockReturnValueOnce('epicUrl'); return tree; } describe('epic-generator', () => { beforeEach(() => { jest.restoreAllMocks(); // eslint-disable-next-line @typescript-eslint/no-empty-function jest.spyOn(console, 'log').mockImplementation(() => {}); }); describe('validation', () => { it('requires a non-empty title', () => { const tree = createTreeWithEmptyWorkspace(); expect(() => epicGenerator(tree, { title: ' ', repository: 'microsoft/fluentui' }), ).toThrowErrorMatchingInlineSnapshot(`"Must provide a title for the issue"`); }); it('requires a well formatted repository', () => { const tree = createTreeWithEmptyWorkspace(); expect(() => epicGenerator(tree, { title: 'test title', repository: 'invalid_repo' })) .toThrowErrorMatchingInlineSnapshot(` "You provided \\"invalid_repo\\", which is an invalid repository name. Please follow the format {owner}/{repositoryName}." `); }); }); describe('authentication', () => { it('requires gh to be installed', () => { spawnSyncMock.mockReturnValueOnce({ error: new Error('command not found.'), }); const tree = createTreeWithEmptyWorkspace(); expect(() => epicGenerator(tree, { title: 'test title', repository: 'microsoft/fluentui' })) .toThrowErrorMatchingInlineSnapshot(` "Error calling GitHub CLI (gh). Please make sure it's installed correctly. command not found." `); }); it('requires you to have logged in with gh', () => { spawnSyncMock.mockReturnValueOnce({ output: [['You are not logged into any GitHub hosts. Run gh auth login to authenticate.']], }); const tree = createTreeWithEmptyWorkspace(); expect(() => epicGenerator(tree, { title: 'test title', repository: 'microsoft/fluentui' }), ).toThrowErrorMatchingInlineSnapshot(`"You are not logged into GitHub CLI (gh)."`); }); }); describe('issue generation', () => { it('handles a real life scenario', () => { const packages: Package[] = [ { name: 'public-docsite', version: '9.0.0', projectType: 'application', owners: ['@microsoft/fluentui-v8-website'], }, { name: 'react-link', version: '9.0.0', projectType: 'library', owners: ['@microsoft/cxe-red', '@khmakoto', '@microsoft/cxe-coastal'], }, { name: 'react-card', version: '9.0.0', projectType: 'library', owners: ['@microsoft/cxe-prg'], }, { name: 'react', version: '8.0.0', projectType: 'library', owners: ['@microsoft/cxe-red'], }, { name: 'react-menu', version: '9.0.0', projectType: 'library', owners: ['@microsoft/teams-prg'], }, { name: 'react-button', version: '9.0.0', projectType: 'library', owners: ['@microsoft/cxe-red', '@khmakoto'], }, { name: 'misterious-unowned-package', version: '9.0.0', projectType: 'library', owners: [], }, { name: 'react-slider', version: '9.0.0', projectType: 'library', owners: ['@microsoft/cxe-coastal', '@micahgodbolt'], }, { name: 'vr-tests', version: '9.0.0', projectType: 'application', owners: ['@microsoft/fluentui-react'], }, { name: 'react-accordion', version: '9.0.0', projectType: 'library', owners: ['@microsoft/teams-prg', '@microsoft/cxe-coastal'], }, ]; const tree = setupTest(packages); const effectsCall = epicGenerator(tree, { title: 'test title', repository: 'cool-company/repository', }); effectsCall(); expect(execSyncMock).nthCalledWith( 1, stripIndents`gh issue create --repo "cool-company/repository" --title "test title" --body "*Description to be added*"`, ); // @microsoft/cxe-red issue creation expect(execSyncMock).nthCalledWith( 2, stripIndents`gh issue create --repo "cool-company/repository" --title "test title - @microsoft/cxe-red" --body " This is an auto-generated issue to individually track migration progress. ### Packages to migrate: - react-link - react-button"`, ); // @microsoft/cxe-prg issue creation expect(execSyncMock).nthCalledWith( 3, stripIndents`gh issue create --repo "cool-company/repository" --title "test title - @microsoft/cxe-prg" --body " This is an auto-generated issue to individually track migration progress. ### Packages to migrate: - react-card"`, ); // @microsoft/teams-prg issue creation expect(execSyncMock).nthCalledWith( 4, stripIndents`gh issue create --repo "cool-company/repository" --title "test title - @microsoft/teams-prg" --body " This is an auto-generated issue to individually track migration progress. ### Packages to migrate: - react-menu - react-accordion"`, ); // no owner issue creation expect(execSyncMock).nthCalledWith( 5, stripIndents`gh issue create --repo "cool-company/repository" --title "test title - ownerless" --body " This is an auto-generated issue to individually track migration progress. ### Packages to migrate: - misterious-unowned-package"`, ); // @microsoft/cxe-coastal issue creation expect(execSyncMock).nthCalledWith( 6, stripIndents`gh issue create --repo "cool-company/repository" --title "test title - @microsoft/cxe-coastal" --body " This is an auto-generated issue to individually track migration progress. ### Packages to migrate: - react-slider"`, ); // epic edit to add sub-issues expect(execSyncMock).nthCalledWith( 7, stripIndents`gh issue edit epicUrl --body "*Description to be added* ### Packages that need migration: - [ ] issueUrl-@microsoft/cxe-red - react-link - react-button - [ ] issueUrl-@microsoft/cxe-coastal - react-card - [ ] issueUrl-@microsoft/cxe-prg - react-menu - react-accordion - [ ] issueUrl-@microsoft/teams-prg - misterious-unowned-package - [ ] epicUrl - react-slider"`, ); }); }); }); ```
/content/code_sandbox/tools/workspace-plugin/src/generators/epic-generator/index.spec.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
2,142
```xml import { nextTestSetup } from 'e2e-utils' import { check } from 'next-test-utils' describe('RSC binary serialization', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, dependencies: { react: '19.0.0-beta-04b058868c-20240508', 'react-dom': '19.0.0-beta-04b058868c-20240508', 'server-only': 'latest', }, }) if (skipped) return afterEach(async () => { await next.stop() }) it('should correctly encode/decode binaries and hydrate', async function () { const browser = await next.browser('/') await check(async () => { const content = await browser.elementByCss('body').text() return content.includes('utf8 binary: hello') && content.includes('arbitrary binary: 255,0,1,2,3') && content.includes('hydrated: true') ? 'success' : 'fail' }, 'success') }) }) ```
/content/code_sandbox/test/e2e/app-dir/binary/rsc-binary.test.ts
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
244
```xml import { Text, TextProps } from './Text'; export { Text }; export type { TextProps }; ```
/content/code_sandbox/packages/base/src/Text/index.tsx
xml
2016-09-08T14:21:41
2024-08-16T10:11:29
react-native-elements
react-native-elements/react-native-elements
24,875
22
```xml import Spinner from "@erxes/ui/src/components/Spinner"; import { IField } from "@erxes/ui/src/types"; import { gql } from "@apollo/client"; import React from "react"; import { useQuery } from "@apollo/client"; import RelationForm from "../components/RelationForm"; import queries from "../queries"; type Props = { contentType: string; insertedId?: string; onChange: (relations: any) => void; }; const Container = (props: Props) => { const { data, loading } = useQuery(gql(queries.relations), { variables: { contentType: props.contentType, isVisibleToCreate: true } }); if (loading) { return <Spinner objective={true} />; } const fields: IField[] = data ? data.fieldsGetRelations || [] : []; return <RelationForm {...props} fields={fields} />; }; export default Container; ```
/content/code_sandbox/packages/core-ui/src/modules/forms/containers/RelationForm.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
192
```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 /** * Tests if a value is ndarray-like. * * @param v - value to test * @returns boolean indicating if a value is ndarray-like * * @example * var ndarray = require( '@stdlib/ndarray/ctor' ); * * var arr = ndarray( 'generic', [ 0, 0, 0, 0 ], [ 2, 2 ], [ 2, 1 ], 0, 'row-major' ); * * var bool = isndarrayLike( arr ); * // returns true * * bool = isndarrayLike( [] ); * // returns false */ declare function isndarrayLike( v: any ): boolean; // EXPORTS // export = isndarrayLike; ```
/content/code_sandbox/lib/node_modules/@stdlib/assert/is-ndarray-like/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
214
```xml import * as nls from "vscode-nls"; import { basicCheck, createNotFoundMessage } from "../util"; import { IValidation, ValidationCategoryE, ValidationResultT } from "./types"; nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone, })(); const locale = nls.loadMessageBundle(); const label = "Xcode CLI"; async function test(): Promise<ValidationResultT> { const result = await basicCheck({ command: "xcode-select", }); if (result.exists) { return { status: "success", }; } return { status: "failure", comment: createNotFoundMessage(label), }; } const main: IValidation = { label, platform: ["darwin"], description: locale( "XcodeCLICheckDescription", "Required for building and testing RN macOS apps", ), category: ValidationCategoryE.macOS, exec: test, }; export default main; ```
/content/code_sandbox/src/extension/services/validationService/checks/xcodecli.ts
xml
2016-01-20T21:10:07
2024-08-16T15:29:52
vscode-react-native
microsoft/vscode-react-native
2,617
217
```xml export * from './SQLite'; export * from './SQLite.types'; ```
/content/code_sandbox/packages/expo-sqlite/src/legacy/index.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
14
```xml import { Model, model } from 'mongoose'; import { ICover, ICoverDocument, coverSchema } from './definitions/covers'; export interface ICoverModel extends Model<ICoverDocument> { getCover(_id: string): Promise<ICoverDocument>; createCover(doc: ICover): Promise<ICoverDocument>; updateCover(_id: string, doc: ICover): Promise<ICoverDocument>; deleteCover(_id: string): Promise<any>; } export const loadCoverClass = models => { class Cover { public static async getCover(_id: string) { const cover = await models.Covers.findOne({ _id }).lean(); if (!cover) { throw new Error(`Cover not found with id: ${_id}`); } return cover; } public static async updateCover(_id: string, doc: ICover) { await models.Covers.updateOne( { _id }, { $set: { ...doc, modifiedAt: new Date() } } ); return models.Covers.findOne({ _id }).lean(); } public static async deleteCover(_id: string) { return models.Covers.deleteOne({ _id }); } } coverSchema.loadClass(Cover); return coverSchema; }; ```
/content/code_sandbox/packages/plugin-pos-api/src/models/Covers.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
274
```xml <clickhouse> <logger> <level>test</level> </logger> <storage_configuration> <disks> <s3> <type>s3</type> <!-- Use custom S3 endpoint --> <endpoint>path_to_url <access_key_id>minio</access_key_id> <secret_access_key>minio123</secret_access_key> <!-- ClickHouse starts earlier than custom S3 endpoint. Skip access check to avoid fail on start-up --> <skip_access_check>true</skip_access_check> <!-- Avoid extra retries to speed up tests --> <retry_attempts>0</retry_attempts> <skip_access_check>true</skip_access_check> </s3> </disks> <policies> <s3> <volumes> <main> <disk>s3</disk> </main> </volumes> </s3> </policies> </storage_configuration> <merge_tree> <storage_policy>s3</storage_policy> </merge_tree> </clickhouse> ```
/content/code_sandbox/tests/integration/test_s3_aws_sdk_has_slightly_unreliable_behaviour/configs/storage_conf.xml
xml
2016-06-02T08:28:18
2024-08-16T18:39:33
ClickHouse
ClickHouse/ClickHouse
36,234
236
```xml import { zoneDetailMock } from 'stories/mockData'; import { dateToDatetimeString, getCarbonIntensity, getCO2IntensityByMode, getFossilFuelRatio, getProductionCo2Intensity, getRenewableRatio, } from './helpers'; describe('getCO2IntensityByMode', () => { // Tests for consumption describe('consumption', () => { it('returns 100 when the mode is consumption', () => { const actual = getCO2IntensityByMode( { c: { ci: 100 }, p: { ci: 200 } }, 'consumption' ); expect(actual).to.eq(100); }); }); // Tests for production describe('production', () => { it('returns 200 when the mode is production', () => { const actual = getCO2IntensityByMode( { c: { ci: 100 }, p: { ci: 200 } }, 'production' ); expect(actual).to.eq(200); }); }); }); describe('dateToDatetimeString', () => { it('returns the correct datetime string', () => { const actual = dateToDatetimeString(new Date('2023-01-01T12:00:00Z')); expect(actual).to.eq('2023-01-01T12:00:00Z'); }); }); describe('getProductionCo2Intensity', () => { it('returns the correct value when the type is hydro', () => { const actual = getProductionCo2Intensity('hydro', zoneDetailMock); expect(actual).to.eq(10.7); }); it('returns the correct value when the type is battery storage', () => { const actual = getProductionCo2Intensity('battery storage', zoneDetailMock); expect(actual).to.eq(155.11); }); }); describe('getFossilFuelRatio', () => { // Tests for consumption describe('consumption', () => { it('returns 1 when fossil fuel ratio is 0', () => { const actual = getFossilFuelRatio({ c: { fr: 0 }, p: { fr: 1 } }, true); expect(actual).to.eq(1); }); it('returns 0 when fossil fuel ratio is 1', () => { const actual = getFossilFuelRatio({ c: { fr: 1 }, p: { fr: 0 } }, true); expect(actual).to.eq(0); }); it('returns NaN when fossil fuel ratio is null', () => { const actual = getFossilFuelRatio({ c: { fr: null }, p: { fr: null } }, true); expect(actual).to.be.NaN; }); it('returns NaN when fossil fuel ratio is undefined', () => { const actual = getFossilFuelRatio({ c: {}, p: {} }, true); expect(actual).to.be.NaN; }); it('returns 1 - fossil fuel ratio when fossil fuel ratio is between 0 and 1', () => { const actual = getFossilFuelRatio({ c: { fr: 0.3 }, p: { fr: 0.7 } }, true); expect(actual).to.eq(0.7); }); }); // Tests for production describe('production', () => { it('returns 1 when fossil fuel ratio is 0', () => { const actual = getFossilFuelRatio({ c: { fr: 1 }, p: { fr: 0 } }, false); expect(actual).to.eq(1); }); it('returns 0 when fossil fuel ratio is 1', () => { const actual = getFossilFuelRatio({ c: { fr: 0 }, p: { fr: 1 } }, false); expect(actual).to.eq(0); }); it('returns NaN when fossil fuel ratio is null', () => { const actual = getFossilFuelRatio({ c: { fr: null }, p: { fr: null } }, false); expect(actual).to.be.NaN; }); it('returns NaN when fossil fuel ratio is undefined', () => { const actual = getFossilFuelRatio({ c: {}, p: {} }, false); expect(actual).to.be.NaN; }); it('returns 1 - fossil fuel ratio when fossil fuel ratio is between 0 and 1', () => { const actual = getFossilFuelRatio({ c: { fr: 0.7 }, p: { fr: 0.3 } }, false); expect(actual).to.eq(0.7); }); }); }); describe('getCarbonIntensity', () => { // Tests for consumption describe('consumption', () => { it('returns carbon intensity when carbon intensity is not null', () => { const actual = getCarbonIntensity({ c: { ci: 100 }, p: { ci: 200 } }, true); expect(actual).to.eq(100); }); it('returns NaN when carbon intensity is null', () => { const actual = getCarbonIntensity({ c: { fr: null }, p: { fr: null } }, true); expect(actual).to.be.NaN; }); it('returns NaN when carbon intensity is undefined', () => { const actual = getCarbonIntensity({ c: {}, p: {} }, true); expect(actual).to.be.NaN; }); }); // Tests for production describe('production', () => { it('returns carbon intensity when carbon intensity is not null', () => { const actual = getCarbonIntensity({ c: { ci: 100 }, p: { ci: 200 } }, false); expect(actual).to.eq(200); }); it('returns NaN when carbon intensity is null', () => { const actual = getCarbonIntensity({ c: { fr: null }, p: { fr: null } }, false); expect(actual).to.be.NaN; }); it('returns NaN when carbon intensity is undefined', () => { const actual = getCarbonIntensity({ c: {}, p: {} }, false); expect(actual).to.be.NaN; }); }); }); describe('getRenewableRatio', () => { // Tests for consumption describe('consumption', () => { it('returns renewable ratio when renewable ratio is not null', () => { const actual = getRenewableRatio({ c: { rr: 0.5 }, p: { rr: 0.3 } }, true); expect(actual).to.eq(0.5); }); it('returns NaN when renewable ratio is null', () => { const actual = getRenewableRatio({ c: { rr: null }, p: { rr: null } }, true); expect(actual).to.be.NaN; }); it('returns NaN when renewable ratio is undefined', () => { const actual = getRenewableRatio({ c: {}, p: {} }, true); expect(actual).to.be.NaN; }); }); // Tests for production describe('production', () => { it('returns renewable ratio when renewable ratio is not null', () => { const actual = getRenewableRatio({ c: { rr: 0.5 }, p: { rr: 0.3 } }, false); expect(actual).to.eq(0.3); }); it('returns NaN when renewable ratio is null', () => { const actual = getRenewableRatio({ c: { rr: null }, p: { rr: null } }, false); expect(actual).to.be.NaN; }); it('returns NaN when renewable ratio is undefined', () => { const actual = getRenewableRatio({ c: {}, p: {} }, false); expect(actual).to.be.NaN; }); }); }); ```
/content/code_sandbox/web/src/utils/helpers.test.ts
xml
2016-05-21T16:36:17
2024-08-16T17:56:07
electricitymaps-contrib
electricitymaps/electricitymaps-contrib
3,437
1,701
```xml import { IContext } from '../..'; import { IObjectTypeResolver } from '@graphql-tools/utils'; //forumCpMySubscriptionOrders: [ForumSubscriptionOrder!] const subscriptionOrderQueries: IObjectTypeResolver<any, IContext> = { async forumCpMySubscriptionOrders( _, __, { models: { SubscriptionOrder }, cpUser } ) { return SubscriptionOrder.cpMyOrders(cpUser); } }; export default subscriptionOrderQueries; ```
/content/code_sandbox/packages/plugin-forum-api/src/graphql/resolvers/Query/subscriptionOrderQueries.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
99
```xml import {clone, isObject, Timer} from '../utils' describe('Timer', () => { it('should init timer', (done) => { // eslint-disable-next-line @typescript-eslint/no-empty-function let time = 0 const spy = jest.fn() const timer = new Timer(40, spy) expect(timer.remainingTime).toEqual(40) // 1. start the timer timer.resume() // 2. stop the timer after 10ms setTimeout(() => { timer.pause() time = timer.remainingTime }, 10) // 3. check the time has stopped after 15ms setTimeout(() => { expect(timer.remainingTime).toEqual(time) // 4. restart timer timer.resume() setTimeout(() => { // 5. check that the callback has been called expect(spy).toHaveBeenNthCalledWith(1) done() }, time) }, 10) }) }) describe('clone()', () => { it('should clone object', () => { const objA = { a: [1, 3], d: '12', e: {f: '2'}, } const clonedObj = clone(objA) expect(objA !== clonedObj).toBe(true) expect(objA.a !== clonedObj.a).toBe(true) expect(objA.e !== clonedObj.e).toBe(true) expect(objA).toEqual(clonedObj) expect(objA.a).toEqual(clonedObj.a) expect(objA.e).toEqual(clonedObj.e) expect(objA.d).toEqual(clonedObj.d) }) }) describe('isObject()', () => { it.each([ [undefined, false], [null, false], ['', false], [1, false], [[], false], [{}, true], ])('should determine whether %s is an object', (value, expected) => { expect(isObject(value)).toEqual(expected) }) }) ```
/content/code_sandbox/src/tests/utils.spec.ts
xml
2016-04-18T14:42:12
2024-08-13T16:26:17
reapop
LouisBarranqueiro/reapop
1,547
434
```xml // Soft validation to prevent invalid API calls export function isValidName(name: string = ''): boolean { // The name must have at least one different character. // We need to do it this way to still allow project names // with different characters, like other languages, but // prevent API calls like `path_to_url` const blacklist = ':/#?&@%+~'.split(''); return !name.split('').every(c => blacklist.includes(c)); } ```
/content/code_sandbox/packages/cli/src/util/is-valid-name.ts
xml
2016-09-09T01:12:08
2024-08-16T17:39:45
vercel
vercel/vercel
12,545
101
```xml <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="path_to_url" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="24dp" android:layout_marginRight="24dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="22dp" android:layout_gravity="center_horizontal" android:text="@string/locked_accounts_label" android:textSize="20sp" android:textAppearance="@style/TextAppearance.Mega.Subtitle1.Medium"/> <ImageView android:layout_width="80dp" android:layout_height="80dp" android:layout_gravity="center_horizontal" android:layout_marginTop="16dp" android:src="@drawable/ic_looked_accounts"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@string/locked_accounts_text_1" android:textAppearance="@style/TextAppearance.Mega.Subtitle1.Secondary"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@string/locked_accounts_text_2" android:textAppearance="@style/TextAppearance.Mega.Subtitle1.Secondary"/> <Button android:id="@+id/ok_button" android:layout_marginTop="24dp" android:layout_gravity="end" android:text="@string/general_ok" style="?attr/borderlessButtonStyle" /> </LinearLayout> </ScrollView> ```
/content/code_sandbox/app/src/main/res/layout/dialog_locked_accounts.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
412
```xml /* * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ export const MODULE_ID_REWARD = 10; export const REWARD_NO_REDUCTION = 0; export const REWARD_REDUCTION_SEED_REVEAL = 1; export const REWARD_REDUCTION_MAX_PREVOTES = 2; export const REWARD_REDUCTION_NO_ACCOUNT = 3; export const REWARD_REDUCTION_FACTOR_BFT = BigInt(4); export const defaultConfig = { offset: 2160, distance: 3000000, brackets: ['500000000', '400000000', '300000000', '200000000', '100000000'], rewardReductionFactorBFT: REWARD_REDUCTION_FACTOR_BFT.toString(), }; export const CONTEXT_STORE_KEY_BLOCK_REWARD = 'CONTEXT_STORE_KEY_BLOCK_REWARD'; export const CONTEXT_STORE_KEY_BLOCK_REDUCTION = 'CONTEXT_STORE_KEY_BLOCK_REDUCTION'; ```
/content/code_sandbox/framework/src/modules/reward/constants.ts
xml
2016-02-01T21:45:35
2024-08-15T19:16:48
lisk-sdk
LiskArchive/lisk-sdk
2,721
261
```xml import React from 'react'; import { render } from '@testing-library/react'; import Icon from '../index'; const Right = (props) => ( <svg viewBox="0 0 32 24" fill="currentColor" stroke="currentColor" width="1em" height="1em" {...props} > <path d="M1 12.376l8.8 9.114L30.431 1.568" stroke="currentColor" strokeWidth={2.6} fill="none" /> </svg> ); describe('Icon', () => { it('renders Icons using iconfont', () => { const MyIcon = Icon.createFromIconfont('//lf1-cdn-tos.bytegoofy.com/obj/iconpark/svg_20337_14.627ee457cf7594fbbce6d5e14b8c29ef.js'); const wrapper = render( <> <MyIcon type="home" /> <MyIcon type="user" /> </>, ); expect(wrapper.asFragment()).toMatchSnapshot(); }); it('renders Icons using svg component', () => { const wrapper = render(<Icon size="lg" theme="primary" component={Right} />); expect(wrapper.asFragment()).toMatchSnapshot(); }); }); ```
/content/code_sandbox/packages/zarm/src/icon/__tests__/index.test.tsx
xml
2016-07-13T11:45:37
2024-08-12T19:23:48
zarm
ZhongAnTech/zarm
1,707
284
```xml import { Component } from 'react'; import { NumberProp } from '../../lib/extract/types'; import { warnUnimplementedFilter } from '../../lib/util'; export interface FeDistantLightProps { azimuth?: NumberProp; elevation?: NumberProp; } export default class FeDistantLight extends Component<FeDistantLightProps> { static displayName = 'FeDistantLight'; static defaultProps = {}; render() { warnUnimplementedFilter(); return null; } } ```
/content/code_sandbox/src/elements/filters/FeDistantLight.tsx
xml
2016-01-17T14:29:21
2024-08-16T13:35:44
react-native-svg
software-mansion/react-native-svg
7,397
103
```xml import { Typed } from "../typed.js"; import { Coder } from "./abstract-coder.js"; import type { BigNumberish } from "../../utils/index.js"; import type { Reader, Writer } from "./abstract-coder.js"; /** * @_ignore */ export declare class NumberCoder extends Coder { readonly size: number; readonly signed: boolean; constructor(size: number, signed: boolean, localName: string); defaultValue(): number; encode(writer: Writer, _value: BigNumberish | Typed): number; decode(reader: Reader): any; } //# sourceMappingURL=number.d.ts.map ```
/content/code_sandbox/lib.commonjs/abi/coders/number.d.ts
xml
2016-07-16T04:35:37
2024-08-16T13:37:46
ethers.js
ethers-io/ethers.js
7,843
128
```xml <?xml version="1.0" encoding="UTF-8"?> <module external.linked.project.id=":base" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4"> <component name="FacetManager"> <facet type="android-gradle" name="Android-Gradle"> <configuration> <option name="GRADLE_PROJECT_PATH" value=":base" /> </configuration> </facet> <facet type="android" name="Android"> <configuration> <option name="SELECTED_BUILD_VARIANT" value="debug" /> <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" /> <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" /> <afterSyncTasks> <task>generateDebugSources</task> </afterSyncTasks> <option name="ALLOW_USER_CONFIGURATION" value="false" /> <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" /> <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" /> <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" /> <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" /> <option name="PROJECT_TYPE" value="5" /> </configuration> </facet> </component> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7"> <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" /> <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" /> <exclude-output /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/test/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/attr" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/check-manifest" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes-jar" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/feature-split" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/intermediate-jars" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaPrecompile" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/packaged-aidl" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/packagedAssets" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/packaged_res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/public_res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/shaders" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/splits-support" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" /> <excludeFolder url="file://$MODULE_DIR$/build/outputs" /> <excludeFolder url="file://$MODULE_DIR$/build/tmp" /> </content> <orderEntry type="jdk" jdkName="Android API 28 Platform" jdkType="Android SDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Gradle: com.android.support:versionedparcelable-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:print-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:documentfile-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:asynclayoutinflater-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:appcompat-v7-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: android.arch.lifecycle:viewmodel-1.1.1" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:transition-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:support-core-ui-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:animated-vector-drawable-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:customview-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:cursoradapter-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:cardview-v7-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:support-vector-drawable-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:support-compat-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:drawerlayout-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: android.arch.core:common:1.1.1@jar" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:design-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:support-fragment-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: android.arch.core:runtime-1.1.1" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:recyclerview-v7-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:interpolator-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:support-annotations:28.0.0-alpha3@jar" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:coordinatorlayout-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:slidingpanelayout-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:collections:28.0.0-alpha3@jar" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:support-core-utils-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:loader-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: android.arch.lifecycle:common:1.1.1@jar" level="project" /> <orderEntry type="library" name="Gradle: android.arch.lifecycle:livedata-core-1.1.1" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:localbroadcastmanager-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: android.arch.lifecycle:runtime-1.1.1" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:viewpager-28.0.0-alpha3" level="project" /> <orderEntry type="library" name="Gradle: com.android.support:swiperefreshlayout-28.0.0-alpha3" level="project" /> </component> </module> ```
/content/code_sandbox/Android/AndroidInstantApps/base/base.iml
xml
2016-05-02T05:43:21
2024-08-16T06:51:39
journaldev
WebJournal/journaldev
1,314
3,521
```xml export { default } from "./Quantizer" ```
/content/code_sandbox/app/src/quantizer/index.ts
xml
2016-03-06T15:19:53
2024-08-15T14:27:10
signal
ryohey/signal
1,238
10
```xml import WorkerMessageBroker from 'proton-pass-extension/app/worker/channel'; import store from 'proton-pass-extension/app/worker/store'; import { validateFormCredentials } from 'proton-pass-extension/lib/utils/form-entry'; import { c } from 'ttag'; import { itemBuilder } from '@proton/pass/lib/items/item.builder'; import { hasUserIdentifier } from '@proton/pass/lib/items/item.predicates'; import { intoLoginItemPreview } from '@proton/pass/lib/items/item.utils'; import { itemCreationIntent, itemCreationSuccess, itemEditIntent, itemEditSuccess } from '@proton/pass/store/actions'; import { selectAutosaveCandidate, selectAutosaveVault, selectFeatureFlag, selectItem, selectWritableVaults, } from '@proton/pass/store/selectors'; import type { AutosavePrompt, FormEntry } from '@proton/pass/types'; import { AutosaveMode, WorkerMessageType } from '@proton/pass/types'; import { PassFeature } from '@proton/pass/types/api/features'; import { prop } from '@proton/pass/utils/fp/lens'; import { deobfuscate } from '@proton/pass/utils/obfuscate/xor'; import { uniqueId } from '@proton/pass/utils/string/unique-id'; import { getEpoch } from '@proton/pass/utils/time/epoch'; import { isValidURL } from '@proton/pass/utils/url/is-valid-url'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; export const createAutoSaveService = () => { const resolve = ({ type, data, domain, subdomain }: FormEntry): AutosavePrompt => { /* If credentials are not valid for the form type : exit early */ if (!validateFormCredentials(data, { type, partial: false })) return { shouldPrompt: false }; const { userIdentifier, password } = data; const state = store.getState(); const shareIds = selectWritableVaults(store.getState()).map(prop('shareId')); if (type === 'register') { const candidates = selectAutosaveCandidate({ domain, subdomain, userIdentifier: '', shareIds })(state); const pwMatch = candidates.filter((item) => deobfuscate(item.data.content.password) === password); const fullMatch = Boolean(userIdentifier) && pwMatch.some(hasUserIdentifier(userIdentifier)); /* The credentials may have been saved during the password-autosuggest autosave * sequence - as such ensure we don't have an exact username/password match */ if (fullMatch) return { shouldPrompt: false }; if (pwMatch.length > 0) { return { shouldPrompt: true, data: { type: AutosaveMode.UPDATE, candidates: pwMatch.map(intoLoginItemPreview) }, }; } else return { shouldPrompt: true, data: { type: AutosaveMode.NEW } }; } /* If no login items found for the current domain & the * current username - prompt for autosaving a new entry */ const candidates = selectAutosaveCandidate({ domain, subdomain, userIdentifier, shareIds })(state); if (candidates.length === 0) return { shouldPrompt: true, data: { type: AutosaveMode.NEW } }; /* If we cannot find an entry which also matches the current submission's * password then we should prompt for update */ const match = candidates.some((item) => deobfuscate(item.data.content.password) === password); return match ? { shouldPrompt: false } : { shouldPrompt: true, data: { type: AutosaveMode.UPDATE, candidates: candidates.map(intoLoginItemPreview) }, }; }; WorkerMessageBroker.registerMessage(WorkerMessageType.AUTOSAVE_REQUEST, async ({ payload }) => { const state = store.getState(); const { valid, url } = isValidURL(payload.domain); if (payload.type === AutosaveMode.NEW) { const selectedVault = selectAutosaveVault(state); const item = itemBuilder('login'); item.get('metadata') .set('name', payload.name) .set('note', c('Info').t`Autosaved on ${payload.domain}`); item.get('content') .set('password', payload.password) .set('urls', valid ? [url] : []) .set('passkeys', payload.passkey ? [payload.passkey] : []); const usernameSplitEnabled = selectFeatureFlag(PassFeature.PassUsernameSplit)(state); // TODO: migrate to use Rust's email validation if (validateEmailAddress(payload.userIdentifier) || !usernameSplitEnabled) { item.get('content').set('itemEmail', payload.userIdentifier); } else { item.get('content').set('itemUsername', payload.userIdentifier); } return new Promise<boolean>((resolve) => store.dispatch( itemCreationIntent( { ...item.data, createTime: getEpoch(), extraData: { withAlias: false }, optimisticId: uniqueId(), shareId: selectedVault.shareId, }, (action) => resolve(itemCreationSuccess.match(action)) ) ) ); } if (payload.type === AutosaveMode.UPDATE) { const { shareId, itemId } = payload; const currentItem = selectItem<'login'>(shareId, itemId)(state); if (!currentItem) throw new Error(c('Error').t`Item does not exist`); const item = itemBuilder('login', currentItem.data); const { passkey } = payload; item.get('metadata').set('name', payload.name); item.get('content') .set('password', (password) => (passkey ? password : payload.password)) .set('urls', (urls) => Array.from(new Set(urls.concat(valid ? [url] : [])))) .set('passkeys', (passkeys) => (passkey ? [...passkeys, passkey] : passkeys)); // TODO: migrate to use Rust's email validation const usernameSplitEnabled = selectFeatureFlag(PassFeature.PassUsernameSplit)(state); const isEmail = usernameSplitEnabled && validateEmailAddress(payload.userIdentifier); const userIdKey = isEmail ? 'itemEmail' : 'itemUsername'; item.get('content').set(userIdKey, (value) => (passkey ? value : payload.userIdentifier)); return new Promise<boolean>((resolve) => store.dispatch( itemEditIntent( { ...item.data, lastRevision: currentItem.revision, itemId, shareId, }, (action) => resolve(itemEditSuccess.match(action)) ) ) ); } return false; }); return { resolve }; }; export type AutoSaveService = ReturnType<typeof createAutoSaveService>; ```
/content/code_sandbox/applications/pass-extension/src/app/worker/services/autosave.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
1,437
```xml <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>FloatingActionButtonSettingsForm</class> <widget class="QWidget" name="FloatingActionButtonSettingsForm"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>599</width> <height>418</height> </rect> </property> <property name="windowTitle"> <string>Form</string> </property> <widget class="QWidget" name="formLayoutWidget"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>234</width> <height>391</height> </rect> </property> <layout class="QFormLayout" name="formLayout"> <property name="formAlignment"> <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set> </property> <item row="0" column="0"> <widget class="QLabel" name="disabledLabel"> <property name="text"> <string>Disabled</string> </property> </widget> </item> <item row="0" column="1"> <widget class="QCheckBox" name="disabledCheckBox"/> </item> <item row="1" column="0"> <widget class="QLabel" name="cornerLabel"> <property name="text"> <string>Corner</string> </property> </widget> </item> <item row="1" column="1"> <widget class="QComboBox" name="cornerComboBox"> <item> <property name="text"> <string>Top Left</string> </property> </item> <item> <property name="text"> <string>Top Right</string> </property> </item> <item> <property name="text"> <string>Bottom Left</string> </property> </item> <item> <property name="text"> <string>Bottom Right</string> </property> </item> </widget> </item> <item row="2" column="0"> <widget class="QLabel" name="buttonRoleLabel"> <property name="text"> <string>Button role</string> </property> </widget> </item> <item row="2" column="1"> <widget class="QComboBox" name="buttonRoleComboBox"> <item> <property name="text"> <string>Default</string> </property> </item> <item> <property name="text"> <string>Primary</string> </property> </item> <item> <property name="text"> <string>Secondary</string> </property> </item> </widget> </item> <item row="3" column="0"> <widget class="QLabel" name="horizontalOffsetLabel"> <property name="text"> <string>Horizontal offset</string> </property> </widget> </item> <item row="3" column="1"> <widget class="QSpinBox" name="horizontalOffsetSpinBox"/> </item> <item row="4" column="0"> <widget class="QLabel" name="verticalOffsetLabel"> <property name="text"> <string>Vertical offset</string> </property> </widget> </item> <item row="4" column="1"> <widget class="QSpinBox" name="verticalOffsetSpinBox"/> </item> <item row="5" column="0"> <widget class="QLabel" name="miniLabel"> <property name="text"> <string>Mini</string> </property> </widget> </item> <item row="5" column="1"> <widget class="QCheckBox" name="miniCheckBox"/> </item> <item row="6" column="0"> <widget class="QLabel" name="rippleStyleLabel"> <property name="text"> <string>Ripple style</string> </property> </widget> </item> <item row="6" column="1"> <widget class="QComboBox" name="rippleStyleComboBox"> <item> <property name="text"> <string>Centered</string> </property> </item> <item> <property name="text"> <string>Positioned</string> </property> </item> <item> <property name="text"> <string>No Ripple</string> </property> </item> </widget> </item> <item row="7" column="0"> <widget class="QLabel" name="useThemeColorsLabel"> <property name="text"> <string>Use theme colors</string> </property> </widget> </item> <item row="7" column="1"> <widget class="QCheckBox" name="useThemeColorsCheckBox"/> </item> <item row="8" column="0"> <widget class="QLabel" name="backgroundColorLabel"> <property name="text"> <string>Background color</string> </property> </widget> </item> <item row="8" column="1"> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QLineEdit" name="backgroundColorLineEdit"> <property name="enabled"> <bool>false</bool> </property> </widget> </item> <item> <widget class="QToolButton" name="backgroundColorToolButton"> <property name="text"> <string>...</string> </property> </widget> </item> </layout> </item> <item row="9" column="0"> <widget class="QLabel" name="foregroundColorLabel"> <property name="text"> <string>Foreground color</string> </property> </widget> </item> <item row="10" column="0"> <widget class="QLabel" name="disabledBgColorLabel"> <property name="text"> <string>Disabled bg color</string> </property> </widget> </item> <item row="11" column="0"> <widget class="QLabel" name="disabledFgColorLabel"> <property name="text"> <string>Disabled fg color</string> </property> </widget> </item> <item row="9" column="1"> <layout class="QHBoxLayout" name="horizontalLayout_2"> <item> <widget class="QLineEdit" name="foregroundColorLineEdit"> <property name="enabled"> <bool>false</bool> </property> </widget> </item> <item> <widget class="QToolButton" name="foregroundColorToolButton"> <property name="text"> <string>...</string> </property> </widget> </item> </layout> </item> <item row="10" column="1"> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> <widget class="QLineEdit" name="disabledBgColorLineEdit"> <property name="enabled"> <bool>false</bool> </property> </widget> </item> <item> <widget class="QToolButton" name="disabledBgColorToolButton"> <property name="text"> <string>...</string> </property> </widget> </item> </layout> </item> <item row="11" column="1"> <layout class="QHBoxLayout" name="horizontalLayout_4"> <item> <widget class="QLineEdit" name="disabledFgColorLineEdit"> <property name="enabled"> <bool>false</bool> </property> </widget> </item> <item> <widget class="QToolButton" name="disabledFgColorToolButton"> <property name="text"> <string>...</string> </property> </widget> </item> </layout> </item> </layout> </widget> </widget> <resources/> <connections/> </ui> ```
/content/code_sandbox/examples/fabsettingsform.ui
xml
2016-03-18T08:58:04
2024-08-16T14:50:20
qt-material-widgets
laserpants/qt-material-widgets
2,898
1,897
```xml <vector android:height="48dp" android:viewportHeight="128" android:viewportWidth="128" android:width="48dp" xmlns:android="path_to_url"> <path android:fillColor="#bacfef" android:pathData="m38,28v88h20v4h12v-4h20v-88z" /> <path android:fillColor="#859dbf" android:pathData="M38,28h52v4h-52zM38,56h52v4h-52zM38,84h52v4h-52z"/> <path android:fillColor="#6f829f" android:pathData="M50,24h8v96h-8zM70,24h8v96h-8zM90,24h8v88h-8zM30,24h8v88h-8z"/> <path android:fillColor="#acb4c2" android:pathData="m26,20v8,20 8,20 8,28 4h24v-12h-20v-20h68v20h-20v12h24v-4,-8 -84h-4zM30,28h68v20h-68zM30,56h68v20h-68z"/> <path android:fillColor="#b9c0c9" android:pathData="M34,12h60v8h-60z"/> </vector> ```
/content/code_sandbox/app/src/main/res/drawable/ic_building_office.xml
xml
2016-07-02T10:44:04
2024-08-16T18:55:54
StreetComplete
streetcomplete/StreetComplete
3,781
332
```xml import { colorToFunctionalRgbaString, IntColor, mapRange, readIntColorString, } from '@tweakpane/core'; import {presetToState, stateToPreset} from 'ts/preset'; import {Pane} from 'tweakpane'; import {Sketch} from '../sketch.js'; import {Environment} from '../sketch.js'; import {selectContainer} from '../util.js'; const COLORS = { dark: 'hsl(230deg, 7%, 10%)', light: 'hsl(230deg, 7%, 90%)', }; export function initIndex() { const ENV: Environment = { amp: {x: 0.1, y: 0.5}, color: 'hsl(0, 0, 0)', freq: { x: 17, y: 6.3, }, maxSize: 5, range: 0, spacing: 24, speed: 0.02, title: 'Tweakpane', }; const PRESETS: {[key: string]: Environment} = { atmos: { amp: {x: 0.1, y: 0.53}, color: 'hsl(220, 0%, 70%)', freq: {x: 45, y: 16}, maxSize: 128, range: 0.77, spacing: 24, speed: 0.02, title: 'Tweakpane', }, bubble: { amp: {x: 0.3, y: 0.51}, color: 'hsl(182, 15%, 45%)', freq: {x: 64, y: 32}, maxSize: 128, range: 0.5, spacing: 48, speed: 0.02, title: 'Tweakpane', }, cloud: { amp: {x: 0.07, y: 0}, color: 'hsl(45, 12%, 80%)', freq: {x: 22.25, y: 0}, maxSize: 105, range: 0.63, spacing: 48, speed: 0.02, title: 'Tweakpane', }, }; const HIDDEN_PARAMS = { presetId: '', presetJson: '', }; const sketchElem = document.querySelector('.pageHeader_sketchContainer'); if (!sketchElem) { return; } const sketch = new Sketch(sketchElem, ENV); const updateBg = () => { const headerElem: HTMLElement | null = document.querySelector('.pageHeader'); if (!headerElem) { return; } const [h, s, l] = readIntColorString(ENV.color).getComponents('hsl'); const bg = new IntColor([h + 30, s, l < 50 ? l - 4 : l + 5], 'hsl'); headerElem.style.backgroundColor = colorToFunctionalRgbaString(bg); }; const markerToFnMap: { [key: string]: (container: HTMLElement) => void; } = { index: (container) => { const pane = new Pane({ container: container, title: 'Parameters', }); pane.addBinding(ENV, 'color').on('change', updateBg); pane.addBinding(ENV, 'title').on('change', (ev) => { const titleElem = document.querySelector('.pageHeader_title'); if (titleElem) { titleElem.textContent = ev.value; } }); const tab = pane.addTab({ pages: [{title: 'Layout'}, {title: 'Presets'}], }); const p0 = tab.pages[0]; p0.addBinding(ENV, 'spacing', { max: 48, min: 24, }); p0.addBinding(ENV, 'range', { max: 1, min: 0, }); p0.addBinding(ENV, 'maxSize', { max: 128, min: 5, }); p0.addBinding(ENV, 'freq', { x: {max: 64, min: 0}, y: {max: 32, min: 0}, }); p0.addBinding(ENV, 'amp', { x: {max: 0.3, min: 0}, y: {max: 1, min: 0}, }); const p1 = tab.pages[1]; p1.addBinding(HIDDEN_PARAMS, 'presetId', { label: 'preset', options: { 'Import...': '', Atmos: 'atmos', Bubble: 'bubble', Cloud: 'cloud', }, }).on('change', (ev) => { const preset = PRESETS[ev.value]; if (preset) { HIDDEN_PARAMS.presetId = ''; pane.importState(presetToState(pane.exportState(), preset as any)); } }); p1.addBinding(HIDDEN_PARAMS, 'presetJson', { label: 'data', multiline: true, readonly: true, rows: 4, }); pane.on('change', () => { sketch.reset(); const preset = stateToPreset(pane.exportState()); delete preset.presetJson; HIDDEN_PARAMS.presetJson = JSON.stringify(preset, null, 2); }); pane.on('fold', () => { sketch.resize(); setTimeout(() => { sketch.resize(); }, 200); }); let t = -0.2; const timerId = setInterval(() => { t = Math.min(t + 0.02, 1); if (t >= 1) { clearInterval(timerId); } const tz = Math.max(t, 0); const et = tz < 0.5 ? 2 * tz * tz : 1 - 2 * (1 - tz) * (1 - tz); ENV.range = mapRange(et, 0, 1, 0, 0.8); ENV.maxSize = mapRange(et, 0, 1, 5, 70); pane.refresh(); }, 1000 / 30); const mm = window.matchMedia('(prefers-color-scheme: dark)'); const applyScheme = () => { ENV.color = mm.matches ? COLORS.dark : COLORS.light; sketch.resize(); pane.refresh(); }; mm.addEventListener('change', applyScheme); applyScheme(); }, }; Object.keys(markerToFnMap).forEach((marker) => { const initFn = markerToFnMap[marker]; const container = selectContainer(marker); initFn(container); }); } ```
/content/code_sandbox/packages/tweakpane/src/doc/ts/route/index.ts
xml
2016-05-10T15:45:13
2024-08-16T19:57:27
tweakpane
cocopon/tweakpane
3,480
1,566
```xml /* eslint-disable testing-library/no-node-access */ import React from 'react'; import sinon from 'sinon'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { mockTreeData } from '@test/mocks/data-mock'; import { testStandardProps } from '@test/utils'; import CheckTree from '../index'; const data = mockTreeData([['Master', 'tester0', ['tester1', 'tester2', 'tester3']], 'disabled']); describe('CheckTree', () => { testStandardProps(<CheckTree data={data} />); it('Should set a height for the Tree', () => { const { rerender } = render(<CheckTree data={data} />); expect(screen.getByRole('tree')).to.have.style('height', '360px'); rerender(<CheckTree data={data} height={100} />); expect(screen.getByRole('tree')).to.have.style('height', '100px'); }); it('Should set a height for the Tree with virtualized', () => { render(<CheckTree data={data} virtualized height={100} />); expect(screen.getByRole('tree').querySelector('.rs-check-tree-virt-list')).to.have.style( 'height', '100px' ); }); it('Should render a multi-selectable tree', () => { const { container } = render(<CheckTree data={data} />); expect(container.firstChild).to.have.class('rs-check-tree'); expect(screen.getByRole('tree')).to.have.attr('aria-multiselectable', 'true'); }); it('Should show indent line', () => { render(<CheckTree data={data} showIndentLine />); expect(screen.queryAllByTestId('indent-line')).to.have.length(2); }); it('Should call `onSelectItem` callback with the selected item and the full path', () => { const onSelectItem = sinon.spy(); render( <CheckTree data={data} expandItemValues={['Master', 'tester1']} onSelectItem={onSelectItem} /> ); fireEvent.click(screen.getByRole('checkbox', { name: 'tester2' })); expect(onSelectItem).to.have.been.calledWith(sinon.match({ value: 'tester2' }), [ sinon.match({ value: 'Master' }), sinon.match({ value: 'tester1' }), sinon.match({ value: 'tester2' }) ]); }); it('Should call `onSelect` callback', () => { const onSelect = sinon.spy(); render(<CheckTree data={data} onSelect={onSelect} />); fireEvent.click(screen.getByRole('checkbox', { name: 'Master' })); expect(onSelect).to.have.been.calledWith(sinon.match({ value: 'Master' })); }); it('Should not call `onSelect` callback when the item is disabled', () => { const onSelect = sinon.spy(); render(<CheckTree data={data} onSelect={onSelect} disabledItemValues={['Master']} />); fireEvent.click(screen.getByRole('checkbox', { name: 'Master' })); expect(onSelect).to.not.have.been.called; }); it('Should async load children nodes', async () => { const data = [{ label: 'async', value: 'async', children: [] }]; const fetchNodes = () => { return new Promise<any>(resolve => { setTimeout(() => resolve([{ label: 'children', value: 'children' }]), 500); }); }; render( <CheckTree data={data} value={['Master']} cascade={false} defaultExpandAll getChildren={fetchNodes} /> ); fireEvent.click(screen.getByRole('button', { name: 'Expand async' })); expect(screen.getByRole('button', { name: 'Collapse async' })).to.have.attribute('aria-busy'); await waitFor(() => { expect(screen.getByRole('treeitem', { name: 'children' })).to.exist; expect(screen.getByRole('button', { name: 'Collapse async' })).to.not.have.attribute( 'aria-busy' ); }); }); it('Should all nodes be checked', () => { // Test data comes from: path_to_url const data = [ { label: 'label_1', value: 'value_1', children: [ { label: 'label_2', value: 'value_2', children: [ { label: 'label_3', value: 'value_3', children: [ { label: 'label_4', value: 'value_4', children: [ { label: 'label_5', value: 'value_5' } ] } ] } ] } ] } ]; render(<CheckTree data={data} value={['value_5']} defaultExpandAll />); screen.getAllByRole('treeitem').forEach(item => { expect(item).to.have.attribute('aria-checked', 'true'); }); }); describe('Disabled/Uncheckable items', () => { it('Should render the item as disabled', () => { const onSelect = sinon.spy(); render(<CheckTree data={data} disabledItemValues={['Master']} onSelect={onSelect} />); expect(screen.getByRole('treeitem', { name: 'Master' })).to.have.attribute('aria-disabled'); fireEvent.click(screen.getByRole('checkbox', { name: 'Master' })); expect(onSelect).to.not.have.been.called; }); it('Should not render the checkbox when the item is uncheckable', () => { const onSelect = sinon.spy(); render(<CheckTree data={data} onSelect={onSelect} uncheckableItemValues={['Master']} />); expect(screen.queryByRole('checkbox', { name: 'Master' })).to.not.exist; }); }); describe('Accessibility - Keyboard interactions', () => { it('Should focus the next item when pressing the down arrow key', () => { render(<CheckTree data={data} />); const tree = screen.getByRole('tree'); const treeItems = screen.getAllByRole('treeitem'); fireEvent.keyDown(tree, { key: 'ArrowDown' }); expect(treeItems[0]).to.have.focus; }); it('Should focus the previous item when pressing the up arrow key', () => { render(<CheckTree data={data} defaultExpandAll />); const tree = screen.getByRole('tree'); const treeItems = screen.getAllByRole('treeitem'); fireEvent.keyDown(tree, { key: 'ArrowUp' }); fireEvent.keyDown(tree, { key: 'ArrowUp' }); expect(treeItems[treeItems.length - 1]).to.have.focus; }); it('Should expand the item when pressing the right arrow key', () => { render(<CheckTree data={data} />); const treeItems = screen.getAllByRole('treeitem'); fireEvent.click(screen.getAllByRole('checkbox')[0]); fireEvent.keyDown(treeItems[0], { key: 'ArrowRight' }); expect(treeItems[0]).to.have.attribute('aria-expanded', 'true'); }); it('Should collapse the item when pressing the left arrow key', () => { render(<CheckTree data={data} defaultExpandAll />); const treeItems = screen.getAllByRole('treeitem'); fireEvent.click(screen.getAllByRole('checkbox')[0]); fireEvent.keyDown(treeItems[0], { key: 'ArrowLeft' }); expect(treeItems[0]).to.have.attribute('aria-expanded', 'false'); }); it('Should check the item when pressing the enter key', () => { render(<CheckTree data={data} />); const tree = screen.getByRole('tree'); const treeItems = screen.getAllByRole('treeitem'); fireEvent.keyDown(tree, { key: 'ArrowDown' }); fireEvent.keyDown(tree, { key: 'Enter' }); expect(treeItems[0]).to.have.attribute('aria-checked', 'true'); }); describe('With virtualized', () => { it('Should focus the next item when pressing the down arrow key', () => { render(<CheckTree data={data} virtualized defaultExpandAll />); const tree = screen.getByRole('tree'); fireEvent.keyDown(tree, { key: 'ArrowDown' }); expect(screen.getAllByRole('treeitem')[0]).to.have.focus; }); it('Should focus the previous item when pressing the up arrow key', () => { render(<CheckTree data={data} virtualized defaultExpandAll />); const tree = screen.getByRole('tree'); fireEvent.keyDown(tree, { key: 'ArrowUp' }); fireEvent.keyDown(tree, { key: 'ArrowUp' }); const treeItems = screen.getAllByRole('treeitem'); expect(treeItems[treeItems.length - 1]).to.have.focus; }); it('Should expand the item when pressing the right arrow key', () => { render(<CheckTree data={data} virtualized defaultExpandAll />); fireEvent.click(screen.getAllByRole('checkbox')[0]); fireEvent.keyDown(screen.getAllByRole('treeitem')[0], { key: 'ArrowRight' }); expect(screen.getAllByRole('treeitem')[0]).to.have.attribute('aria-expanded', 'true'); }); it('Should collapse the item when pressing the left arrow key', () => { render(<CheckTree data={data} virtualized defaultExpandAll />); fireEvent.click(screen.getAllByRole('checkbox')[0]); fireEvent.keyDown(screen.getAllByRole('treeitem')[0], { key: 'ArrowLeft' }); expect(screen.getAllByRole('treeitem')[0]).to.have.attribute('aria-expanded', 'false'); }); it('Should check the item when pressing the enter key', () => { render(<CheckTree data={data} virtualized defaultExpandAll />); const tree = screen.getByRole('tree'); fireEvent.keyDown(tree, { key: 'ArrowDown' }); fireEvent.keyDown(tree, { key: 'Enter' }); expect(screen.getAllByRole('treeitem')[0]).to.have.attribute('aria-checked', 'true'); }); }); }); describe('Scroll Shadows', () => { it('Should hava a scroll shadow', () => { render(<CheckTree data={data} scrollShadow height={100} />); expect(screen.getByRole('tree')).to.have.class('rs-scroll-view-shadow'); }); it('Should hava a scroll shadow with virtualized', () => { render(<CheckTree data={data} scrollShadow height={100} virtualized />); expect(screen.getByRole('tree')).to.not.have.class('rs-scroll-view-shadow'); expect(screen.getByTestId('scroll-view')).to.have.class('rs-scroll-view-shadow'); }); }); describe('Controlled and uncontrolled value', () => { it('Should checked the item passed through the `value` property', async () => { render(<CheckTree data={data} value={['tester2']} defaultExpandAll />); expect(screen.getByRole('treeitem', { name: 'tester2' })).to.have.attribute( 'aria-checked', 'true' ); }); it('Should checked the item passed through the `defaultValue` property', () => { render(<CheckTree data={data} defaultValue={['tester2']} defaultExpandAll />); expect(screen.getByRole('treeitem', { name: 'tester2' })).to.have.attribute( 'aria-checked', 'true' ); }); it('Should call `onChange` when the value changes', () => { const onChange = sinon.spy(); render(<CheckTree data={data} onChange={onChange} defaultExpandAll />); fireEvent.click(screen.getByRole('checkbox', { name: 'tester2' })); expect(onChange).to.have.been.calledWith(['tester2']); }); it('Should be controlled and render the updated value', () => { const App = () => { const [value, setValue] = React.useState(['tester0']); return ( <> <CheckTree data={data} value={value} defaultExpandAll /> <button onClick={() => setValue(['tester1'])}>Click</button> </> ); }; render(<App />); expect(screen.getByRole('treeitem', { name: 'tester0' })).to.have.attribute( 'aria-checked', 'true' ); expect(screen.getByRole('treeitem', { name: 'tester1' })).to.have.attribute( 'aria-checked', 'false' ); fireEvent.click(screen.getByRole('button', { name: 'Click' })); expect(screen.getByRole('treeitem', { name: 'tester0' })).to.have.attribute( 'aria-checked', 'false' ); expect(screen.getByRole('treeitem', { name: 'tester1' })).to.have.attribute( 'aria-checked', 'true' ); }); it('Should be uncontrolled and render default value', () => { const App = () => { const [value, setValue] = React.useState(['tester0']); return ( <> <CheckTree data={data} defaultValue={value} defaultExpandAll /> <button onClick={() => setValue(['tester1'])}>Click</button> </> ); }; render(<App />); expect(screen.getByRole('treeitem', { name: 'tester0' })).to.have.attribute( 'aria-checked', 'true' ); expect(screen.getByRole('treeitem', { name: 'tester1' })).to.have.attribute( 'aria-checked', 'false' ); fireEvent.click(screen.getByRole('button', { name: 'Click' })); expect(screen.getByRole('treeitem', { name: 'tester0' })).to.have.attribute( 'aria-checked', 'true' ); expect(screen.getByRole('treeitem', { name: 'tester1' })).to.have.attribute( 'aria-checked', 'false' ); }); }); }); ```
/content/code_sandbox/src/CheckTree/test/CheckTreeSpec.tsx
xml
2016-06-06T02:27:46
2024-08-16T16:41:54
rsuite
rsuite/rsuite
8,263
3,036
```xml import type { TreeNode } from '../types'; export function findNodeOfTree(data, check) { const findNode = (nodes: readonly TreeNode[] = []) => { for (let i = 0; i < nodes.length; i += 1) { const item = nodes[i]; if (Array.isArray(item.children)) { const node = findNode(item.children); if (node) { return node; } } if (check(item)) { return item; } } return undefined; }; return findNode(data); } ```
/content/code_sandbox/src/internals/Tree/utils/findNodeOfTree.ts
xml
2016-06-06T02:27:46
2024-08-16T16:41:54
rsuite
rsuite/rsuite
8,263
123
```xml import { ExpoConfig } from '@expo/config-types'; import { AndroidManifest } from './Manifest'; export type IntentFilterProps = { actions: string[]; categories: string[]; data: { scheme: string; host?: string; }[]; }; export declare const withScheme: import("..").ConfigPlugin; export declare function getScheme(config: { scheme?: string | string[]; }): string[]; export declare function setScheme(config: Pick<ExpoConfig, 'scheme' | 'android'>, androidManifest: AndroidManifest): AndroidManifest; export declare function getSchemesFromManifest(androidManifest: AndroidManifest, requestedHost?: string | null): string[]; export declare function ensureManifestHasValidIntentFilter(androidManifest: AndroidManifest): boolean; export declare function hasScheme(scheme: string, androidManifest: AndroidManifest): boolean; export declare function appendScheme(scheme: string, androidManifest: AndroidManifest): AndroidManifest; export declare function removeScheme(scheme: string, androidManifest: AndroidManifest): AndroidManifest; ```
/content/code_sandbox/packages/@expo/config-plugins/build/android/Scheme.d.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
211
```xml import { StreamEntry, pino } from '../../pino' import { join } from 'node:path' import { tmpdir } from 'node:os' import pinoPretty from 'pino-pretty' const destination = join( tmpdir(), '_' + Math.random().toString(36).substr(2, 9) ) // Single const transport = pino.transport({ target: 'pino-pretty', options: { some: 'options for', the: 'transport' } }) const logger = pino(transport) logger.setBindings({ some: 'bindings' }) logger.info('test2') logger.flush() const transport2 = pino.transport({ target: 'pino-pretty', }) const logger2 = pino(transport2) logger2.info('test2') // Multiple const transports = pino.transport({targets: [ { level: 'info', target: 'pino-pretty', options: { some: 'options for', the: 'transport' } }, { level: 'trace', target: 'pino/file', options: { destination } } ]}) const loggerMulti = pino(transports) loggerMulti.info('test2') // custom levels const customLevels = { debug : 1, info : 2, network : 3, error : 4, }; type CustomLevels = keyof typeof customLevels; const pinoOpts = { level: 'debug', useOnlyCustomLevels: true, customLevels: customLevels, }; const multistreamOpts = { dedupe: true, levels: customLevels }; const streams: StreamEntry<CustomLevels>[] = [ { level : 'debug', stream : pinoPretty() }, { level : 'info', stream : pinoPretty() }, { level : 'network', stream : pinoPretty() }, { level : 'error', stream : pinoPretty() }, ]; const loggerCustomLevel = pino(pinoOpts, pino.multistream(streams, multistreamOpts)); loggerCustomLevel.debug('test3') loggerCustomLevel.info('test4') loggerCustomLevel.error('test5') loggerCustomLevel.network('test6') ```
/content/code_sandbox/test/types/pino.ts
xml
2016-02-16T14:14:29
2024-08-16T17:25:00
pino
pinojs/pino
13,839
477
```xml // *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // path_to_url // *********************************************** // eslint-disable-next-line @typescript-eslint/no-namespace declare namespace Cypress { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface Chainable<Subject> { login(email: string, password: string): void; } } // // -- This is a parent command -- Cypress.Commands.add('login', (email, password) => { console.log('Custom command example: Login', email, password); }); // // -- This is a child command -- // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) ```
/content/code_sandbox/apps/docs-e2e/src/support/commands.ts
xml
2016-07-11T23:30:52
2024-08-15T15:20:45
covalent
Teradata/covalent
2,228
237
```xml import * as React from 'react'; import { Calendar, defaultCalendarStrings } from '@fluentui/react'; export const CalendarInlineOverlaidMonthExample: React.FunctionComponent = () => { const [selectedDate, setSelectedDate] = React.useState<Date>(); const onSelectDate = React.useCallback((date: Date, dateRangeArray: Date[]): void => { setSelectedDate(date); }, []); return ( <div style={{ height: '360px' }}> <div>Selected date: {selectedDate?.toLocaleString() || 'Not set'}</div> <Calendar showMonthPickerAsOverlay highlightSelectedMonth showGoToToday={false} onSelectDate={onSelectDate} value={selectedDate} // Calendar uses English strings by default. For localized apps, you must override this prop. strings={defaultCalendarStrings} /> </div> ); }; ```
/content/code_sandbox/packages/react-examples/src/react/Calendar/Calendar.Inline.OverlaidMonthPicker.Example.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
195
```xml /*~ On this line, import the module which this module adds to */ import * as m from 'someModule'; /*~ You can also import other modules if needed */ import * as other from 'anotherModule'; /*~ Here, declare the same module as the one you imported above */ declare module 'someModule' { /*~ Inside, add new function, classes, or variables. You can use *~ unexported types from the original module if needed. */ export function theNewMethod(x: m.foo): other.bar; /*~ You can also add new properties to existing interfaces from *~ the original module by writing interface augmentations */ export interface SomeModuleOptions { someModuleSetting?: string; } /*~ New types can also be declared and will appear as if they *~ are in the original module */ export interface MyModulePluginOptions { size: number; } } ```
/content/code_sandbox/templates/module-plugin.d.ts
xml
2016-08-25T21:07:14
2024-07-29T17:30:13
dts-gen
microsoft/dts-gen
2,431
197
```xml import * as React from 'react'; import { makeStyles, CompoundButton } from '@fluentui/react-components'; import { bundleIcon, CalendarMonthFilled, CalendarMonthRegular } from '@fluentui/react-icons'; const CalendarMonth = bundleIcon(CalendarMonthFilled, CalendarMonthRegular); const useStyles = makeStyles({ wrapper: { columnGap: '15px', display: 'flex', minWidth: 'min-content', }, }); export const Appearance = () => { const styles = useStyles(); return ( <div className={styles.wrapper}> <CompoundButton secondaryContent="Secondary content" icon={<CalendarMonthRegular />}> Default </CompoundButton> <CompoundButton secondaryContent="Secondary content" appearance="primary" icon={<CalendarMonthRegular />}> Primary </CompoundButton> <CompoundButton secondaryContent="Secondary content" appearance="outline" icon={<CalendarMonth />}> Outline </CompoundButton> <CompoundButton secondaryContent="Secondary content" appearance="subtle" icon={<CalendarMonth />}> Subtle </CompoundButton> <CompoundButton secondaryContent="Secondary content" appearance="transparent" icon={<CalendarMonth />}> Transparent </CompoundButton> </div> ); }; Appearance.parameters = { docs: { description: { story: '- `(undefined)`: the compound button appears with the default style\n' + '- `primary`: emphasizes the compound button as a primary action.\n' + '- `outline`: removes background styling.\n' + '- `subtle`: minimizes emphasis to blend into the background until hovered or focused\n' + '- `transparent`: removes background and border styling.\n', }, }, }; ```
/content/code_sandbox/packages/react-components/react-button/stories/src/CompoundButton/CompoundButtonAppearance.stories.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
363
```xml <?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="Xamarin.Forms.Controls.Issues.Issue9734" xmlns="path_to_url" xmlns:x="path_to_url" Title="Issue 9734" x:Name="Issue9734Page"> <ContentPage.Content> <Grid RowSpacing="0" ColumnSpacing="0" VerticalOptions="FillAndExpand"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <CollectionView Grid.Row="1" x:Name="MyCollectionView" ItemsSource="{Binding Items}" VerticalOptions="FillAndExpand" ItemSizingStrategy="MeasureAllItems"> <CollectionView.ItemTemplate> <DataTemplate> <SwipeView> <SwipeView.RightItems> <SwipeItems> <SwipeItem Text="Delete" IconImageSource="calculator.png" BackgroundColor="Red" /> </SwipeItems> </SwipeView.RightItems> <SwipeView.LeftItems> <SwipeItems> <SwipeItem Text="Edit" IconImageSource="calculator.png" BackgroundColor="Orange" /> </SwipeItems> </SwipeView.LeftItems> <Grid VerticalOptions="Start" BackgroundColor="White"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <BoxView Grid.Column="0" BackgroundColor="Gray" CornerRadius="36" HeightRequest="36" WidthRequest="36" HorizontalOptions="CenterAndExpand" Margin="12,12,0,0" VerticalOptions="Start" /> <StackLayout Grid.Column="1" VerticalOptions="StartAndExpand" Padding="10, 10, 10, 10" Spacing="3" Orientation="Vertical" HorizontalOptions="FillAndExpand"> <Label Text="{Binding Title}" FontSize="18" HorizontalOptions="Fill" LineBreakMode="TailTruncation" MaxLines="2" VerticalOptions="EndAndExpand" /> <Label Text="{Binding SubTitle}" LineBreakMode="TailTruncation" MaxLines="2" VerticalOptions="FillAndExpand" FontAttributes="Bold" HorizontalOptions="Start" /> <Label Text="{Binding Relation}" LineBreakMode="WordWrap" MaxLines="2" VerticalOptions="FillAndExpand" HorizontalOptions="Start" /> </StackLayout> </Grid> </SwipeView> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> <Grid Grid.Row="1" VerticalOptions="EndAndExpand" HorizontalOptions="End"> <Button Text="Fav"/> </Grid> </Grid> </ContentPage.Content> </ContentPage> ```
/content/code_sandbox/Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Issue9734.xaml
xml
2016-03-18T15:52:03
2024-08-16T16:25:43
Xamarin.Forms
xamarin/Xamarin.Forms
5,637
676
```xml import "reflect-metadata" import { expect } from "chai" import { DataSource } from "../../src/data-source/DataSource" import { Repository } from "../../src/repository/Repository" import { PostDetails } from "../../sample/sample3-many-to-one/entity/PostDetails" import { Post } from "../../sample/sample3-many-to-one/entity/Post" import { PostCategory } from "../../sample/sample3-many-to-one/entity/PostCategory" import { PostAuthor } from "../../sample/sample3-many-to-one/entity/PostAuthor" import { PostMetadata } from "../../sample/sample3-many-to-one/entity/PostMetadata" import { PostImage } from "../../sample/sample3-many-to-one/entity/PostImage" import { PostInformation } from "../../sample/sample3-many-to-one/entity/PostInformation" import { setupSingleTestingConnection } from "../utils/test-utils" describe("many-to-one", function () { // your_sha256_hash--------- // Configuration // your_sha256_hash--------- // connect to db let dataSource: DataSource before(async function () { const options = setupSingleTestingConnection("mysql", { entities: [ Post, PostDetails, PostCategory, PostMetadata, PostImage, PostInformation, PostAuthor, ], }) if (!options) return dataSource = new DataSource(options) await dataSource.initialize() }) after(() => dataSource.destroy()) // clean up database before each test function reloadDatabase() { if (!dataSource) return return dataSource.synchronize(true) } let postRepository: Repository<Post>, postDetailsRepository: Repository<PostDetails>, postCategoryRepository: Repository<PostCategory>, postImageRepository: Repository<PostImage>, postMetadataRepository: Repository<PostMetadata> before(function () { if (!dataSource) return postRepository = dataSource.getRepository(Post) postDetailsRepository = dataSource.getRepository(PostDetails) postCategoryRepository = dataSource.getRepository(PostCategory) postImageRepository = dataSource.getRepository(PostImage) postMetadataRepository = dataSource.getRepository(PostMetadata) }) // your_sha256_hash--------- // Specifications // your_sha256_hash--------- describe("insert post and details (has inverse relation + full cascade options)", function () { if (!dataSource) return let newPost: Post, details: PostDetails, savedPost: Post before(reloadDatabase) before(function () { details = new PostDetails() details.authorName = "Umed" details.comment = "this is post" details.metadata = "post,posting,postman" newPost = new Post() newPost.text = "Hello post" newPost.title = "this is post title" newPost.details = details return postRepository .save(newPost) .then((post) => (savedPost = post as Post)) }) it("should return the same post instance after its created", function () { savedPost.should.be.equal(newPost) }) it("should return the same post details instance after its created", function () { savedPost.details!.should.be.equal(newPost.details) }) it("should have a new generated id after post is created", function () { expect(savedPost.id).not.to.be.undefined expect(savedPost.details!.id).not.to.be.undefined }) it("should have inserted post in the database", function () { if (!dataSource) return const expectedPost = new Post() expectedPost.id = savedPost.id expectedPost.text = savedPost.text expectedPost.title = savedPost.title return postRepository .findOneBy({ id: savedPost.id, }) .should.eventually.eql(expectedPost) }) it("should have inserted post details in the database", function () { if (!dataSource) return const expectedDetails = new PostDetails() expectedDetails.id = savedPost.details!.id expectedDetails.authorName = savedPost.details!.authorName expectedDetails.comment = savedPost.details!.comment expectedDetails.metadata = savedPost.details!.metadata return postDetailsRepository .findOneBy({ id: savedPost.details!.id, }) .should.eventually.eql(expectedDetails) }) it("should load post and its details if left join used", function () { if (!dataSource) return const expectedPost = new Post() expectedPost.id = savedPost.id expectedPost.text = savedPost.text expectedPost.title = savedPost.title expectedPost.details = new PostDetails() expectedPost.details.id = savedPost.details!.id expectedPost.details.authorName = savedPost.details!.authorName expectedPost.details.comment = savedPost.details!.comment expectedPost.details.metadata = savedPost.details!.metadata return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.details", "details") .where("post.id=:id") .setParameter("id", savedPost.id) .getOne() .should.eventually.eql(expectedPost) }) it("should load details and its post if left join used (from reverse side)", function () { if (!dataSource) return const expectedDetails = new PostDetails() expectedDetails.id = savedPost.details!.id expectedDetails.authorName = savedPost.details!.authorName expectedDetails.comment = savedPost.details!.comment expectedDetails.metadata = savedPost.details!.metadata const expectedPost = new Post() expectedPost.id = savedPost.id expectedPost.text = savedPost.text expectedPost.title = savedPost.title expectedDetails.posts = [] expectedDetails.posts.push(expectedPost) return postDetailsRepository .createQueryBuilder("details") .leftJoinAndSelect("details.posts", "posts") .where("details.id=:id") .setParameter("id", savedPost.id) .getOne() .should.eventually.eql(expectedDetails) }) it("should load saved post without details if left joins are not specified", function () { if (!dataSource) return const expectedPost = new Post() expectedPost.id = savedPost.id expectedPost.text = savedPost.text expectedPost.title = savedPost.title return postRepository .createQueryBuilder("post") .where("post.id=:id", { id: savedPost.id }) .getOne() .should.eventually.eql(expectedPost) }) it("should load saved post without details if left joins are not specified", function () { if (!dataSource) return const expectedDetails = new PostDetails() expectedDetails.id = savedPost.details!.id expectedDetails.authorName = savedPost.details!.authorName expectedDetails.comment = savedPost.details!.comment expectedDetails.metadata = savedPost.details!.metadata return postDetailsRepository .createQueryBuilder("details") .where("details.id=:id", { id: savedPost.id }) .getOne() .should.eventually.eql(expectedDetails) }) it("should load post and its details with no hangup if query used", async function () { if (!dataSource) return const expectedPost = new Post() expectedPost.id = savedPost.id expectedPost.text = savedPost.text expectedPost.title = savedPost.title expectedPost.details = new PostDetails() expectedPost.details!.id = savedPost.details!.id expectedPost.details!.authorName = savedPost.details!.authorName expectedPost.details!.comment = savedPost.details!.comment expectedPost.details!.metadata = savedPost.details!.metadata const findOne = () => postRepository.findOne({ where: { id: savedPost.id }, relations: { details: true }, relationLoadStrategy: "query" }) const posts = await Promise.all([ findOne(), findOne(), findOne(), findOne(), findOne(), findOne(), findOne(), findOne(), findOne(), findOne(), ]) posts.forEach(post => { expect(post).not.to.be.null post!.should.eql(expectedPost) }) }) }) describe("insert post and category (one-side relation)", function () { if (!dataSource) return let newPost: Post, category: PostCategory, savedPost: Post before(reloadDatabase) before(function () { category = new PostCategory() category.name = "technology" newPost = new Post() newPost.text = "Hello post" newPost.title = "this is post title" newPost.category = category return postRepository .save(newPost) .then((post) => (savedPost = post as Post)) }) it("should return the same post instance after its created", function () { savedPost.should.be.equal(newPost) }) it("should return the same post category instance after its created", function () { savedPost.category.should.be.equal(newPost.category) }) it("should have a new generated id after post is created", function () { expect(savedPost.id).not.to.be.undefined expect(savedPost.category.id).not.to.be.undefined }) it("should have inserted post in the database", function () { if (!dataSource) return const expectedPost = new Post() expectedPost.id = savedPost.id expectedPost.text = savedPost.text expectedPost.title = savedPost.title return postRepository .findOneBy({ id: savedPost.id, }) .should.eventually.eql(expectedPost) }) it("should have inserted category in the database", function () { if (!dataSource) return const expectedPost = new PostCategory() expectedPost.id = savedPost.category.id expectedPost.name = "technology" return postCategoryRepository .findOneBy({ id: savedPost.category.id, }) .should.eventually.eql(expectedPost) }) it("should load post and its category if left join used", function () { if (!dataSource) return const expectedPost = new Post() expectedPost.id = savedPost.id expectedPost.title = savedPost.title expectedPost.text = savedPost.text expectedPost.category = new PostCategory() expectedPost.category.id = savedPost.category.id expectedPost.category.name = savedPost.category.name return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.category", "category") .where("post.id=:id", { id: savedPost.id }) .getOne() .should.eventually.eql(expectedPost) }) it("should load details and its post if left join used (from reverse side)", function () { // later need to specify with what exception we reject it /*return postCategoryRepository .createQueryBuilder("category") .leftJoinAndSelect("category.post", "post") .where("category.id=:id", { id: savedPost.id }) .getSingleResult() .should.be.rejectedWith(Error);*/ // not working, find fix }) }) describe("cascade updates should not be executed when cascadeUpdate option is not set", function () { if (!dataSource) return let newPost: Post, details: PostDetails before(reloadDatabase) before(function () { details = new PostDetails() details.authorName = "Umed" details.comment = "this is post" details.metadata = "post,posting,postman" newPost = new Post() newPost.text = "Hello post" newPost.title = "this is post title" newPost.details = details return postRepository.save(newPost) }) it("should ignore updates in the model and do not update the db when entity is updated", function () { newPost.details!.comment = "i am updated comment" return postRepository .save(newPost) .then((updatedPost) => { updatedPost.details!.comment!.should.be.equal( "i am updated comment", ) return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.details", "details") .where("post.id=:id") .setParameter("id", updatedPost.id) .getOne() }) .then((updatedPostReloaded) => { updatedPostReloaded!.details!.comment!.should.be.equal( "this is post", ) }) }) // todo: also check that updates throw exception in strict cascades mode }) describe("cascade remove should not be executed when cascadeRemove option is not set", function () { if (!dataSource) return let newPost: Post, details: PostDetails before(reloadDatabase) before(function () { details = new PostDetails() details.authorName = "Umed" details.comment = "this is post" details.metadata = "post,posting,postman" newPost = new Post() newPost.text = "Hello post" newPost.title = "this is post title" newPost.details = details return postRepository.save(newPost) }) it("should ignore updates in the model and do not update the db when entity is updated", function () { delete newPost.details return postRepository .save(newPost) .then((updatedPost) => { return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.details", "details") .where("post.id=:id") .setParameter("id", updatedPost.id) .getOne() }) .then((updatedPostReloaded) => { updatedPostReloaded!.details!.comment!.should.be.equal( "this is post", ) }) }) }) describe("cascade updates should be executed when cascadeUpdate option is set", function () { if (!dataSource) return let newPost: Post, newImage: PostImage before(reloadDatabase) it("should update a relation successfully when updated", function () { newImage = new PostImage() newImage.url = "logo.png" newPost = new Post() newPost.text = "Hello post" newPost.title = "this is post title" return postImageRepository .save(newImage) .then((image) => { newPost.image = image as PostImage return postRepository.save(newPost) }) .then((post) => { newPost = post as Post return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.image", "image") .where("post.id=:id") .setParameter("id", post.id) .getOne() }) .then((loadedPost) => { loadedPost!.image.url = "new-logo.png" return postRepository.save(loadedPost!) }) .then(() => { return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.image", "image") .where("post.id=:id") .setParameter("id", newPost.id) .getOne() }) .then((reloadedPost) => { reloadedPost!.image.url.should.be.equal("new-logo.png") }) }) }) describe("cascade remove should be executed when cascadeRemove option is set", function () { if (!dataSource) return let newPost: Post, newMetadata: PostMetadata before(reloadDatabase) it("should remove a relation entity successfully when removed", function () { newMetadata = new PostMetadata() newMetadata.description = "this is post metadata" newPost = new Post() newPost.text = "Hello post" newPost.title = "this is post title" return postMetadataRepository .save(newMetadata) .then((metadata) => { newPost.metadata = metadata as PostMetadata return postRepository.save(newPost) }) .then((post) => { newPost = post as Post return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.metadata", "metadata") .where("post.id=:id") .setParameter("id", post.id) .getOne() }) .then((loadedPost) => { loadedPost!.metadata = null return postRepository.save(loadedPost!) }) .then(() => { return postRepository .createQueryBuilder("post") .leftJoinAndSelect("post.metadata", "metadata") .where("post.id=:id") .setParameter("id", newPost.id) .getOne() }) .then((reloadedPost) => { expect(reloadedPost!.metadata).to.be.null }) }) }) describe("insert post details from reverse side", function () { if (!dataSource) return let newPost: Post, details: PostDetails, savedDetails: PostDetails before(reloadDatabase) before(function () { newPost = new Post() newPost.text = "Hello post" newPost.title = "this is post title" details = new PostDetails() details.comment = "post details comment" details.posts = [] details.posts.push(newPost) return postDetailsRepository .save(details) .then((details) => (savedDetails = details as PostDetails)) }) it("should return the same post instance after its created", function () { savedDetails.posts[0].should.be.equal(newPost) }) it("should return the same post details instance after its created", function () { savedDetails.should.be.equal(details) }) it("should have a new generated id after post is created", function () { expect(savedDetails.id).not.to.be.undefined expect(details.id).not.to.be.undefined }) it("should have inserted post in the database", function () { const expectedPost = new Post() expectedPost.id = newPost.id expectedPost.text = newPost.text expectedPost.title = newPost.title return postRepository .findOneBy({ id: savedDetails.id, }) .should.eventually.eql(expectedPost) }) it("should have inserted details in the database", function () { const expectedDetails = new PostDetails() expectedDetails.id = details.id expectedDetails.comment = details.comment expectedDetails.metadata = null expectedDetails.authorName = null return postDetailsRepository .findOneBy({ id: details.id, }) .should.eventually.eql(expectedDetails) }) it("should load post and its details if left join used", function () { const expectedDetails = new PostDetails() expectedDetails.id = savedDetails.id expectedDetails.comment = savedDetails.comment expectedDetails.metadata = null expectedDetails.authorName = null expectedDetails.posts = [] expectedDetails.posts.push(new Post()) expectedDetails.posts[0].id = newPost.id expectedDetails.posts[0].text = newPost.text expectedDetails.posts[0].title = newPost.title return postDetailsRepository .createQueryBuilder("details") .leftJoinAndSelect("details.posts", "posts") .where("details.id=:id", { id: savedDetails.id }) .getOne() .should.eventually.eql(expectedDetails) }) }) }) ```
/content/code_sandbox/test/integration/sample3-many-to-one.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
4,164
```xml <menu xmlns:tools="path_to_url" xmlns:android="path_to_url" xmlns:app="path_to_url"> <item android:id="@+id/action_photos_filter" android:icon="@drawable/ic_filter" android:orderInCategory="75" android:visible="false" app:iconTint="?attr/colorControlNormal" app:showAsAction="always" /> <item android:id="@+id/action_cu_status_default" android:icon="@drawable/ic_cu_status" android:orderInCategory="80" android:visible="false" app:showAsAction="always" tools:ignore="AlwaysShowAction" /> <item android:id="@+id/action_cu_status_paused" android:icon="@drawable/ic_cu_status_paused" android:orderInCategory="80" android:visible="false" app:showAsAction="always" /> <item android:id="@+id/action_cu_status_complete" android:icon="@drawable/ic_cu_status_completed" android:orderInCategory="80" android:visible="false" app:showAsAction="always" /> <item android:id="@+id/action_cu_status_warning" android:icon="@drawable/ic_cu_status_warning" android:orderInCategory="80" android:visible="false" app:showAsAction="always" /> <item android:id="@+id/action_photos_filter_secondary" android:icon="@drawable/ic_action_bar_null" android:orderInCategory="105" android:title="@string/photos_action_filter" android:visible="false" app:showAsAction="never" /> <item android:id="@+id/action_photos_sortby" android:icon="@drawable/ic_action_bar_null" android:orderInCategory="110" android:title="@string/action_sort_by" android:visible="false" app:showAsAction="never" /> <item android:id="@+id/action_zoom_in" android:orderInCategory="120" android:title="@string/photos_action_zoom_in" android:visible="false" app:showAsAction="never" /> <item android:id="@+id/action_zoom_out" android:orderInCategory="130" android:title="@string/photos_action_zoom_out" android:visible="false" app:showAsAction="never" /> <item android:id="@+id/action_cu_settings" android:icon="@drawable/ic_action_bar_null" android:orderInCategory="140" android:title="@string/action_settings" android:visible="false" app:showAsAction="never" /> </menu> ```
/content/code_sandbox/app/src/main/res/menu/fragment_photos_toolbar.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
592
```xml #import <ReactCommon/RCTTurboModule.h> #import <ExpoModulesCore/ExpoBridgeModule.h> #import <ExpoModulesCore/Swift.h> // The runtime executor is included as of React Native 0.74 in bridgeless mode. #if __has_include(<ReactCommon/RCTRuntimeExecutor.h>) #import <ReactCommon/RCTRuntimeExecutor.h> #endif // React Native >=0.74 @implementation ExpoBridgeModule @synthesize bridge = _bridge; RCT_EXPORT_MODULE(ExpoModulesCore); - (instancetype)init { if (self = [super init]) { _appContext = [[EXAppContext alloc] init]; } return self; } - (instancetype)initWithAppContext:(EXAppContext *) appContext { if (self = [super init]) { _appContext = appContext; } return self; } + (BOOL)requiresMainQueueSetup { // We do want to run the initialization (`setBridge`) on the JS thread. return NO; } - (void)setBridge:(RCTBridge *)bridge { // As of React Native 0.74 with the New Architecture enabled, // it's actually an instance of `RCTBridgeProxy` that provides backwards compatibility. // Also, hold on with initializing the runtime until `setRuntimeExecutor` is called. _bridge = bridge; _appContext.reactBridge = bridge; #if !__has_include(<ReactCommon/RCTRuntimeExecutor.h>) _appContext._runtime = [EXJavaScriptRuntimeManager runtimeFromBridge:bridge]; #endif // React Native <0.74 } #if __has_include(<ReactCommon/RCTRuntimeExecutor.h>) - (void)setRuntimeExecutor:(RCTRuntimeExecutor *)runtimeExecutor { _appContext._runtime = [EXJavaScriptRuntimeManager runtimeFromBridge:_bridge withExecutor:runtimeExecutor]; } #endif // React Native >=0.74 /** This should be called inside `[EXNativeModulesProxy setBridge:]`. */ - (void)legacyProxyDidSetBridge:(nonnull EXNativeModulesProxy *)moduleProxy legacyModuleRegistry:(nonnull EXModuleRegistry *)moduleRegistry { _appContext.legacyModulesProxy = moduleProxy; _appContext.legacyModuleRegistry = moduleRegistry; // We need to register all the modules after the legacy module registry is set // otherwise legacy modules (e.g. permissions) won't be available in OnCreate { } [_appContext useModulesProvider:@"ExpoModulesProvider"]; } /** A synchronous method that is called from JS before requiring any module to ensure that all necessary bindings are installed. */ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(installModules) { if (_bridge && !_appContext._runtime) { // TODO: Keep this condition until we remove the other way of installing modules. // See `setBridge` method above. _appContext._runtime = [EXJavaScriptRuntimeManager runtimeFromBridge:_bridge]; } return nil; } @end ```
/content/code_sandbox/packages/expo-modules-core/ios/Core/ExpoBridgeModule.mm
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
628
```xml import { html, ref } from '@microsoft/fast-element'; import type { ElementViewTemplate } from '@microsoft/fast-element'; import { staticallyCompose } from '../utils/template-helpers.js'; import type { SliderOptions } from './slider.options.js'; import type { Slider } from './slider.js'; export function sliderTemplate<T extends Slider>(options: SliderOptions = {}): ElementViewTemplate<T> { return html<T>` <template tabindex="${x => (x.disabled ? null : 0)}" @pointerdown="${(x, c) => x.handlePointerDown(c.event as PointerEvent)}" > <div ${ref('track')} part="track-container" class="track" style="${x => x.position}"></div> <div ${ref('thumb')} part="thumb-container" class="thumb-container" style="${x => x.position}" @pointerdown="${(x, c) => x.handleThumbPointerDown(c.event as PointerEvent)}" > <slot name="thumb">${staticallyCompose(options.thumb)}</slot> </div> </template> `; } export const template: ElementViewTemplate<Slider> = sliderTemplate({ thumb: `<div class="thumb"></div>`, }); ```
/content/code_sandbox/packages/web-components/src/slider/slider.template.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
264
```xml import { EventOccurrence, Refiner, RefinerValue } from "model"; import { Moment } from "moment-timezone"; import { IEventCommands } from "../events/IEventCommands"; import { IViewCommands } from "./IViewCommands"; export interface IViewProps { anchorDate: Moment; cccurrences: readonly EventOccurrence[]; refiners: readonly Refiner[]; selectedRefinerValues: Set<RefinerValue>; eventCommands: IEventCommands; viewCommands: IViewCommands; } ```
/content/code_sandbox/samples/react-rhythm-of-business-calendar/src/components/views/IViewProps.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
112
```xml <?xml version="1.0" encoding="UTF-8"?> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <LWM2M xmlns:xsi="path_to_url" xsi:noNamespaceSchemaLocation="path_to_url"> <Object ObjectType="MODefinition"> <Name>oA OGC-Security</Name> <Description1><![CDATA[The 'OGC Security' provides the appropriate keying material for a specific OGC Application group in the context of OGC. The keying material will be provided by a key distribution server, and must not be readable by any instance outside the local node.]]></Description1> <ObjectID>3405</ObjectID> <ObjectURN>urn:oma:lwm2m:ext:3405</ObjectURN> <LWM2MVersion>1.1</LWM2MVersion> <ObjectVersion>1.0</ObjectVersion> <MultipleInstances>Multiple</MultipleInstances> <Mandatory>Optional</Mandatory> <Resources> <Item ID="4001"> <Name>ObjectVersion</Name> <Operations>R</Operations> <MultipleInstances>Single</MultipleInstances> <Mandatory>Optional</Mandatory> <Type>String</Type> <RangeEnumeration></RangeEnumeration> <Units></Units> <Description><![CDATA[LWM2M Object versioning label.]]></Description> </Item> <Item ID="901"> <Name>Documentary Description</Name> <Operations>RW</Operations> <MultipleInstances>Single</MultipleInstances> <Mandatory>Optional</Mandatory> <Type>String</Type> <RangeEnumeration>0..256 bytes</RangeEnumeration> <Units></Units> <Description><![CDATA[Resource to hold a documentary text description of the object.]]></Description> </Item> <Item ID="0"> <Name>OGC Security ID</Name> <Operations>RW</Operations> <MultipleInstances>Single</MultipleInstances> <Mandatory>Mandatory</Mandatory> <Type>Unsigned Integer</Type> <RangeEnumeration>0..65535</RangeEnumeration> <Units></Units> <Description><![CDATA[Uniquely identifies the OpenAIS Security group that this instance is using.]]></Description> </Item> <Item ID="3"> <Name>Accepted Senders</Name> <Operations>RW</Operations> <MultipleInstances>Multiple</MultipleInstances> <Mandatory>Mandatory</Mandatory> <Type>Opaque</Type> <RangeEnumeration></RangeEnumeration> <Units></Units> <Description><![CDATA[Stores the identities (OSCORE / IPv6) and Keys of accepted senders in the group]]></Description> </Item> <Item ID="5"> <Name>Secret Group Key</Name> <Operations>W</Operations> <MultipleInstances>Single</MultipleInstances> <Mandatory>Mandatory</Mandatory> <Type>Opaque</Type> <RangeEnumeration></RangeEnumeration> <Units></Units> <Description><![CDATA[Stores the shared symmetric key for low latency group communication.This Resource MUST NOT be readable by any server.]]></Description> </Item> </Resources> <Description2><![CDATA[]]></Description2> </Object> </LWM2M> ```
/content/code_sandbox/application/src/main/data/lwm2m-registry/3405.xml
xml
2016-12-01T09:33:30
2024-08-16T19:58:25
thingsboard
thingsboard/thingsboard
16,820
1,042