text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```xml
import React, { FunctionComponent } from "react";
const MessagesBubbleSquareStarIcon: FunctionComponent = () => {
// path_to_url
return (
<svg viewBox="0 0 24 24" xmlns="path_to_url">
<path
d="M8.223 19.9 3.75 23.25v-4.5h-1.5a1.5 1.5 0 0 1 -1.5 -1.5v-15a1.5 1.5 0 0 1 1.5 -1.5h19.5a1.5 1.5 0 0 1 1.5 1.5v9"
fill="none"
stroke="currentcolor"
strokeLinecap="round"
strokeLinejoin="round"
></path>
<path
d="M17.948 11.68 19.489 15h3a0.735 0.735 0 0 1 0.518 1.283l-2.6 2.562 1.442 3.314a0.786 0.786 0 0 1 -1.119 0.982l-3.486 -1.961 -3.487 1.961a0.786 0.786 0 0 1 -1.119 -0.982l1.443 -3.314 -2.6 -2.562A0.734 0.734 0 0 1 11.989 15h3l1.544 -3.323a0.8 0.8 0 0 1 1.415 0.003Z"
fill="none"
stroke="currentcolor"
strokeLinecap="round"
strokeLinejoin="round"
></path>
</svg>
);
};
export default MessagesBubbleSquareStarIcon;
``` | /content/code_sandbox/client/src/core/client/ui/components/icons/MessagesBubbleSquareStarIcon.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 424 |
```xml
<?xml version="1.0" encoding="utf-8"?><!--
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<resources>
<!-- Default colors and dimens per Material Design guidelines (Last update: May 2016 release) -->
<!-- Layout -->
<!-- Metrics & Keylines -->
<!-- path_to_url#metrics-keylines-keylines-spacing -->
<dimen name="material_layout_keylines_screen_edge_margin">24dp</dimen>
<dimen name="material_layout_keylines_content_left_margin_from_screen_edge">80dp</dimen>
<dimen name="material_layout_keylines_horizontal_mobile_margin">24dp</dimen>
</resources>
``` | /content/code_sandbox/material-design-dimens/src/main/res/values-sw600dp/dimens.xml | xml | 2016-05-08T18:56:18 | 2024-08-07T21:41:38 | material-design-dimens | DmitryMalkovich/material-design-dimens | 1,349 | 166 |
```xml
import 'reflect-metadata';
import { assert } from 'chai';
import { ServiceIdentifiers } from '../../../src/container/ServiceIdentifiers';
import { IArrayUtils } from '../../../src/interfaces/utils/IArrayUtils';
import { IInversifyContainerFacade } from '../../../src/interfaces/container/IInversifyContainerFacade';
import { InversifyContainerFacade } from '../../../src/container/InversifyContainerFacade';
describe('ArrayUtils', () => {
let arrayUtils: IArrayUtils;
before(() => {
const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade();
inversifyContainerFacade.load('', '', {});
arrayUtils = inversifyContainerFacade.get<IArrayUtils>(ServiceIdentifiers.IArrayUtils);
});
describe('createWithRange', () => {
describe('range length more than 0', () => {
const rangeLength: number = 5;
const expectedArray: number[] = [0, 1, 2, 3, 4];
let array: number[];
before(() => {
array = arrayUtils.createWithRange(rangeLength);
});
it('should return array with range of numbers', () => {
assert.deepEqual(array, expectedArray);
});
});
describe('range length is 0', () => {
const rangeLength: number = 0;
const expectedArray: number[] = [];
let array: number[];
before(() => {
array = arrayUtils.createWithRange(rangeLength);
});
it('should return empty array', () => {
assert.deepEqual(array, expectedArray);
});
});
describe('range length less than 0', () => {
const rangeLength: number = -5;
const expectedArray: number[] = [];
let array: number[];
before(() => {
array = arrayUtils.createWithRange(rangeLength);
});
it('should return empty array', () => {
assert.deepEqual(array, expectedArray);
});
});
});
describe('fillWithRange', () => {
const valueFunction: (index: number) => string = (index: number) => `foo${index}`;
describe('range length more than 0', () => {
const rangeLength: number = 5;
const expectedArray: string[] = [
'foo0',
'foo1',
'foo2',
'foo3',
'foo4',
];
let array: string[];
before(() => {
array = arrayUtils.fillWithRange(rangeLength, valueFunction);
});
it('should return array with range of strings', () => {
assert.deepEqual(array, expectedArray);
});
});
describe('range length is 0', () => {
const rangeLength: number = 0;
const expectedArray: string[] = [];
let array: string[];
before(() => {
array = arrayUtils.fillWithRange(rangeLength, valueFunction);
});
it('should return empty array', () => {
assert.deepEqual(array, expectedArray);
});
});
describe('range length less than 0', () => {
const rangeLength: number = -5;
const expectedArray: string[] = [];
let array: string[];
before(() => {
array = arrayUtils.fillWithRange(rangeLength, valueFunction);
});
it('should return empty array', () => {
assert.deepEqual(array, expectedArray);
});
});
});
describe('findMostOccurringElement', () => {
describe('empty array', () => {
const array: string[] = [];
const expectedMostOccurringElement: null = null;
let mostOccurringElement: string | null;
before(() => {
mostOccurringElement = arrayUtils.findMostOccurringElement(array);
});
it('should return null if array is empty', () => {
assert.equal(mostOccurringElement, expectedMostOccurringElement);
});
});
describe('one elements is most occurring', () => {
const array: string[] = ['foo', 'bar', 'bar', 'baz', 'bar', 'foo'];
const expectedMostOccurringElement: string = 'bar';
let mostOccurringElement: string | null;
before(() => {
mostOccurringElement = arrayUtils.findMostOccurringElement(array);
});
it('should return most occurring element', () => {
assert.equal(mostOccurringElement, expectedMostOccurringElement);
});
});
describe('few elements are most occurring', () => {
const array: string[] = ['foo', 'bar', 'bar', 'baz', 'bar'];
const expectedMostOccurringElement: string = 'bar';
let mostOccurringElement: string | null;
before(() => {
mostOccurringElement = arrayUtils.findMostOccurringElement(array);
});
it('should return first most occurring element', () => {
assert.equal(mostOccurringElement, expectedMostOccurringElement);
});
});
});
describe('getLastElement', () => {
describe('empty array', () => {
const array: string[] = [];
const expectedLastElement: undefined = undefined;
let lastElement: string | undefined;
before(() => {
lastElement = arrayUtils.getLastElement(array);
});
it('should return undefined if array is empty', () => {
assert.equal(lastElement, expectedLastElement);
});
});
describe('array length: `1`', () => {
const array: string[] = ['foo'];
const expectedLastElement: string = 'foo';
let lastElement: string | undefined;
before(() => {
lastElement = arrayUtils.getLastElement(array);
});
it('should return first element for array with length: `1`', () => {
assert.equal(lastElement, expectedLastElement);
});
});
describe('array length: `3`', () => {
const array: string[] = ['foo', 'bar', 'baz'];
const expectedLastElement: string = 'baz';
let lastElement: string | undefined;
before(() => {
lastElement = arrayUtils.getLastElement(array);
});
it('should return last element for array with length: `3`', () => {
assert.equal(lastElement, expectedLastElement);
});
});
});
describe('getLastElementByIndex', () => {
describe('empty array', () => {
const array: string[] = [];
const expectedLastElement: undefined = undefined;
let lastElement: string | undefined;
before(() => {
lastElement = arrayUtils.getLastElementByIndex(array, 1);
});
it('should return undefined if array is empty', () => {
assert.equal(lastElement, expectedLastElement);
});
});
describe('array length: `1` and index is out of array boundary', () => {
const array: string[] = ['foo'];
const expectedLastElement: undefined = undefined;
let lastElement: string | undefined;
before(() => {
lastElement = arrayUtils.getLastElementByIndex(array, 2);
});
it('should return undefined', () => {
assert.equal(lastElement, expectedLastElement);
});
});
describe('array length: `3` and index is `0`', () => {
const array: string[] = ['foo', 'bar', 'baz'];
const expectedLastElement: string = 'baz';
let lastElement: string | undefined;
before(() => {
lastElement = arrayUtils.getLastElementByIndex(array, 0);
});
it('should return element with a correct index', () => {
assert.equal(lastElement, expectedLastElement);
});
});
describe('array length: `3` and index is `1`', () => {
const array: string[] = ['foo', 'bar', 'baz'];
const expectedLastElement: string = 'bar';
let lastElement: string | undefined;
before(() => {
lastElement = arrayUtils.getLastElementByIndex(array, 1);
});
it('should return element with a correct index', () => {
assert.equal(lastElement, expectedLastElement);
});
});
});
describe('rotate', () => {
let array: number[],
rotatedArray: number[];
beforeEach(() => {
array = [1, 2, 3, 4, 5, 6];
});
describe('value is not 0', () => {
const rotateValue: number = 2;
const expectedArray: number[] = [5, 6, 1, 2, 3, 4];
beforeEach(() => {
rotatedArray = arrayUtils.rotate(array, rotateValue);
});
it('should rotate (shift) array by a given value', () => {
assert.deepEqual(rotatedArray, expectedArray);
});
});
describe('value equals or less 0', () => {
const rotateValue: number = 0;
const expectedArray: number[] = [1, 2, 3, 4, 5, 6];
beforeEach(() => {
rotatedArray = arrayUtils.rotate(array, rotateValue);
});
it('shouldn\'t rotate array', () => {
assert.deepEqual(rotatedArray, expectedArray);
});
});
describe('empty array', () => {
const emptyArray: number[] = [];
const rotateValue: number = 5;
const expectedError: ReferenceErrorConstructor = ReferenceError;
let testFunc: () => void;
beforeEach(() => {
testFunc = () => arrayUtils.rotate(emptyArray, rotateValue);
});
it('should throw exception if array is empty', () => {
assert.throws(testFunc, expectedError);
});
});
});
});
``` | /content/code_sandbox/test/unit-tests/utils/ArrayUtils.spec.ts | xml | 2016-05-09T08:16:53 | 2024-08-16T19:43:07 | javascript-obfuscator | javascript-obfuscator/javascript-obfuscator | 13,358 | 2,100 |
```xml
import * as React from 'react';
import {
Animated,
ColorValue,
EasingFunction,
Platform,
StyleProp,
StyleSheet,
View,
ViewStyle,
} from 'react-native';
import useLatestCallback from 'use-latest-callback';
import BottomNavigationBar from './BottomNavigationBar';
import BottomNavigationRouteScreen from './BottomNavigationRouteScreen';
import { useInternalTheme } from '../../core/theming';
import type { ThemeProp } from '../../types';
import useAnimatedValueArray from '../../utils/useAnimatedValueArray';
import type { IconSource } from '../Icon';
import { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple';
export type BaseRoute = {
key: string;
title?: string;
focusedIcon?: IconSource;
unfocusedIcon?: IconSource;
badge?: string | number | boolean;
/**
* @deprecated In v5.x works only with theme version 2.
*/
color?: string;
accessibilityLabel?: string;
testID?: string;
lazy?: boolean;
};
type NavigationState<Route extends BaseRoute> = {
index: number;
routes: Route[];
};
type TabPressEvent = {
defaultPrevented: boolean;
preventDefault(): void;
};
type TouchableProps<Route extends BaseRoute> = TouchableRippleProps & {
key: string;
route: Route;
children: React.ReactNode;
borderless?: boolean;
centered?: boolean;
rippleColor?: ColorValue;
};
export type Props<Route extends BaseRoute> = {
/**
* Whether the shifting style is used, the active tab icon shifts up to show the label and the inactive tabs won't have a label.
*
* By default, this is `false` with theme version 3 and `true` when you have more than 3 tabs.
* Pass `shifting={false}` to explicitly disable this animation, or `shifting={true}` to always use this animation.
* Note that you need at least 2 tabs be able to run this animation.
*/
shifting?: boolean;
/**
* Whether to show labels in tabs. When `false`, only icons will be displayed.
*/
labeled?: boolean;
/**
* Whether tabs should be spread across the entire width.
*/
compact?: boolean;
/**
* State for the bottom navigation. The state should contain the following properties:
*
* - `index`: a number representing the index of the active route in the `routes` array
* - `routes`: an array containing a list of route objects used for rendering the tabs
*
* Each route object should contain the following properties:
*
* - `key`: a unique key to identify the route (required)
* - `title`: title of the route to use as the tab label
* - `focusedIcon`: icon to use as the focused tab icon, can be a string, an image source or a react component @renamed Renamed from 'icon' to 'focusedIcon' in v5.x
* - `unfocusedIcon`: icon to use as the unfocused tab icon, can be a string, an image source or a react component @supported Available in v5.x with theme version 3
* - `color`: color to use as background color for shifting bottom navigation @deprecatedProperty In v5.x works only with theme version 2.
* - `badge`: badge to show on the tab icon, can be `true` to show a dot, `string` or `number` to show text.
* - `accessibilityLabel`: accessibility label for the tab button
* - `testID`: test id for the tab button
*
* Example:
*
* ```js
* {
* index: 1,
* routes: [
* { key: 'music', title: 'Favorites', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'},
* { key: 'albums', title: 'Albums', focusedIcon: 'album' },
* { key: 'recents', title: 'Recents', focusedIcon: 'history' },
* { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' },
* ]
* }
* ```
*
* `BottomNavigation` is a controlled component, which means the `index` needs to be updated via the `onIndexChange` callback.
*/
navigationState: NavigationState<Route>;
/**
* Callback which is called on tab change, receives the index of the new tab as argument.
* The navigation state needs to be updated when it's called, otherwise the change is dropped.
*/
onIndexChange: (index: number) => void;
/**
* Callback which returns a react element to render as the page for the tab. Receives an object containing the route as the argument:
*
* ```js
* renderScene = ({ route, jumpTo }) => {
* switch (route.key) {
* case 'music':
* return <MusicRoute jumpTo={jumpTo} />;
* case 'albums':
* return <AlbumsRoute jumpTo={jumpTo} />;
* }
* }
* ```
*
* Pages are lazily rendered, which means that a page will be rendered the first time you navigate to it.
* After initial render, all the pages stay rendered to preserve their state.
*
* You need to make sure that your individual routes implement a `shouldComponentUpdate` to improve the performance.
* To make it easier to specify the components, you can use the `SceneMap` helper:
*
* ```js
* renderScene = BottomNavigation.SceneMap({
* music: MusicRoute,
* albums: AlbumsRoute,
* });
* ```
*
* Specifying the components this way is easier and takes care of implementing a `shouldComponentUpdate` method.
* Each component will receive the current route and a `jumpTo` method as it's props.
* The `jumpTo` method can be used to navigate to other tabs programmatically:
*
* ```js
* this.props.jumpTo('albums')
* ```
*/
renderScene: (props: {
route: Route;
jumpTo: (key: string) => void;
}) => React.ReactNode | null;
/**
* Callback which returns a React Element to be used as tab icon.
*/
renderIcon?: (props: {
route: Route;
focused: boolean;
color: string;
}) => React.ReactNode;
/**
* Callback which React Element to be used as tab label.
*/
renderLabel?: (props: {
route: Route;
focused: boolean;
color: string;
}) => React.ReactNode;
/**
* Callback which returns a React element to be used as the touchable for the tab item.
* Renders a `TouchableRipple` on Android and `Pressable` on iOS.
*/
renderTouchable?: (props: TouchableProps<Route>) => React.ReactNode;
/**
* Get accessibility label for the tab button. This is read by the screen reader when the user taps the tab.
* Uses `route.accessibilityLabel` by default.
*/
getAccessibilityLabel?: (props: { route: Route }) => string | undefined;
/**
* Get badge for the tab, uses `route.badge` by default.
*/
getBadge?: (props: { route: Route }) => boolean | number | string | undefined;
/**
* Get color for the tab, uses `route.color` by default.
*/
getColor?: (props: { route: Route }) => string | undefined;
/**
* Get label text for the tab, uses `route.title` by default. Use `renderLabel` to replace label component.
*/
getLabelText?: (props: { route: Route }) => string | undefined;
/**
* Get lazy for the current screen. Uses true by default.
*/
getLazy?: (props: { route: Route }) => boolean | undefined;
/**
* Get the id to locate this tab button in tests, uses `route.testID` by default.
*/
getTestID?: (props: { route: Route }) => string | undefined;
/**
* Function to execute on tab press. It receives the route for the pressed tab, useful for things like scroll to top.
*/
onTabPress?: (props: { route: Route } & TabPressEvent) => void;
/**
* Function to execute on tab long press. It receives the route for the pressed tab, useful for things like custom action when longed pressed.
*/
onTabLongPress?: (props: { route: Route } & TabPressEvent) => void;
/**
* Custom color for icon and label in the active tab.
*/
activeColor?: string;
/**
* Custom color for icon and label in the inactive tab.
*/
inactiveColor?: string;
/**
* Whether animation is enabled for scenes transitions in `shifting` mode.
* By default, the scenes cross-fade during tab change when `shifting` is enabled.
* Specify `sceneAnimationEnabled` as `false` to disable the animation.
*/
sceneAnimationEnabled?: boolean;
/**
* The scene animation effect. Specify `'shifting'` for a different effect.
* By default, 'opacity' will be used.
*/
sceneAnimationType?: 'opacity' | 'shifting';
/**
* The scene animation Easing.
*/
sceneAnimationEasing?: EasingFunction | undefined;
/**
* Whether the bottom navigation bar is hidden when keyboard is shown.
* On Android, this works best when [`windowSoftInputMode`](path_to_url#wsoft) is set to `adjustResize`.
*/
keyboardHidesNavigationBar?: boolean;
/**
* Safe area insets for the tab bar. This can be used to avoid elements like the navigation bar on Android and bottom safe area on iOS.
* The bottom insets for iOS is added by default. You can override the behavior with this option.
*/
safeAreaInsets?: {
top?: number;
right?: number;
bottom?: number;
left?: number;
};
/**
* Style for the bottom navigation bar. You can pass a custom background color here:
*
* ```js
* barStyle={{ backgroundColor: '#694fad' }}
* ```
*/
barStyle?: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
/**
* Specifies the largest possible scale a label font can reach.
*/
labelMaxFontSizeMultiplier?: number;
style?: StyleProp<ViewStyle>;
activeIndicatorStyle?: StyleProp<ViewStyle>;
/**
* @optional
*/
theme?: ThemeProp;
/**
* TestID used for testing purposes
*/
testID?: string;
};
const FAR_FAR_AWAY = Platform.OS === 'web' ? 0 : 9999;
const SceneComponent = React.memo(({ component, ...rest }: any) =>
React.createElement(component, rest)
);
/**
* BottomNavigation provides quick navigation between top-level views of an app with a bottom navigation bar.
* It is primarily designed for use on mobile. If you want to use the navigation bar only see [`BottomNavigation.Bar`](BottomNavigationBar).
*
* By default BottomNavigation uses primary color as a background, in dark theme with `adaptive` mode it will use surface colour instead.
* See [Dark Theme](path_to_url#dark-theme) for more information.
*
* ## Usage
* ```js
* import * as React from 'react';
* import { BottomNavigation, Text } from 'react-native-paper';
*
* const MusicRoute = () => <Text>Music</Text>;
*
* const AlbumsRoute = () => <Text>Albums</Text>;
*
* const RecentsRoute = () => <Text>Recents</Text>;
*
* const NotificationsRoute = () => <Text>Notifications</Text>;
*
* const MyComponent = () => {
* const [index, setIndex] = React.useState(0);
* const [routes] = React.useState([
* { key: 'music', title: 'Favorites', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'},
* { key: 'albums', title: 'Albums', focusedIcon: 'album' },
* { key: 'recents', title: 'Recents', focusedIcon: 'history' },
* { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' },
* ]);
*
* const renderScene = BottomNavigation.SceneMap({
* music: MusicRoute,
* albums: AlbumsRoute,
* recents: RecentsRoute,
* notifications: NotificationsRoute,
* });
*
* return (
* <BottomNavigation
* navigationState={{ index, routes }}
* onIndexChange={setIndex}
* renderScene={renderScene}
* />
* );
* };
*
* export default MyComponent;
* ```
*/
const BottomNavigation = <Route extends BaseRoute>({
navigationState,
renderScene,
renderIcon,
renderLabel,
renderTouchable,
getLabelText,
getBadge,
getColor,
getAccessibilityLabel,
getTestID,
activeColor,
inactiveColor,
keyboardHidesNavigationBar = Platform.OS === 'android',
barStyle,
labeled = true,
style,
activeIndicatorStyle,
sceneAnimationEnabled = false,
sceneAnimationType = 'opacity',
sceneAnimationEasing,
onTabPress,
onTabLongPress,
onIndexChange,
shifting: shiftingProp,
safeAreaInsets,
labelMaxFontSizeMultiplier = 1,
compact: compactProp,
testID = 'bottom-navigation',
theme: themeOverrides,
getLazy = ({ route }: { route: Route }) => route.lazy,
}: Props<Route>) => {
const theme = useInternalTheme(themeOverrides);
const { scale } = theme.animation;
const compact = compactProp ?? !theme.isV3;
let shifting =
shiftingProp ?? (theme.isV3 ? false : navigationState.routes.length > 3);
if (shifting && navigationState.routes.length < 2) {
shifting = false;
console.warn(
'BottomNavigation needs at least 2 tabs to run shifting animation'
);
}
const focusedKey = navigationState.routes[navigationState.index].key;
/**
* Active state of individual tab item positions:
* -1 if they're before the active tab, 0 if they're active, 1 if they're after the active tab
*/
const tabsPositionAnims = useAnimatedValueArray(
navigationState.routes.map((_, i) =>
i === navigationState.index ? 0 : i >= navigationState.index ? 1 : -1
)
);
/**
* The top offset for each tab item to position it offscreen.
* Placing items offscreen helps to save memory usage for inactive screens with removeClippedSubviews.
* We use animated values for this to prevent unnecessary re-renders.
*/
const offsetsAnims = useAnimatedValueArray(
navigationState.routes.map(
// offscreen === 1, normal === 0
(_, i) => (i === navigationState.index ? 0 : 1)
)
);
/**
* List of loaded tabs, tabs will be loaded when navigated to.
*/
const [loaded, setLoaded] = React.useState<string[]>([focusedKey]);
if (!loaded.includes(focusedKey)) {
// Set the current tab to be loaded if it was not loaded before
setLoaded((loaded) => [...loaded, focusedKey]);
}
const animateToIndex = React.useCallback(
(index: number) => {
Animated.parallel([
...navigationState.routes.map((_, i) =>
Animated.timing(tabsPositionAnims[i], {
toValue: i === index ? 0 : i >= index ? 1 : -1,
duration: theme.isV3 || shifting ? 150 * scale : 0,
useNativeDriver: true,
easing: sceneAnimationEasing,
})
),
]).start(({ finished }) => {
if (finished) {
// Position all inactive screens offscreen to save memory usage
// Only do it when animation has finished to avoid glitches mid-transition if switching fast
offsetsAnims.forEach((offset, i) => {
if (i === index) {
offset.setValue(0);
} else {
offset.setValue(1);
}
});
}
});
},
[
shifting,
navigationState.routes,
offsetsAnims,
scale,
tabsPositionAnims,
sceneAnimationEasing,
theme,
]
);
React.useEffect(() => {
// Workaround for native animated bug in react-native@^0.57
// Context: path_to_url
animateToIndex(navigationState.index);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const prevNavigationState = React.useRef<NavigationState<Route>>();
React.useEffect(() => {
// Reset offsets of previous and current tabs before animation
offsetsAnims.forEach((offset, i) => {
if (
i === navigationState.index ||
i === prevNavigationState.current?.index
) {
offset.setValue(0);
}
});
animateToIndex(navigationState.index);
}, [navigationState.index, animateToIndex, offsetsAnims]);
const handleTabPress = useLatestCallback(
(event: { route: Route } & TabPressEvent) => {
onTabPress?.(event);
if (event.defaultPrevented) {
return;
}
const index = navigationState.routes.findIndex(
(route) => event.route.key === route.key
);
if (index !== navigationState.index) {
prevNavigationState.current = navigationState;
onIndexChange(index);
}
}
);
const jumpTo = useLatestCallback((key: string) => {
const index = navigationState.routes.findIndex(
(route) => route.key === key
);
prevNavigationState.current = navigationState;
onIndexChange(index);
});
const { routes } = navigationState;
const { colors } = theme;
return (
<View style={[styles.container, style]} testID={testID}>
<View style={[styles.content, { backgroundColor: colors?.background }]}>
{routes.map((route, index) => {
if (getLazy({ route }) !== false && !loaded.includes(route.key)) {
// Don't render a screen if we've never navigated to it
return null;
}
const focused = navigationState.index === index;
const previouslyFocused =
prevNavigationState.current?.index === index;
const countAlphaOffscreen =
sceneAnimationEnabled && (focused || previouslyFocused);
const renderToHardwareTextureAndroid =
sceneAnimationEnabled && focused;
const opacity = sceneAnimationEnabled
? tabsPositionAnims[index].interpolate({
inputRange: [-1, 0, 1],
outputRange: [0, 1, 0],
})
: focused
? 1
: 0;
const offsetTarget = focused ? 0 : FAR_FAR_AWAY;
const top = sceneAnimationEnabled
? offsetsAnims[index].interpolate({
inputRange: [0, 1],
outputRange: [0, offsetTarget],
})
: offsetTarget;
const left =
sceneAnimationType === 'shifting'
? tabsPositionAnims[index].interpolate({
inputRange: [-1, 0, 1],
outputRange: [-50, 0, 50],
})
: 0;
const zIndex = focused ? 1 : 0;
return (
<BottomNavigationRouteScreen
key={route.key}
pointerEvents={focused ? 'auto' : 'none'}
accessibilityElementsHidden={!focused}
importantForAccessibility={
focused ? 'auto' : 'no-hide-descendants'
}
index={index}
visibility={opacity}
style={[StyleSheet.absoluteFill, { zIndex }]}
collapsable={false}
removeClippedSubviews={
// On iOS, set removeClippedSubviews to true only when not focused
// This is an workaround for a bug where the clipped view never re-appears
Platform.OS === 'ios' ? navigationState.index !== index : true
}
>
<Animated.View
{...(Platform.OS === 'android' && {
needsOffscreenAlphaCompositing: countAlphaOffscreen,
})}
renderToHardwareTextureAndroid={renderToHardwareTextureAndroid}
style={[
styles.content,
{
opacity,
transform: [{ translateX: left }, { translateY: top }],
},
]}
>
{renderScene({ route, jumpTo })}
</Animated.View>
</BottomNavigationRouteScreen>
);
})}
</View>
<BottomNavigationBar
navigationState={navigationState}
renderIcon={renderIcon}
renderLabel={renderLabel}
renderTouchable={renderTouchable}
getLabelText={getLabelText}
getBadge={getBadge}
getColor={getColor}
getAccessibilityLabel={getAccessibilityLabel}
getTestID={getTestID}
activeColor={activeColor}
inactiveColor={inactiveColor}
keyboardHidesNavigationBar={keyboardHidesNavigationBar}
style={barStyle}
activeIndicatorStyle={activeIndicatorStyle}
labeled={labeled}
animationEasing={sceneAnimationEasing}
onTabPress={handleTabPress}
onTabLongPress={onTabLongPress}
shifting={shifting}
safeAreaInsets={safeAreaInsets}
labelMaxFontSizeMultiplier={labelMaxFontSizeMultiplier}
compact={compact}
testID={`${testID}-bar`}
theme={theme}
/>
</View>
);
};
/**
* Function which takes a map of route keys to components.
* Pure components are used to minimize re-rendering of the pages.
* This drastically improves the animation performance.
*/
BottomNavigation.SceneMap = <Route extends BaseRoute>(scenes: {
[key: string]: React.ComponentType<{
route: Route;
jumpTo: (key: string) => void;
}>;
}) => {
return ({
route,
jumpTo,
}: {
route: Route;
jumpTo: (key: string) => void;
}) => (
<SceneComponent
key={route.key}
component={scenes[route.key ? route.key : '']}
route={route}
jumpTo={jumpTo}
/>
);
};
// @component ./BottomNavigationBar.tsx
BottomNavigation.Bar = BottomNavigationBar;
export default BottomNavigation;
const styles = StyleSheet.create({
container: {
flex: 1,
overflow: 'hidden',
},
content: {
flex: 1,
},
});
``` | /content/code_sandbox/src/components/BottomNavigation/BottomNavigation.tsx | xml | 2016-10-19T05:56:53 | 2024-08-16T08:48:04 | react-native-paper | callstack/react-native-paper | 12,646 | 4,971 |
```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.
~
-->
<window xmlns="path_to_url"
class="com.haulmont.cuba.web.app.ui.serverlogviewer.LogDownloadOptionsWindow"
messagesPack="com.haulmont.cuba.web.app.ui.serverlogviewer"
caption="msg://log.download.options">
<layout spacing="true">
<hbox spacing="true" id="remoteContextBox">
<label value="msg://log.remoteContext" align="MIDDLE_CENTER"/>
<lookupField id="remoteContextField" required="true" width="200px"/>
</hbox>
<label id="sizeNotificationLabel"/>
<hbox spacing="true" align="MIDDLE_RIGHT">
<button id="downloadTailBtn" caption="msg://log.downloadTail" invoke="downloadTail"/>
<button id="downloadFullBtn" caption="msg://log.downloadFull" invoke="downloadFull"/>
<button caption="msg://actions.Cancel" invoke="cancel" icon="icons/cancel.png"/>
</hbox>
</layout>
</window>
``` | /content/code_sandbox/modules/web/src/com/haulmont/cuba/web/app/ui/serverlogviewer/log-download-options.xml | xml | 2016-03-24T07:55:56 | 2024-07-14T05:13:48 | cuba | cuba-platform/cuba | 1,342 | 269 |
```xml
import { PerformanceObserver } from 'perf_hooks'
import { warn } from '../../build/output/log'
import { bold } from '../picocolors'
const LONG_RUNNING_GC_THRESHOLD_MS = 15
const gcEvents: PerformanceEntry[] = []
const obs = new PerformanceObserver((list) => {
const entry = list.getEntries()[0]
gcEvents.push(entry)
if (entry.duration > LONG_RUNNING_GC_THRESHOLD_MS) {
warn(bold(`Long running GC detected: ${entry.duration.toFixed(2)}ms`))
}
})
/**
* Starts recording garbage collection events in the process and warn on long
* running GCs. To disable, call `stopObservingGc`.
*/
export function startObservingGc() {
obs.observe({ entryTypes: ['gc'] })
}
export function stopObservingGc() {
obs.disconnect()
}
/**
* Returns all recorded garbage collection events. This function will only
* return information from when `startObservingGc` was enabled and before
* `stopObservingGc` was called.
*/
export function getGcEvents() {
return gcEvents
}
``` | /content/code_sandbox/packages/next/src/lib/memory/gc-observer.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 238 |
```xml
import * as pulumi from "@pulumi/pulumi";
class FooResource extends pulumi.ComponentResource {
constructor(name: string, opts?: pulumi.ComponentResourceOptions) {
super("my:module:FooResource", name, {}, opts);
}
}
class ComponentResource extends pulumi.ComponentResource {
constructor(name: string, opts?: pulumi.ComponentResourceOptions) {
super("my:module:ComponentResource", name, {}, opts);
new FooResource("childrenamed", {
parent: this,
aliases: [{ name: "child" }],
});
}
}
new ComponentResource("comp");
``` | /content/code_sandbox/tests/integration/aliases/nodejs/rename_component_child/step2/index.ts | xml | 2016-10-31T21:02:47 | 2024-08-16T19:47:04 | pulumi | pulumi/pulumi | 20,743 | 125 |
```xml
// Styles
import './VStepper.sass'
// Components
import { VStepperSymbol } from './shared'
import { makeVStepperActionsProps, VStepperActions } from './VStepperActions'
import { VStepperHeader } from './VStepperHeader'
import { VStepperItem } from './VStepperItem'
import { VStepperWindow } from './VStepperWindow'
import { VStepperWindowItem } from './VStepperWindowItem'
import { VDivider } from '@/components/VDivider'
import { makeVSheetProps, VSheet } from '@/components/VSheet/VSheet'
// Composables
import { provideDefaults } from '@/composables/defaults'
import { makeDisplayProps, useDisplay } from '@/composables/display'
import { makeGroupProps, useGroup } from '@/composables/group'
// Utilities
import { computed, toRefs } from 'vue'
import { genericComponent, getPropertyFromItem, only, propsFactory, useRender } from '@/util'
// Types
import type { PropType } from 'vue'
import type { StepperItem, StepperItemSlot } from './VStepperItem'
export type VStepperSlot = {
prev: () => void
next: () => void
}
export type VStepperSlots = {
actions: VStepperSlot
default: VStepperSlot
header: StepperItem
'header-item': StepperItemSlot
icon: StepperItemSlot
title: StepperItemSlot
subtitle: StepperItemSlot
item: StepperItem
prev: never
next: never
} & {
[key: `header-item.${string}`]: StepperItemSlot
[key: `item.${string}`]: StepperItem
}
export const makeStepperProps = propsFactory({
altLabels: Boolean,
bgColor: String,
completeIcon: String,
editIcon: String,
editable: Boolean,
errorIcon: String,
hideActions: Boolean,
items: {
type: Array as PropType<readonly StepperItem[]>,
default: () => ([]),
},
itemTitle: {
type: String,
default: 'title',
},
itemValue: {
type: String,
default: 'value',
},
nonLinear: Boolean,
flat: Boolean,
...makeDisplayProps(),
}, 'Stepper')
export const makeVStepperProps = propsFactory({
...makeStepperProps(),
...makeGroupProps({
mandatory: 'force' as const,
selectedClass: 'v-stepper-item--selected',
}),
...makeVSheetProps(),
...only(makeVStepperActionsProps(), ['prevText', 'nextText']),
}, 'VStepper')
export const VStepper = genericComponent<VStepperSlots>()({
name: 'VStepper',
props: makeVStepperProps(),
emits: {
'update:modelValue': (v: unknown) => true,
},
setup (props, { slots }) {
const { items: _items, next, prev, selected } = useGroup(props, VStepperSymbol)
const { displayClasses, mobile } = useDisplay(props)
const { completeIcon, editIcon, errorIcon, color, editable, prevText, nextText } = toRefs(props)
const items = computed(() => props.items.map((item, index) => {
const title = getPropertyFromItem(item, props.itemTitle, item)
const value = getPropertyFromItem(item, props.itemValue, index + 1)
return {
title,
value,
raw: item,
}
}))
const activeIndex = computed(() => {
return _items.value.findIndex(item => selected.value.includes(item.id))
})
const disabled = computed(() => {
if (props.disabled) return props.disabled
if (activeIndex.value === 0) return 'prev'
if (activeIndex.value === _items.value.length - 1) return 'next'
return false
})
provideDefaults({
VStepperItem: {
editable,
errorIcon,
completeIcon,
editIcon,
prevText,
nextText,
},
VStepperActions: {
color,
disabled,
prevText,
nextText,
},
})
useRender(() => {
const sheetProps = VSheet.filterProps(props)
const hasHeader = !!(slots.header || props.items.length)
const hasWindow = props.items.length > 0
const hasActions = !props.hideActions && !!(hasWindow || slots.actions)
return (
<VSheet
{ ...sheetProps }
color={ props.bgColor }
class={[
'v-stepper',
{
'v-stepper--alt-labels': props.altLabels,
'v-stepper--flat': props.flat,
'v-stepper--non-linear': props.nonLinear,
'v-stepper--mobile': mobile.value,
},
displayClasses.value,
props.class,
]}
style={ props.style }
>
{ hasHeader && (
<VStepperHeader key="stepper-header">
{ items.value.map(({ raw, ...item }, index) => (
<>
{ !!index && (<VDivider />) }
<VStepperItem
{ ...item }
v-slots={{
default: slots[`header-item.${item.value}`] ?? slots.header,
icon: slots.icon,
title: slots.title,
subtitle: slots.subtitle,
}}
/>
</>
))}
</VStepperHeader>
)}
{ hasWindow && (
<VStepperWindow key="stepper-window">
{ items.value.map(item => (
<VStepperWindowItem
value={ item.value }
v-slots={{
default: () => slots[`item.${item.value}`]?.(item) ?? slots.item?.(item),
}}
/>
))}
</VStepperWindow>
)}
{ slots.default?.({ prev, next }) }
{ hasActions && (
slots.actions?.({ next, prev }) ?? (
<VStepperActions
key="stepper-actions"
onClick:prev={ prev }
onClick:next={ next }
v-slots={ slots }
/>
)
)}
</VSheet>
)
})
return {
prev,
next,
}
},
})
export type VStepper = InstanceType<typeof VStepper>
``` | /content/code_sandbox/packages/vuetify/src/components/VStepper/VStepper.tsx | xml | 2016-09-12T00:39:35 | 2024-08-16T20:06:39 | vuetify | vuetifyjs/vuetify | 39,539 | 1,402 |
```xml
import React from 'react'
import styles from './Bio.module.css'
import { getGravatarURL } from '../utils/getGravatarURL'
interface BioProps {
className?: string
}
function Bio(props: BioProps) {
let photoURL = getGravatarURL({
email: "test1@example.com",
size: 56,
})
return (
<div
className={`
${styles.Bio}
${props.className || ''}
`}>
<img src={photoURL} alt="Me" />
<p>
Create a blog with a single command, by{' '}
<a href="path_to_url">James K Nelson</a>.
<br />
Themed after Gatsby's blog starter and Dan Abramov's{' '}
<a href="path_to_url">overreacted.io</a>.<br />
Based on{' '}
<a href="path_to_url">
create-react-app
</a>
, <a href="path_to_url">MDX</a>, and{' '}
<a href="path_to_url">Navi</a>.
</p>
</div>
)
}
export default Bio
``` | /content/code_sandbox/examples/blog-typescript/src/components/Bio.tsx | xml | 2016-09-24T07:44:26 | 2024-07-11T14:52:12 | navi | frontarm/navi | 2,070 | 254 |
```xml
import { describe, expect, it, vi } from 'vitest';
import type { JsPackageManager } from 'storybook/internal/common';
import type { StorybookConfig } from 'storybook/internal/types';
import * as findUp from 'find-up';
import * as rendererHelpers from '../helpers/detectRenderer';
import { newFrameworks } from './new-frameworks';
vi.mock('find-up');
vi.mock('../helpers/detectRenderer', async (importOriginal) => ({
detectRenderer: vi.fn(
(await importOriginal<typeof import('../helpers/detectRenderer')>()).detectRenderer
),
}));
const checkNewFrameworks = async ({
packageManager = {},
main: mainConfig,
storybookVersion = '7.0.0',
rendererPackage,
}: {
packageManager?: any;
main?: Partial<StorybookConfig> & Record<string, unknown>;
storybookVersion?: string;
rendererPackage?: string;
}) => {
return newFrameworks.check({
packageManager,
mainConfig: mainConfig as any,
storybookVersion,
rendererPackage,
configDir: '',
mainConfigPath: ' ',
});
};
const getPackageManager = (packages: Record<string, string>) => {
return {
getPackageVersion(packageName) {
return new Promise((resolve) => {
Object.entries(packages).forEach(([name, version]) => {
if (packageName === name) {
resolve(version);
}
});
resolve(null);
});
},
retrievePackageJson: () =>
Promise.resolve({
dependencies: {},
devDependencies: packages,
}),
getAllDependencies: () => Promise.resolve(packages),
} as Partial<JsPackageManager>;
};
describe('new-frameworks fix', () => {
describe('should no-op', () => {
it('in sb 7 with correct structure already', async () => {
const packageManager = getPackageManager({
'@storybook/angular': '7.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: '@storybook/angular',
},
})
).resolves.toBeFalsy();
});
});
describe('should throw an error', () => {
it('in sb 7 with no main.js', async () => {
await expect(() =>
checkNewFrameworks({
main: undefined,
})
).rejects.toBeTruthy();
});
it('in sb 7 with vite < 3', async () => {
const packageManager = getPackageManager({
'@storybook/react': '7.0.0',
'@storybook/builder-vite': 'x.y.z',
vite: '2.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
rendererPackage: '@storybook/react',
main: {
framework: '@storybook/react',
core: {
builder: '@storybook/builder-vite',
},
},
})
).rejects.toBeTruthy();
});
});
describe('generic new-frameworks migration', () => {
it('should update to @storybook/react-webpack5', async () => {
const packageManager = getPackageManager({
'@storybook/react': '7.0.0-alpha.0',
'@storybook/builder-webpack5': '6.5.9',
'@storybook/manager-webpack5': '6.5.9',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: '@storybook/react',
core: {
builder: {
name: 'webpack5',
options: {
lazyCompilation: true,
},
},
},
},
})
).resolves.toEqual(
expect.objectContaining({
renderer: 'react',
frameworkPackage: '@storybook/react-webpack5',
dependenciesToAdd: ['@storybook/react-webpack5'],
dependenciesToRemove: ['@storybook/builder-webpack5', '@storybook/manager-webpack5'],
builderConfig: {
name: 'webpack5',
options: {
lazyCompilation: true,
},
},
})
);
});
it('should update to @storybook/react-vite', async () => {
const packageManager = getPackageManager({
'@storybook/react': '7.0.0-alpha.0',
'@storybook/builder-vite': '0.0.2',
vite: '3.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: '@storybook/react',
core: {
builder: '@storybook/builder-vite',
},
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/react-vite',
dependenciesToAdd: ['@storybook/react-vite'],
dependenciesToRemove: ['@storybook/builder-vite'],
})
);
});
it('should update only builders in @storybook/angular', async () => {
const packageManager = getPackageManager({
'@storybook/angular': '7.0.0-alpha.0',
'@storybook/builder-webpack5': '6.5.9',
'@storybook/manager-webpack5': '6.5.9',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: '@storybook/angular',
core: {
builder: {
name: 'webpack5',
options: {
lazyCompilation: true,
},
},
},
angularOptions: {
enableIvy: true,
enableNgcc: true,
},
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/angular',
dependenciesToAdd: [],
dependenciesToRemove: ['@storybook/builder-webpack5', '@storybook/manager-webpack5'],
frameworkOptions: {
enableIvy: true,
enableNgcc: true,
},
builderConfig: {
name: 'webpack5',
options: {
lazyCompilation: true,
},
},
})
);
});
it('should update to @storybook/preact-vite', async () => {
const packageManager = getPackageManager({
'@storybook/preact': '7.0.0-alpha.0',
'@storybook/builder-vite': '0.0.2',
vite: '3.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: '@storybook/preact',
core: {
builder: '@storybook/builder-vite',
},
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/preact-vite',
dependenciesToAdd: ['@storybook/preact-vite'],
dependenciesToRemove: ['@storybook/builder-vite'],
})
);
});
it('should update correctly when there is no builder', async () => {
const packageManager = getPackageManager({
'@storybook/vue3': '7.0.0',
'@storybook/builder-webpack5': '7.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: '@storybook/vue3',
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/vue3-webpack5',
dependenciesToAdd: ['@storybook/vue3-webpack5'],
dependenciesToRemove: ['@storybook/builder-webpack5'],
})
);
});
it('should update when there is no framework field in main', async () => {
const packageManager = getPackageManager({
'@storybook/vue3': '7.0.0',
'@storybook/manager-webpack5': '7.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/vue3-webpack5',
dependenciesToAdd: ['@storybook/vue3-webpack5'],
dependenciesToRemove: ['@storybook/manager-webpack5'],
hasFrameworkInMainConfig: false,
})
);
});
it('should update when the framework field has a legacy value', async () => {
const packageManager = getPackageManager({
'@storybook/vue3': '7.0.0',
'@storybook/manager-webpack5': '7.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: 'vue3',
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/vue3-webpack5',
dependenciesToAdd: ['@storybook/vue3-webpack5'],
dependenciesToRemove: ['@storybook/manager-webpack5'],
hasFrameworkInMainConfig: false,
})
);
});
it('should prompt when there are multiple renderer packages', async () => {
// there should be a prompt, which we mock the response
const detectRendererSpy = vi.spyOn(rendererHelpers, 'detectRenderer');
detectRendererSpy.mockReturnValueOnce(Promise.resolve('@storybook/react'));
const packageManager = getPackageManager({
'@storybook/react': '7.0.0',
'@storybook/vue': '7.0.0',
'@storybook/builder-vite': 'x.y.z',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
core: {
builder: '@storybook/builder-vite',
},
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/react-vite',
dependenciesToRemove: ['@storybook/builder-vite'],
})
);
expect(detectRendererSpy).toHaveBeenCalled();
});
it('should add framework field in main.js when everything is properly configured, but framework field in main.js is missing', async () => {
const packageManager = getPackageManager({
'@storybook/react': '7.0.0-alpha.0',
'@storybook/react-vite': '7.0.0-alpha.0',
});
// project contains vite.config.js
vi.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('vite.config.js'));
await expect(
checkNewFrameworks({
packageManager,
main: {},
})
).resolves.toEqual(
expect.objectContaining({
hasFrameworkInMainConfig: false,
frameworkPackage: '@storybook/react-vite',
})
);
});
it('should migrate to @storybook/web-components-webpack5 in a monorepo that contains the vite builder, but main.js has webpack5 in builder field', async () => {
vi.spyOn(rendererHelpers, 'detectRenderer').mockReturnValueOnce(
Promise.resolve('@storybook/web-components')
);
const packageManager = getPackageManager({
'@storybook/addon-essentials': '7.0.0-beta.48',
'@storybook/vue': '7.0.0-beta.48',
'@storybook/builder-vite': '7.0.0-beta.48',
'@storybook/builder-webpack5': '7.0.0-beta.48',
'@storybook/core-server': '7.0.0-beta.48',
'@storybook/manager-webpack5': '6.5.15',
'@storybook/react': '7.0.0-beta.48',
'@storybook/web-components': '7.0.0-beta.48',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
core: { builder: 'webpack5' },
},
})
).resolves.toEqual(
expect.objectContaining({
hasFrameworkInMainConfig: false,
frameworkPackage: '@storybook/web-components-webpack5',
})
);
});
});
describe('nextjs migration', () => {
it('skips in non-Next.js projects', async () => {
const packageManager = getPackageManager({
'@storybook/react': '7.0.0',
'@storybook/react-vite': '7.0.0',
});
const main = {
framework: '@storybook/react-vite',
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy();
});
it('skips if project uses Next.js < 12.0.0', async () => {
const packageManager = getPackageManager({
'@storybook/react': '7.0.0',
'@storybook/react-webpack5': '7.0.0',
next: '11.0.0',
});
const main = {
framework: '@storybook/react',
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy();
});
it('skips if project already has @storybook/nextjs set up', async () => {
vi.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js'));
const packageManager = getPackageManager({
'@storybook/react': '7.0.0',
'@storybook/nextjs': '7.0.0',
next: '12.0.0',
});
const main = {
framework: '@storybook/nextjs',
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy();
});
it('should update from @storybook/react-webpack5 to @storybook/nextjs', async () => {
const packageManager = getPackageManager({
'@storybook/react': '7.0.0-alpha.0',
'@storybook/react-webpack5': '7.0.0-alpha.0',
'@storybook/builder-webpack5': '7.0.0-alpha.0',
next: '12.0.0',
});
vi.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js'));
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: { name: '@storybook/react-webpack5', options: {} },
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/nextjs',
dependenciesToAdd: ['@storybook/nextjs'],
dependenciesToRemove: ['@storybook/builder-webpack5', '@storybook/react-webpack5'],
})
);
});
it('should remove legacy addons', async () => {
vi.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js'));
const packageManager = getPackageManager({
'@storybook/react': '7.0.0-alpha.0',
'@storybook/react-webpack5': '7.0.0-alpha.0',
next: '12.0.0',
'storybook-addon-next': '1.0.0',
'storybook-addon-next-router': '1.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: '@storybook/react-webpack5',
addons: ['storybook-addon-next', 'storybook-addon-next-router'],
},
})
).resolves.toEqual(
expect.objectContaining({
addonsToRemove: ['storybook-addon-next', 'storybook-addon-next-router'],
dependenciesToRemove: [
'@storybook/react-webpack5',
'storybook-addon-next',
'storybook-addon-next-router',
],
})
);
});
it('should move storybook-addon-next options and reactOptions to frameworkOptions', async () => {
vi.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js'));
const packageManager = getPackageManager({
'@storybook/react': '7.0.0-alpha.0',
'@storybook/react-webpack5': '7.0.0-alpha.0',
next: '12.0.0',
'storybook-addon-next': '1.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
framework: { name: '@storybook/react-webpack5' },
addons: [
{
name: 'storybook-addon-next',
options: {
nextConfigPath: '../next.config.js',
},
},
],
core: {
builder: {
name: '@storybook/builder-webpack5',
options: { lazyCompilation: true },
},
},
},
})
).resolves.toEqual(
expect.objectContaining({
frameworkPackage: '@storybook/nextjs',
dependenciesToAdd: ['@storybook/nextjs'],
dependenciesToRemove: ['@storybook/react-webpack5', 'storybook-addon-next'],
addonsToRemove: ['storybook-addon-next'],
frameworkOptions: {
nextConfigPath: '../next.config.js',
},
builderInfo: {
name: 'webpack5',
options: { lazyCompilation: true },
},
})
);
});
it('should migrate to @storybook/react-vite in Next.js project that uses vite builder', async () => {
vi.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js'));
const packageManager = getPackageManager({
'@storybook/react': '7.0.0-alpha.0',
'@storybook/builder-vite': '7.0.0-alpha.0',
next: '12.0.0',
'storybook-addon-next': '1.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
core: {
builder: '@storybook/builder-vite',
},
},
})
).resolves.toEqual(
expect.objectContaining({
addonsToRemove: [],
dependenciesToAdd: ['@storybook/react-vite'],
dependenciesToRemove: ['@storybook/builder-vite'],
frameworkPackage: '@storybook/react-vite',
})
);
});
});
describe('SvelteKit migration', () => {
it('skips in non-SvelteKit projects', async () => {
const packageManager = getPackageManager({
svelte: '3.53.1',
'@storybook/svelte': '7.0.0',
'@storybook/svelte-vite': '7.0.0',
});
const main = {
framework: '@storybook/svelte-vite',
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy();
});
it('skips if project uses SvelteKit < 1.0.0', async () => {
const packageManager = getPackageManager({
'@storybook/svelte': '7.0.0',
'@storybook/svelte-vite': '7.0.0',
'@sveltejs/kit': '0.9.0',
});
const main = {
framework: '@storybook/svelte-vite',
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy();
});
it('skips if project already has @storybook/sveltekit set up', async () => {
const packageManager = getPackageManager({
'@storybook/svelte': '7.0.0',
'@storybook/sveltekit': '7.0.0',
'@sveltejs/kit': '1.0.0',
});
const main = {
framework: '@storybook/svelte-vite',
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy();
});
it('from @storybook/svelte-vite', async () => {
const packageManager = getPackageManager({
'@storybook/svelte': '7.0.0',
'@storybook/svelte-vite': '7.0.0',
'@sveltejs/kit': '1.0.0',
});
const main = {
framework: '@storybook/svelte-vite',
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual(
expect.objectContaining({
dependenciesToAdd: ['@storybook/sveltekit'],
dependenciesToRemove: ['@storybook/svelte-vite'],
frameworkPackage: '@storybook/sveltekit',
})
);
});
it('from @storybook/svelte framework and @storybook/builder-vite builder', async () => {
const packageManager = getPackageManager({
'@storybook/svelte': '7.0.0',
'@storybook/builder-vite': '7.0.0',
'@sveltejs/kit': '1.0.0',
});
const main = {
framework: '@storybook/svelte',
core: { builder: '@storybook/builder-vite' },
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual(
expect.objectContaining({
dependenciesToAdd: ['@storybook/sveltekit'],
dependenciesToRemove: ['@storybook/builder-vite'],
frameworkPackage: '@storybook/sveltekit',
})
);
});
it('from @storybook/svelte framework and storybook-builder-vite builder', async () => {
const packageManager = getPackageManager({
'@storybook/svelte': '7.0.0',
'storybook-builder-vite': '0.2.5',
'@sveltejs/kit': '1.0.0',
});
const main = {
framework: '@storybook/svelte',
core: { builder: 'storybook-builder-vite' },
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual(
expect.objectContaining({
dependenciesToAdd: ['@storybook/sveltekit'],
dependenciesToRemove: ['storybook-builder-vite'],
frameworkPackage: '@storybook/sveltekit',
})
);
});
it('should migrate and remove svelteOptions', async () => {
const packageManager = getPackageManager({
'@storybook/svelte': '7.0.0',
'storybook-builder-vite': '0.2.5',
'@sveltejs/kit': '1.0.0',
});
const main = {
framework: '@storybook/svelte',
core: { builder: 'storybook-builder-vite' },
svelteOptions: { preprocess: 'preprocess' },
};
await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual(
expect.objectContaining({
dependenciesToAdd: ['@storybook/sveltekit'],
dependenciesToRemove: ['storybook-builder-vite'],
frameworkPackage: '@storybook/sveltekit',
rendererOptions: {},
})
);
});
it('should migrate to @storybook/svelte-webpack5 in SvelteKit project that uses Webpack5 builder', async () => {
const packageManager = getPackageManager({
'@storybook/svelte': '7.0.0-alpha.0',
'@storybook/builder-webpack5': '7.0.0-alpha.0',
'@sveltejs/kit': '1.0.0',
});
await expect(
checkNewFrameworks({
packageManager,
main: {
core: {
builder: '@storybook/builder-webpack5',
},
},
})
).resolves.toEqual(
expect.objectContaining({
addonsToRemove: [],
dependenciesToAdd: ['@storybook/svelte-webpack5'],
dependenciesToRemove: ['@storybook/builder-webpack5'],
frameworkPackage: '@storybook/svelte-webpack5',
})
);
});
});
});
``` | /content/code_sandbox/code/lib/cli-storybook/src/automigrate/fixes/new-frameworks.test.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 4,902 |
```xml
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Car } from '@domain/car';
import { Code } from '@domain/code';
import { CarService } from '@service/carservice';
interface Column {
field: string;
header: string;
}
@Component({
selector: 'virtual-scroll-doc',
template: ` <app-docsectiontext>
<p>
VirtualScroller is a performance-approach to handle huge data efficiently. Setting <i>virtualScroll</i> property as true and providing a <i>virtualScrollItemSize</i> in pixels would be enough to enable this functionality. It is also
suggested to use the same <i>virtualScrollItemSize</i> value on the tr element inside the body template.
</p>
</app-docsectiontext>
<p-deferred-demo (load)="loadDemoData()">
<div class="card">
<p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="400px" [virtualScroll]="true" [virtualScrollItemSize]="46">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" style="width: 20%;">
{{ col.header }}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex" let-columns="columns">
<tr style="height:46px">
<td *ngFor="let col of columns">
{{ rowData[col.field] }}
</td>
</tr>
</ng-template>
</p-table>
</div>
</p-deferred-demo>
<app-code [code]="code" selector="table-virtual-scroll-demo" [extFiles]="extFiles"></app-code>`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class VirtualScrollDoc {
cars!: Car[];
virtualCars!: Car[];
cols!: Column[];
constructor(private carService: CarService) {}
loadDemoData() {
this.cols = [
{ field: 'id', header: 'Id' },
{ field: 'vin', header: 'Vin' },
{ field: 'year', header: 'Year' },
{ field: 'brand', header: 'Brand' },
{ field: 'color', header: 'Color' }
];
this.cars = Array.from({ length: 10000 }).map((_, i) => this.carService.generateCar(i + 1));
this.virtualCars = Array.from({ length: 10000 });
}
code: Code = {
basic: `<p-table
[columns]="cols"
[value]="cars"
[scrollable]="true"
scrollHeight="400px"
[virtualScroll]="true"
[virtualScrollItemSize]="46">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" style="width: 20%;">
{{ col.header }}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex" let-columns="columns">
<tr style="height:46px">
<td *ngFor="let col of columns">
{{ rowData[col.field] }}
</td>
</tr>
</ng-template>
</p-table>`,
html: `<div class="card">
<p-table
[columns]="cols"
[value]="cars"
[scrollable]="true"
scrollHeight="400px"
[virtualScroll]="true"
[virtualScrollItemSize]="46">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" style="width: 20%;">
{{ col.header }}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex" let-columns="columns">
<tr style="height:46px">
<td *ngFor="let col of columns">
{{ rowData[col.field] }}
</td>
</tr>
</ng-template>
</p-table>
</div>`,
typescript: `import { Component, OnInit } from '@angular/core';
import { Car } from '@domain/car';
import { CarService } from '@service/carservice';
import { TableModule } from 'primeng/table';
import { CommonModule } from '@angular/common';
interface Column {
field: string;
header: string;
}
@Component({
selector: 'table-virtual-scroll-demo',
templateUrl: 'table-virtual-scroll-demo.html',
standalone: true,
imports: [TableModule, CommonModule],
providers: [CarService]
})
export class TableVirtualScrollDemo implements OnInit{
cars!: Car[];
virtualCars!: Car[];
cols!: Column[];
constructor(private carService: CarService) {}
ngOnInit() {
this.cols = [
{ field: 'id', header: 'Id' },
{ field: 'vin', header: 'Vin' },
{ field: 'year', header: 'Year' },
{ field: 'brand', header: 'Brand' },
{ field: 'color', header: 'Color' }
];
this.cars = Array.from({ length: 10000 }).map((_, i) => this.carService.generateCar(i + 1));
this.virtualCars = Array.from({ length: 10000 });
}
}`,
data: `{
id: 1
vin: tvACo,
brand: Norma,
color: Black,
year: 2002
}
...`,
service: ['CarService']
};
extFiles = [
{
path: 'src/domain/car.ts',
content: `
export interface Car {
id?;
vin?;
year?;
brand?;
color?;
price?;
saleDate?;
}`
}
];
}
``` | /content/code_sandbox/src/app/showcase/doc/table/virtualscrolldoc.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 1,312 |
```xml
import * as React from 'react';
import Attributes from 'shared/view/domain/ModelRecord/ModelRecordProps/Attributes/Attributes/Attributes';
import { IRow } from '../types';
interface ILocalProps {
row: IRow;
}
type AllProps = ILocalProps;
class AttributesColumn extends React.PureComponent<AllProps> {
public render() {
const {
row: {
experimentRun: { attributes },
},
} = this.props;
return <Attributes attributes={attributes} />;
}
}
export default AttributesColumn;
``` | /content/code_sandbox/webapp/client/src/features/experimentRuns/view/ExperimentRuns/Table/ColumnDefinitions/Attributes/AttributesColumn.tsx | xml | 2016-10-19T01:07:26 | 2024-08-14T03:53:55 | modeldb | VertaAI/modeldb | 1,689 | 116 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url">
<data>
<variable
name="item"
type="com.topjohnwu.magisk.view.TappableHeadlineItem" />
<variable
name="listener"
type="com.topjohnwu.magisk.view.TappableHeadlineItem.Listener" />
</data>
<com.google.android.material.card.MaterialCardView
style="@style/WidgetFoundation.Card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{() -> listener.onItemPressed(item)}"
tools:layout_gravity="center">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/tappable_icon"
style="@style/WidgetFoundation.Icon"
android:background="@null"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@{item.icon}"
tools:srcCompat="@drawable/ic_day_night" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:requiresFadingEdge="horizontal"
android:singleLine="true"
android:text="@{item.title}"
android:textAppearance="@style/AppearanceFoundation.Body"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/headline_icon_pointer"
app:layout_constraintStart_toEndOf="@+id/tappable_icon"
app:layout_constraintTop_toTopOf="parent"
tools:text="@string/settings_dark_mode_title" />
<ImageView
android:id="@+id/headline_icon_pointer"
style="@style/WidgetFoundation.Icon"
android:background="@null"
android:rotation="180"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_back_md2" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
</layout>
``` | /content/code_sandbox/app/apk/src/main/res/layout/item_tappable_headline.xml | xml | 2016-09-08T12:42:53 | 2024-08-16T19:41:25 | Magisk | topjohnwu/Magisk | 46,424 | 528 |
```xml
export interface NgSwAdapter {
newRequest(req: string | Request, init?: Object): Request;
newResponse(body: string | Blob, init?: Object): Response;
readonly scope: string;
}
export interface Clock {
dateNow(): number;
setTimeout(fn: Function, delay: number);
}
export class BrowserClock implements Clock {
dateNow(): number {
return Date.now();
}
setTimeout(fn: Function, delay: number) {
return setTimeout(fn, delay);
}
}
``` | /content/code_sandbox/service-worker/worker/src/worker/facade/adapter.ts | xml | 2016-01-25T17:36:44 | 2024-08-15T10:53:22 | mobile-toolkit | angular/mobile-toolkit | 1,336 | 106 |
```xml
import { UnavailabilityError } from 'expo-modules-core';
type ShareOptions = { title?: string; text?: string; url?: string };
export default {
async isAvailableAsync(): Promise<boolean> {
if (typeof navigator === 'undefined') {
return false;
}
return !!navigator.share;
},
async shareAsync(url: string, options: ShareOptions = {}): Promise<void> {
// NOTE: `navigator.share` is only available via HTTPS
if (navigator.share) {
await navigator.share({ ...options, url });
} else {
throw new UnavailabilityError('navigator', 'share');
}
},
};
``` | /content/code_sandbox/packages/expo-sharing/src/ExpoSharing.web.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 138 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="about_android">%1$s Android-forrit</string>
<string name="about_title">Um hugbnainn</string>
<string name="about_version">tgfa %1$s</string>
<string name="about_version_with_build">tgfa %1$s, byggingarnmer %2$s</string>
<string name="account_creation_failed">Ger notandaagangs mistkst</string>
<string name="account_icon">Tknmynd fyrir notandaagang</string>
<string name="account_not_found">Notandaagangur fannst ekki!</string>
<string name="action_edit">Breyta</string>
<string name="action_empty_notifications">Hreinsa allar tilkynningar</string>
<string name="action_empty_trashbin">Tma rusli</string>
<string name="action_send_share">Senda/Deila</string>
<string name="action_switch_grid_view">Reitasn</string>
<string name="action_switch_list_view">Listasn</string>
<string name="actionbar_mkdir">N mappa</string>
<string name="actionbar_move_or_copy">Fra ea afrita</string>
<string name="actionbar_open_with">Opna me</string>
<string name="actionbar_search">Leita</string>
<string name="actionbar_see_details">Nnar</string>
<string name="actionbar_send_file">Senda</string>
<string name="actionbar_settings">Stillingar</string>
<string name="actionbar_sort">Flokka</string>
<string name="active_user">Virkur notandi</string>
<string name="activities_no_results_headline">Engin virkni enn</string>
<string name="activities_no_results_message">Enn engir atburir bor vi vibtur, breytingar og deilingar.</string>
<string name="activity_chooser_send_file_title">Senda</string>
<string name="activity_chooser_title">Senda tengil til</string>
<string name="activity_icon">Virkni</string>
<string name="add_another_public_share_link">Bta vi rum tengli</string>
<string name="add_new_public_share">Bta vi njum opinberum tengli</string>
<string name="add_to_cloud">Bta vi %1$s</string>
<string name="advanced_settings">tarlegar stillingar</string>
<string name="allow_resharing">Leyfa endurdeilingu</string>
<string name="app_config_proxy_port_title">Gtt millijns</string>
<string name="app_widget_description">Snir einn vimtshluta af stjrnbori</string>
<string name="appbar_search_in">Leita %s</string>
<string name="assistant_screen_all_task_type">Allt</string>
<string name="assistant_screen_successful_task_text">Loki</string>
<string name="assistant_screen_unknown_task_status_text">ekkt</string>
<string name="associated_account_not_found">Tengdur notandaagangur fannst ekki!</string>
<string name="auth_access_failed">Agangur mistkst: %1$s</string>
<string name="auth_account_does_not_exist">Agangur er ekki enn til tkinu</string>
<string name="auth_account_not_new">Agangur fyrir sama notanda og vefjn er egar til staar tkinu</string>
<string name="auth_account_not_the_same">Notandanafni sem sett var inn samsvarar ekki notanda essa agangs</string>
<string name="auth_bad_oc_version_title">ekkjanleg tgfa af jni</string>
<string name="auth_connection_established">Tengingu hefur veri komi </string>
<string name="auth_fail_get_user_name">Vefjnninn inn er ekki a svara me rttu notandaaukenni, hafu samband vi kerfisstjra..</string>
<string name="auth_host_url">Vistfang jns https://</string>
<string name="auth_incorrect_address_title">Rangt sni vistfangi jns</string>
<string name="auth_incorrect_path_title">jnn finnst ekki!!!</string>
<string name="auth_no_net_conn_title">Engin nettenging</string>
<string name="auth_nossl_plain_ok_title">rugg tenging ekki tiltk.</string>
<string name="auth_not_configured_title">Gllu uppsetning jns</string>
<string name="auth_oauth_error">Aukenning mistkst</string>
<string name="auth_oauth_error_access_denied">Agangi hafna af aukenningarjni</string>
<string name="auth_redirect_non_secure_connection_title">ruggri tengingu endurbeint gegnum rugga lei.</string>
<string name="auth_secure_connection">ruggri tengingu komi </string>
<string name="auth_ssl_general_error_title">Mistkst a frumstilla SSL</string>
<string name="auth_ssl_unverified_server_title">Gate ekki sannreynt aukenni SSL-jnsins</string>
<string name="auth_testing_connection">Prfa tengingu</string>
<string name="auth_timeout_title">jnninn var of lengi a svara</string>
<string name="auth_trying_to_login">Reyni a skr inn</string>
<string name="auth_unauthorized">Rangt notandanafn ea lykilor.</string>
<string name="auth_unknown_error_exception_title">ekkt villa: %s</string>
<string name="auth_unknown_error_http_title">ekkt HTTP-villa kom upp!</string>
<string name="auth_unknown_error_title">ekkt villa kom upp.</string>
<string name="auth_unknown_host_title">Gat ekki fundi hsilvl</string>
<string name="auth_unsupported_multiaccount">%1$s styur ekki fjlaganga</string>
<string name="auth_wrong_connection_title">Gat ekki komi tengingu</string>
<string name="auto_upload_file_behaviour_kept_in_folder">haldi fram upprunalegri mppu, v hn er skrifvarin</string>
<string name="auto_upload_on_wifi">Aeins senda inn gjaldfrjlsu WiFi-neti</string>
<string name="auto_upload_path">/SjlfvirkInnsending</string>
<string name="autoupload_configure">Stilla</string>
<string name="autoupload_create_new_custom_folder">Ba til nja nja srsnina uppsetningu mppum</string>
<string name="autoupload_custom_folder">Settu upp srsnina mppu</string>
<string name="autoupload_disable_power_save_check">Gera orkusparnaarprfun virka</string>
<string name="autoupload_hide_folder">Fela mppu</string>
<string name="avatar">Aukennismynd</string>
<string name="away">Fjarverandi</string>
<string name="backup_settings">Stillingar ryggisafritunar</string>
<string name="battery_optimization_close">Loka</string>
<string name="battery_optimization_disable">Gera virkt</string>
<string name="battery_optimization_message">Tki itt gti veri me virka orkusparnaarstringu. Sjalfvirka innsendingaforriti (AutoUpload) virkar ekki rtt nema a etta forrit s undanegi slkri stringu.</string>
<string name="battery_optimization_title">Bestun fyrir rafhlunotkun</string>
<string name="brute_force_delay">Fresta vegna of margra tilrauna</string>
<string name="calendar">Dagatal</string>
<string name="calendars">Dagatl</string>
<string name="certificate_load_problem">a kom upp vandaml vi a lesa inn skilrki.</string>
<string name="changelog_dev_version">Breytingaskr runartgfu</string>
<string name="check_back_later_or_reload">Athugau aftur sar ea endurlestu.</string>
<string name="checkbox">Gtreitur</string>
<string name="choose_local_folder">Veldu stavra mppu</string>
<string name="choose_remote_folder">Veldu fjartengda mppu</string>
<string name="choose_template_helper_text">Veldu snimt og settu inn skrarheiti.</string>
<string name="choose_which_file">Veldu hvaa skr a halda!</string>
<string name="choose_widget">Veldu vimtshluta</string>
<string name="clear_notifications_failed">Mistkst a hreinsa tilkynningar.</string>
<string name="clear_status_message">Hreinsa stuskilabo</string>
<string name="clear_status_message_after">Hreinsa stuskilabo eftir</string>
<string name="clipboard_label">Texti afritaur r %1$s</string>
<string name="clipboard_no_text_to_copy">Fkk engan texta til a afrita klippispjald</string>
<string name="clipboard_text_copied">Tengill afritaur</string>
<string name="clipboard_unexpected_error">vnt villa kom upp vi afritun klippispjald</string>
<string name="common_back">Til baka</string>
<string name="common_cancel">Htta vi</string>
<string name="common_cancel_sync">Htta vi samstillingu</string>
<string name="common_choose_account">Veldu agang</string>
<string name="common_confirm">Stafesta</string>
<string name="common_copy">Afrita</string>
<string name="common_delete">Eya</string>
<string name="common_error">Villa</string>
<string name="common_error_out_memory">Ekki ngilegt minni</string>
<string name="common_error_unknown">ekkt villa</string>
<string name="common_loading">Hle inn</string>
<string name="common_next">Nsta</string>
<string name="common_no">Nei</string>
<string name="common_ok"> lagi</string>
<string name="common_pending"> bi</string>
<string name="common_remove">Eya</string>
<string name="common_rename">Endurnefna</string>
<string name="common_save">Vista</string>
<string name="common_send">Senda</string>
<string name="common_share">Deila</string>
<string name="common_skip">Sleppa</string>
<string name="common_switch_account">Skipta um notandaagang</string>
<string name="common_switch_to_account">Skipta notandaagang</string>
<string name="common_yes">J</string>
<string name="community_beta_headline">Prfau runartgfuna</string>
<string name="community_beta_text">etta inniheldur alla vntanlega eiginleika og er alveg jarinum hva varar stugleika. Villur geta komi upp, og ef slkt gerist, endilega tilkynntu um r.</string>
<string name="community_contribute_forum_forum">Spjallsvi</string>
<string name="community_contribute_forum_text">Hjlpau rum </string>
<string name="community_contribute_github_text">Yfirfaru, bttu og skrifau ka, skoau %1$s fyrir nnari upplsingar.</string>
<string name="community_contribute_headline">Vertu virkur ttakandi</string>
<string name="community_contribute_translate_text">forriti</string>
<string name="community_contribute_translate_translate">a</string>
<string name="community_dev_direct_download">Nu runartgfu sem beint niurhal</string>
<string name="community_dev_fdroid">Nu runartgfu f-Droid forritasafninu</string>
<string name="community_rc_fdroid">Nu fortgfu f-Droid forritasafninu</string>
<string name="community_rc_play_store">Nu fortgfu Google Play forritasafninu</string>
<string name="community_release_candidate_headline">tgfukanddat</string>
<string name="community_release_candidate_text">Prfunartgfan (RC) er skyndisamsetning verandi tgfu en er vnst a s tiltlulega stug. a a prfir uppsetninguna na tti a hjlpa til vi a n v markmii. Skru ig til prfana Play hugbnaarsafninu ea geru a handvirkt me v a fara \"tgfa\"-hlutann F-Droid.</string>
<string name="community_testing_bug_text">Fannstu villu? Skringilegheit?</string>
<string name="community_testing_headline">Hjlpau til vi prfanir</string>
<string name="community_testing_report_text">Tilkynntu um vandaml GitHub</string>
<string name="configure_new_media_folder_detection_notifications">Stilla</string>
<string name="confirm_removal">Fjarlgja stavra dulritun</string>
<string name="confirmation_remove_file_alert">Viltu virkilega eya \'%s\'?</string>
<string name="confirmation_remove_files_alert">Ertu viss um a viljir eya vldum atrium?</string>
<string name="confirmation_remove_folder_alert">Ertu viss um a viljir eya %1$s og innihaldi ess?</string>
<string name="confirmation_remove_folders_alert">Ertu viss um a viljir eya vldum atrium og innihaldi eirra?</string>
<string name="confirmation_remove_local">Einungis stavrt</string>
<string name="conflict_local_file">Skr tlvunni</string>
<string name="conflict_message_description">Ef velur bar tgfur, mun vera btt tlustaf aftan vi heiti afrituu skrrinnar.</string>
<string name="conflict_server_file">Skr netjni</string>
<string name="contact_backup_title">ryggisafrit tengilia</string>
<string name="contact_no_permission">Heimild til agangs a tengilium er nausynleg.</string>
<string name="contactlist_item_icon">Tknmynd notanda fyrir tengilialista</string>
<string name="contactlist_no_permission">Engin heimild gefin, ekkert flutt inn.</string>
<string name="contacts">Tengiliir</string>
<string name="contacts_backup_button">Taka ryggisafrit nna</string>
<string name="contacts_preferences_backup_scheduled">ryggisafritun er tlun og mun hefjast fljtlega</string>
<string name="contacts_preferences_import_scheduled">Innflutningur er tlun og mun hefjast fljtlega</string>
<string name="contacts_preferences_no_file_found">Engin skr fannst</string>
<string name="contacts_preferences_something_strange_happened">Gat ekki fundi sasta ryggisafriti itt!</string>
<string name="copied_to_clipboard">Afrita klippispjald</string>
<string name="copy_file_error">Villa kom upp vi a reyna a afrita essa skr ea mppu</string>
<string name="copy_file_invalid_into_descendent">Ekki er hgt a afrita mppu inn eina af undirmppum snum</string>
<string name="copy_file_invalid_overwrite">Skrin er egar til mttkumppunni</string>
<string name="copy_file_not_found">Get ekki afrita. Athugau hvort skrin s til.</string>
<string name="copy_link">Afrita tengil</string>
<string name="copy_move_to_encrypted_folder_not_supported">Ekki er stuningur enn vi afritun/frslu inn dulritaa mppu.</string>
<string name="could_not_download_image">Gat ekki stt alla myndina</string>
<string name="could_not_retrieve_shares">Tkst ekki a n sameignir</string>
<string name="could_not_retrieve_url">Tkst ekki a n sl</string>
<string name="create">Ba til</string>
<string name="create_dir_fail_msg">gat ekki bi til mppuna %1</string>
<string name="create_new">Ntt</string>
<string name="create_new_folder">N mappa</string>
<string name="credentials_disabled">Aukenni virk</string>
<string name="daily_backup">Dagleg ryggisafritun</string>
<string name="data_to_back_up">Ggn sem a taka ryggisafrit af</string>
<string name="default_credentials_wrong">Rng aukenni</string>
<string name="delete_account">Fjarlgja reikning</string>
<string name="delete_entries">Eya frslum</string>
<string name="delete_link">Eya tengli</string>
<string name="deselect_all">Afvelja allt</string>
<string name="destination_filename">Mttkuskrarheiti</string>
<string name="dev_version_new_version_available">N tgfa er tiltk</string>
<string name="dev_version_no_information_available">Engar upplsingar tiltkar</string>
<string name="dev_version_no_new_version_available">Engin n tgfa tiltk.</string>
<string name="dialog_close">Loka</string>
<string name="did_not_check_for_dupes">Athugai ekki me tvtk.</string>
<string name="digest_algorithm_not_available">etta reiknirit fyrir gtsummur er ekki tiltkt smanum num.</string>
<string name="direct_login_failed">Innskrning gegnum beinan tengil mistkst!</string>
<string name="direct_login_text">Skr inn me %1$s %2$s</string>
<string name="disable_new_media_folder_detection_notifications">Gera virkt</string>
<string name="dismiss">Hafna</string>
<string name="dismiss_notification_description">Afgreia tilkynningu</string>
<string name="displays_mnemonic">Birtir 12 ora agangssetninguna na</string>
<string name="dnd">ni ekki</string>
<string name="document_scan_export_dialog_images">Margar myndir</string>
<string name="document_scan_export_dialog_pdf">PDF-skr</string>
<string name="document_scan_export_dialog_title">Veldu tegund tflutnings</string>
<string name="document_scan_pdf_generation_failed">Ger PDF tkst ekki</string>
<string name="document_scan_pdf_generation_in_progress">tb PDF</string>
<string name="done">Loki</string>
<string name="dontClear">Ekki hreinsa</string>
<string name="download_cannot_create_file">Get ekki bi til skr tlvu</string>
<string name="download_download_invalid_local_file_name">gilt skrarheiti fyrir stavra skr</string>
<string name="download_latest_dev_version">Skja njustu runartgfuna</string>
<string name="downloader_download_failed_content">Gat ekki stt %1$s</string>
<string name="downloader_download_failed_credentials_error">Niurhal mistkst, skru ig inn aftur</string>
<string name="downloader_download_failed_ticker">Niurhal mistkst</string>
<string name="downloader_download_file_not_found">Skrin er ekki lengur tiltk jninum</string>
<string name="downloader_download_in_progress_content">%1$d%% Ski %2$s</string>
<string name="downloader_download_in_progress_ticker">Ski</string>
<string name="downloader_download_succeeded_content">%1$s niurhala</string>
<string name="downloader_download_succeeded_ticker">Niurhala</string>
<string name="downloader_not_downloaded_yet">Ekki enn bi a skja</string>
<string name="drawer_close">Loka hliarspjaldi</string>
<string name="drawer_community">Samflag</string>
<string name="drawer_header_background">Bakgrunnsmynd haus hliarspjalds</string>
<string name="drawer_item_activities">Agerir</string>
<string name="drawer_item_all_files">Allar skrr</string>
<string name="drawer_item_favorites">Eftirlti</string>
<string name="drawer_item_gallery">Margmilunarggn</string>
<string name="drawer_item_groupfolders">Hpamppur</string>
<string name="drawer_item_home">Heim</string>
<string name="drawer_item_notifications">Tilkynningar</string>
<string name="drawer_item_on_device"> tkinu</string>
<string name="drawer_item_recently_modified">Nleg tillaga</string>
<string name="drawer_item_shared">Sameiginlegt</string>
<string name="drawer_item_trashbin">eyddar skrr</string>
<string name="drawer_item_uploads_list">Innsendingar</string>
<string name="drawer_logout">Skr t</string>
<string name="drawer_open">Opna hliarspjald</string>
<string name="drawer_quota">%1$s af %2$s nota</string>
<string name="drawer_quota_unlimited">%s nota</string>
<string name="drawer_synced_folders">Sjlfvirk innsending</string>
<string name="e2e_not_yet_setup">Ekki bi a setja upp E2E</string>
<string name="e2e_offline">Ekki mgulegt n internettengingar</string>
<string name="ecosystem_apps_display_more">Meira</string>
<string name="ecosystem_apps_display_notes">Minnispunktar</string>
<string name="ecosystem_apps_display_talk">Spjalla</string>
<string name="ecosystem_apps_more">Fleiri Nextcloud-forrit</string>
<string name="ecosystem_apps_notes">Nextcloud-minnispunktar</string>
<string name="ecosystem_apps_talk">Nextcloud Talk</string>
<string name="email_pick_failed">Mistkst a velja tlvupstfang.</string>
<string name="encrypted">Setja sem dulrita</string>
<string name="end_to_end_encryption_confirm_button">Setja upp dulritun</string>
<string name="end_to_end_encryption_decrypting">Afkun</string>
<string name="end_to_end_encryption_dialog_close">Loka</string>
<string name="end_to_end_encryption_enter_password">Settu inn lykilori til a afka einkalykil.</string>
<string name="end_to_end_encryption_folder_not_empty">essi mappa er ekki tm.</string>
<string name="end_to_end_encryption_generating_keys">tb nja dulritunarlykla</string>
<string name="end_to_end_encryption_keywords_description">ll 12 orin saman gera mjg sterkt lykilor, annig a einungis getur skoa og nota dulrituu skrrnar nar. Endilega skrifau au niur og geymdu ruggum sta.</string>
<string name="end_to_end_encryption_not_enabled">Enda--enda dulritun virk jni.</string>
<string name="end_to_end_encryption_passphrase_title">Skrifau niur 12 ora dulritunarlykilori itt</string>
<string name="end_to_end_encryption_password">Lykilor</string>
<string name="end_to_end_encryption_retrieving_keys">Ski dulritunarlykla</string>
<string name="end_to_end_encryption_storing_keys">Geymi dulritunarlykla</string>
<string name="end_to_end_encryption_title">Setja upp dulritun</string>
<string name="end_to_end_encryption_unsuccessful">Gat ekki vista dulritunarlykla, reyndu aftur.</string>
<string name="end_to_end_encryption_wrong_password">Villa kom upp vi afkun. Rangt lykilor?</string>
<string name="enter_destination_filename">Settu inn heiti mttkuskrar</string>
<string name="enter_filename">Settu inn skrarheiti</string>
<string name="error__upload__local_file_not_copied">%1$s var ekki hgt a afrita stavru %2$s mppuna</string>
<string name="error_cant_bind_to_operations_service">Alvarleg villa: Ekki hgt a framkvma agerir</string>
<string name="error_choosing_date">Villa vi a velja dagsetningu</string>
<string name="error_comment_file">Villa vi a gera athugasemd vi skr</string>
<string name="error_crash_title">%1$s hrundi</string>
<string name="error_creating_file_from_template">Villa vi a ba til skr t fr snimti</string>
<string name="error_file_actions">Villa vi birtingu skraagera</string>
<string name="error_file_lock">Villa vi a breyta stu lsingar skr</string>
<string name="error_report_issue_action">Skrsla</string>
<string name="error_report_issue_text">Tilkynna um vandaml verkbeinakerfi? (krefst GitHub-agangs)</string>
<string name="error_retrieving_file">Villa vi a n skr</string>
<string name="error_retrieving_templates">Villa vi a n snimt</string>
<string name="error_showing_encryption_dialog">Villa vi a birta uppsetningarglugga dulritunar!</string>
<string name="error_starting_direct_camera_upload">Villa vi a rsa myndavl</string>
<string name="etm_accounts">Agangar</string>
<string name="etm_background_job_created">Bi til ann</string>
<string name="etm_background_job_name">Heiti verks</string>
<string name="etm_background_job_progress">Framvinda</string>
<string name="etm_background_job_state">Staa</string>
<string name="etm_background_job_user">Notandi</string>
<string name="etm_background_job_uuid">UUID</string>
<string name="etm_background_jobs">Verk bakgrunni</string>
<string name="etm_background_jobs_cancel_all">Htta vi ll verk</string>
<string name="etm_background_jobs_prune">Stfa virk verk</string>
<string name="etm_background_jobs_schedule_test_job">tla prufuverk</string>
<string name="etm_background_jobs_start_test_job">Hefja prufuverk</string>
<string name="etm_background_jobs_stop_test_job">Stva prufuverk</string>
<string name="etm_migrations">Yfirfrslur (uppfrsla forrits)</string>
<string name="etm_preferences">Kjrstillingar</string>
<string name="etm_title">Verkfrilegur prfunarhamur</string>
<string name="etm_transfer">Skraflutningur</string>
<string name="etm_transfer_enqueue_test_download">Setja niurhalsprfun bir</string>
<string name="etm_transfer_remote_path">Fjartengd sl</string>
<string name="etm_transfer_type">Fra</string>
<string name="etm_transfer_type_download">Skja</string>
<string name="etm_transfer_type_upload">Senda inn</string>
<string name="fab_label">Bta vi ea senda inn</string>
<string name="failed_to_download">Mistkst a senda skr niurhalsstringu</string>
<string name="failed_to_print">Mistkst a prenta skr</string>
<string name="failed_to_start_editor">Mistkst a rsa ritil</string>
<string name="failed_update_ui">Mistkst a uppfra vimti</string>
<string name="favorite">Bta Eftirlti</string>
<string name="favorite_icon">Eftirlti</string>
<string name="file_already_exists">Skrarheiti er egar til staar</string>
<string name="file_delete">Eya</string>
<string name="file_detail_activity_error">Villa vi a n virkni fyrir skr</string>
<string name="file_details_no_content">Mistkst a hlaa inn tarupplsingum</string>
<string name="file_icon">Skr</string>
<string name="file_keep">Halda</string>
<string name="file_list_empty">Sendu inn eitthva efni ea samstilltu vi tkin n!</string>
<string name="file_list_empty_favorite_headline">Ekkert er eftirlti enn</string>
<string name="file_list_empty_favorites_filter_list">Skrr og mppur sem merkir sem eftirlti birtast hr.</string>
<string name="file_list_empty_gallery">Fann engar myndir ea myndskei</string>
<string name="file_list_empty_headline">Engar skrr hr</string>
<string name="file_list_empty_headline_search">Engar niurstur essari mppu</string>
<string name="file_list_empty_headline_server_search">Engar niurstur</string>
<string name="file_list_empty_moving">Ekkert hr. getur btt vi mppu.</string>
<string name="file_list_empty_on_device">Skrr og mppur sem skir birtast hr.</string>
<string name="file_list_empty_recently_modified">Fann engar skrr sem breytt hefur veri sustu 7 daga</string>
<string name="file_list_empty_search">Er etta kannski einhverri annarri mppu?</string>
<string name="file_list_empty_shared">Skrr og mppur sem deilir birtast hr.</string>
<string name="file_list_empty_shared_headline">Engu deilt enn</string>
<string name="file_list_empty_unified_search_no_results">Engar niurstur fundust fyrir leitina na</string>
<string name="file_list_folder">mappa</string>
<string name="file_list_live">BEINT</string>
<string name="file_list_loading">Hle inn</string>
<string name="file_list_no_app_for_file_type">Ekkert forrit er uppsett til a mehndla essa tegund skra.</string>
<string name="file_list_seconds_ago">sekndum san</string>
<string name="file_management_permission">Heimilda er krafist</string>
<string name="file_management_permission_optional">Heimildir gagnageymslu</string>
<string name="file_migration_checking_destination">Athuga fangasta</string>
<string name="file_migration_cleaning">Hreinsun</string>
<string name="file_migration_dialog_title">Uppfri mppu fyrir geymslu gagna</string>
<string name="file_migration_directory_already_exists">Gagnamappa er egar til. Veldu eitt af eftirfarandi:</string>
<string name="file_migration_failed_dir_already_exists">Nextcloud-mappa er egar til staar</string>
<string name="file_migration_failed_not_enough_space">arf meira geymsluplss</string>
<string name="file_migration_failed_not_readable">Gat ekki lesi upprunaskrna</string>
<string name="file_migration_failed_not_writable">Gat ekki skrifa ttaksskr</string>
<string name="file_migration_failed_while_coping">Mistkst vi yfirfrslu</string>
<string name="file_migration_failed_while_updating_index">Mistkst a uppfra atriaskr</string>
<string name="file_migration_migrating">Fri ggn</string>
<string name="file_migration_ok_finished">Loki</string>
<string name="file_migration_override_data_folder">Skipta t</string>
<string name="file_migration_preparing">Undirb yfirfrslu...</string>
<string name="file_migration_restoring_accounts_configuration">Endurheimti agangsuppsetningar</string>
<string name="file_migration_saving_accounts_configuration">Vista agangsuppsetningar</string>
<string name="file_migration_source_not_readable">Viltu breyta mppu fyrir geymslurmi gagna yfir %1$s?\n\nAthugau: Skja arf ll ggn aftur.</string>
<string name="file_migration_source_not_readable_title">Upprunamappa er ekki lesanleg!</string>
<string name="file_migration_updating_index">Uppfri atriaskr</string>
<string name="file_migration_use_data_folder">Nota</string>
<string name="file_migration_waiting_for_unfinished_sync">B eftir fullri samstillingu</string>
<string name="file_not_found">Skr fannst ekki</string>
<string name="file_not_synced">Ekki tkst a samstilla skrna. Birti njustu tiltku tgfuna.</string>
<string name="file_rename">Endurnefna</string>
<string name="file_version_restored_error">Villa vi a endurheimta tgfu skrar!</string>
<string name="file_version_restored_successfully">Tkst a endurheimta tgfu skrar.</string>
<string name="filedetails_details">Nnar</string>
<string name="filedetails_download">Skja</string>
<string name="filedetails_export">Flytja t</string>
<string name="filedetails_renamed_in_upload_msg">Skr endurnefnd sem %1$s vi innsendingu</string>
<string name="filedetails_sync_file">Samstilla</string>
<string name="filedisplay_no_file_selected">Engin skr valin</string>
<string name="filename_empty">Skrarheiti m ekki vera tmt</string>
<string name="filename_forbidden_characters">leyfilegir stafir: / \\ < > : \" | ? *</string>
<string name="filename_forbidden_charaters_from_server">Skrarheiti inniheldur a minnsta kosti einn gildan staf</string>
<string name="filename_hint">Skrarheiti</string>
<string name="first_run_1_text">Haltu ggnum num ruggum og undir inni stjrn</string>
<string name="folder_already_exists">Mappa er egar til staar</string>
<string name="folder_confirm_create">Ba til</string>
<string name="folder_list_empty_headline">Engar mppur hr</string>
<string name="folder_picker_choose_button_text">Velja</string>
<string name="folder_picker_choose_caption_text">Veldu ttaksmppu</string>
<string name="folder_picker_copy_button_text">Afrita</string>
<string name="folder_picker_move_button_text">Fra</string>
<string name="forbidden_permissions"> hefur ekki heimild %s</string>
<string name="forbidden_permissions_copy">til a afrita essa skr</string>
<string name="forbidden_permissions_create">til a ba til essa skr</string>
<string name="forbidden_permissions_delete">til a eya essari skr</string>
<string name="forbidden_permissions_move">til a fra essa skr</string>
<string name="forbidden_permissions_rename">til a endurnefna essa skr</string>
<string name="foreground_service_upload">Sendi inn skrr</string>
<string name="foreign_files_fail">Ekki tkst a fra sumar skrr</string>
<string name="foreign_files_local_text">Stavrt: %1$s</string>
<string name="foreign_files_move">Fra allt</string>
<string name="foreign_files_remote_text">Fjartengt: %1$s</string>
<string name="foreign_files_success">Allar skrr voru frar</string>
<string name="forward">fram</string>
<string name="fourHours">4 klukkustundir</string>
<string name="hidden_file_name_warning">Heiti mun valda falinni skr</string>
<string name="hint_name">Heiti</string>
<string name="hint_note">Minnispunktur</string>
<string name="hint_password">Lykilor</string>
<string name="host_not_available">jnn er ekki tiltkur</string>
<string name="host_your_own_server">Hstu inn eigin jn</string>
<string name="icon_for_empty_list">Tkn fyrir tman lista</string>
<string name="icon_of_dashboard_widget">Tknmynd stjrnborshluta</string>
<string name="icon_of_widget_entry">Tknmynd vimtshlutafrslu</string>
<string name="image_editor_file_edited_suffix">breytti</string>
<string name="image_editor_flip_horizontal">Fletta lrtt</string>
<string name="image_editor_flip_vertical">Fletta lrtt</string>
<string name="image_editor_rotate_ccw">Sna rangslis</string>
<string name="image_editor_rotate_cw">Sna rttslis</string>
<string name="image_editor_unable_to_edit_image">Gat ekki breytt mynd.</string>
<string name="image_preview_filedetails">Nnar um skr</string>
<string name="image_preview_image_taking_conditions">Skilyri vi myndatku</string>
<string name="image_preview_unit_fnumber">/%s</string>
<string name="image_preview_unit_iso">ISO %s</string>
<string name="image_preview_unit_megapixel">%s MP</string>
<string name="image_preview_unit_millimetres">%s mm</string>
<string name="image_preview_unit_seconds">%s s</string>
<string name="in_folder"> mppunni %1$s</string>
<string name="instant_upload_existing">Senda lka inn fyrirliggjandi skrr</string>
<string name="instant_upload_on_charging">Einungis senda inn egar veri er a hlaa</string>
<string name="instant_upload_path">/BeinInnsending</string>
<string name="invalid_url">gild sl</string>
<string name="invisible">snilegt</string>
<string name="label_empty">Merki m ekki vera tmt</string>
<string name="last_backup">Sasta ryggisafrit: %1$s</string>
<string name="link">Tengill</string>
<string name="link_name">Heiti tengils</string>
<string name="link_share_allow_upload_and_editing">Leyfa innsendingu og breytingar</string>
<string name="link_share_editing">Breytingar</string>
<string name="link_share_file_drop">Slepping skra (einungis innsending)</string>
<string name="link_share_view_only">Einungis skoa</string>
<string name="list_layout">Framsetning sem listi</string>
<string name="load_more_results">Hlaa inn fleiri niurstum</string>
<string name="local_file_list_empty">a eru engar skrr essari mppu.</string>
<string name="local_file_not_found_message">Skr fannst ekki stavru skrakerfi</string>
<string name="local_folder_friendly_path">%1$s/%2$s</string>
<string name="local_folder_list_empty">a eru engar fleiri mppur.</string>
<string name="locate_folder">Stasetja mppu</string>
<string name="lock_expiration_info">Rennur t: %1$s</string>
<string name="lock_file">Lsa skr</string>
<string name="locked_by">Lst af %1$s</string>
<string name="locked_by_app">Lst af %1$s-forritinu</string>
<string name="log_send_mail_subject">%1$s atvikaskrr Android-forrita</string>
<string name="log_send_no_mail_app">Ekkert forrit fannst til a senda atvikaskrr. Settu upp tlvupstforrit.</string>
<string name="logged_in_as">Skr inn sem %1$s</string>
<string name="login">Skr inn</string>
<string name="logs_menu_delete">Eya atvikaskrm</string>
<string name="logs_menu_refresh">Endurnja</string>
<string name="logs_menu_search">Leita atvikaskrm</string>
<string name="logs_menu_send">Senda atvikaskrr me tlvupsti</string>
<string name="logs_status_filtered">Atvikaskrning: %1$d kB, fyrirspurn samsvarai %2$d / %3$d %4$d ms</string>
<string name="logs_status_loading">Hle inn</string>
<string name="logs_status_not_filtered">Atvikaskrning: %1$d kB, engin sa</string>
<string name="logs_title">Ageraskrr</string>
<string name="maintenance_mode">jnn er vihaldsham</string>
<string name="manage_space_clear_data">Hreinsa ggn</string>
<string name="manage_space_description">Stillingum, gagnagrunni og skilrkjum vefjns r ggnum %1$s verur eytt endanlega. \n\nSttar skrr vera ekki snertar.\n\netta ferli getur teki drjga stund.</string>
<string name="manage_space_title">Ssla me geymslurmi</string>
<string name="media_err_io">Gat ekki lesi margmilunarskrna</string>
<string name="media_err_malformed">Margmilunarskrin er me ranga kun</string>
<string name="media_err_timeout">Tilraun til a spila skr rann t tma</string>
<string name="media_err_unknown">Innbyggi margmilunarspilarinn rur ekki vi a spila essa margmilunarskr </string>
<string name="media_err_unsupported">studd margmilunarlyklun (codec)</string>
<string name="media_forward_description">Spla-hratt-fram hnappur</string>
<string name="media_notif_ticker">%1$s tnlistarspilari</string>
<string name="media_play_pause_description">Afspilun-ea-hl hnappur</string>
<string name="media_rewind_description">Spla-til-baka hnappur</string>
<string name="media_state_playing">%1$s ( spilun)</string>
<string name="menu_item_sort_by_date_newest_first">Njast fyrst</string>
<string name="menu_item_sort_by_date_oldest_first">Elsta fyrst</string>
<string name="menu_item_sort_by_name_a_z">A-</string>
<string name="menu_item_sort_by_name_z_a">-A</string>
<string name="menu_item_sort_by_size_biggest_first">strsta fyrst</string>
<string name="menu_item_sort_by_size_smallest_first">minnsta fyrst</string>
<string name="more">Meira</string>
<string name="move_file_error">Villa kom upp vi a reyna a fra essa skr ea mppu</string>
<string name="move_file_invalid_into_descendent">Ekki er hgt a fra mppu inn eina af undirmppum snum</string>
<string name="move_file_invalid_overwrite">Skrin er egar til mttkumppunni</string>
<string name="move_file_not_found">Get ekki frt skr. Athugau hvort hn s til.</string>
<string name="network_error_connect_timeout_exception">Villa kom upp mean bei var eftir jninum. Ekki var hgt a ljka agerinni.</string>
<string name="network_error_socket_exception">Villa kom upp vi a tengjast jninum</string>
<string name="network_error_socket_timeout_exception">Villa kom upp mean bei var eftir jninum. Ekki var hgt a ljka agerinni.</string>
<string name="network_host_not_available">Gat ekki loki ager. jnn ekki tiltkur.</string>
<string name="new_comment">N athugasemd</string>
<string name="new_media_folder_detected">Fann mppu me %1$s.</string>
<string name="new_media_folder_photos">mynd</string>
<string name="new_media_folder_videos">Myndskei</string>
<string name="new_notification">N tilkynning</string>
<string name="new_version_was_created">N tgfa var tbin</string>
<string name="no_actions">Engar agerir fyrir ennan notanda</string>
<string name="no_browser_available">Ekkert forrit tiltkt til a mehndla tengla</string>
<string name="no_calendar_exists">Ekkert dagatal er til staar</string>
<string name="no_email_app_available">Ekkert forrit er tiltkt sem getur mehndla tlvupstfng</string>
<string name="no_items">Engin atrii</string>
<string name="no_map_app_availble">Ekkert forrit er tiltkt sem getur mehndla landakort</string>
<string name="no_mutliple_accounts_allowed">Aeins leyfur einn notandaagangur</string>
<string name="no_pdf_app_available">Ekkert forrit tiltkt til a mehndla PDF-skrr</string>
<string name="no_send_app">Ekkert forrit er tiltkt sem getur sent vldu skrrnar</string>
<string name="note_could_not_sent">Gat ekki sent minnispunkt</string>
<string name="note_icon_hint">Tknmynd fyrir athugasemd</string>
<string name="notification_action_failed">Mistkst a framkvma ager.</string>
<string name="notification_channel_download_description">Snir framvindu niurhals</string>
<string name="notification_channel_download_name_short">Stt ggn</string>
<string name="notification_channel_file_sync_description">Snir framvindu og niurstur samstillingar skra</string>
<string name="notification_channel_file_sync_name">Skrasamstilling</string>
<string name="notification_channel_general_description">Birta tilkynningar fyrir njar gagnamppur og vumlkt</string>
<string name="notification_channel_general_name">Almennar tilkynningar</string>
<string name="notification_channel_media_description">Framvinda margmilunarspilara</string>
<string name="notification_channel_media_name">Margmilunarspilari</string>
<string name="notification_channel_push_description">Birta tilkynningar sem tt er t fr jninum: Ummli (mentions) athugasemdum, mttaka nrra sameigna, tilkynningar sendar inn af stjrnendum, o.fl.</string>
<string name="notification_channel_push_name">ti-tilkynningar</string>
<string name="notification_channel_upload_description">Snir framvindu innsendingar</string>
<string name="notification_channel_upload_name_short">Innsendingar</string>
<string name="notification_icon">Tilkynningatkn</string>
<string name="notifications_no_results_headline">Engar tilkynningar</string>
<string name="notifications_no_results_message">Athugau aftur sar.</string>
<string name="offline_mode">Engin internettenging</string>
<string name="oneHour">1 klukkustund</string>
<string name="online"> netinu</string>
<string name="online_status">Staa netinu</string>
<string name="outdated_server">Netjnninn er kominn a endimrkum lftma sns, endilega uppfru hann!</string>
<string name="overflow_menu">Valmynd me fleiru</string>
<string name="pass_code_configure_your_pass_code">Settu inn lykilka</string>
<string name="pass_code_configure_your_pass_code_explanation">Lykilkans verur krafist hvert skipti sem forriti er rst</string>
<string name="pass_code_enter_pass_code">Settu inn lykilkann inn</string>
<string name="pass_code_mismatch">Lykilkarnir eru ekki eins</string>
<string name="pass_code_reenter_your_pass_code">Settu aftur inn lykilkann inn</string>
<string name="pass_code_remove_your_pass_code">Eya agangskanum num</string>
<string name="pass_code_removed">Agangska eytt</string>
<string name="pass_code_stored">Geymdi lykilka</string>
<string name="pass_code_wrong">Rangur lykilki</string>
<string name="permission_allow">Leyfa</string>
<string name="permission_deny">Neita</string>
<string name="permission_storage_access">Krafist er vibtarheimilda til a senda inn og skja skrr.</string>
<string name="picture_set_as_no_app">Engin forrit fundust til a setja mynd</string>
<string name="pin_home">Festa upphafsskj</string>
<string name="pin_shortcut_label">Opna %1$s</string>
<string name="placeholder_fileSize">KB</string>
<string name="placeholder_filename">frtkutkn.txt</string>
<string name="placeholder_media_time">12:23:45</string>
<string name="placeholder_sentence">etta er frtkutkn</string>
<string name="placeholder_timestamp">e.h.</string>
<string name="player_stop">stva</string>
<string name="player_toggle">vxla</string>
<string name="power_save_check_dialog_message">S orkusparnaarprfun ger virk getur a leitt til ess a veri s a senda inn skrr egar mjg lti er eftir rafhlunni!</string>
<string name="pref_behaviour_entries_delete_file">eytt</string>
<string name="pref_behaviour_entries_keep_file">fram upprunalegri mppu</string>
<string name="pref_behaviour_entries_move">fr forritsmppu</string>
<string name="pref_instant_name_collision_policy_dialogTitle">Hva a gera ef skrin er egar til staar?</string>
<string name="pref_instant_name_collision_policy_entries_always_ask">Spyrja hvert sinn</string>
<string name="pref_instant_name_collision_policy_entries_cancel">Sleppa innsendingu</string>
<string name="pref_instant_name_collision_policy_entries_overwrite">Skrifa yfir fjartengda tgfu</string>
<string name="pref_instant_name_collision_policy_entries_rename">Endurnefna nja tgfu</string>
<string name="pref_instant_name_collision_policy_title">Hva a gera ef skrin er egar til staar?</string>
<string name="prefs_add_account">Bta vi notandaagangi</string>
<string name="prefs_calendar_contacts_no_store_error">Hvorki F-Droid n Google Play eru uppsett</string>
<string name="prefs_calendar_contacts_summary">Setja upp DAVx5 (ur ekkt sem DAVdroid) (v1.3.0+) fyrir ennan agang</string>
<string name="prefs_category_about">Um hugbnainn</string>
<string name="prefs_category_details">Nnar</string>
<string name="prefs_category_dev">Dev</string>
<string name="prefs_category_general">Almennt</string>
<string name="prefs_category_more">Meira</string>
<string name="prefs_daily_contact_backup_summary">Daglegt ryggisafrit af tengilium</string>
<string name="prefs_e2e_active">Enda--enda dulritun er virk!</string>
<string name="prefs_e2e_mnemonic">E2E minnistkni</string>
<string name="prefs_e2e_no_device_credentials">Til a birta minnishjlp skaltu virkja aukenningu tkisins.</string>
<string name="prefs_enable_media_scan_notifications">Birta tilkynningar vegna sknnunar eftir margmilunarefni</string>
<string name="prefs_enable_media_scan_notifications_summary">Lta vita um nfundnar mppur me margmilunarefni</string>
<string name="prefs_gpl_v2">GNU General Public notkunarleyfi, tgfa 2</string>
<string name="prefs_help">Hjlp</string>
<string name="prefs_imprint">Prenta</string>
<string name="prefs_instant_behaviour_dialogTitle">Upprunaleg skr verur</string>
<string name="prefs_instant_behaviour_title">Upprunaleg skr verur</string>
<string name="prefs_instant_upload_path_use_subfolders_title">Nota undirmppur</string>
<string name="prefs_instant_upload_subfolder_rule_title">Valkostir undirmappa</string>
<string name="prefs_keys_exist">Bta enda--enda dulritun vi etta forrit</string>
<string name="prefs_license">Notkunarleyfi</string>
<string name="prefs_lock">Lykilki forritsins</string>
<string name="prefs_lock_device_credentials_enabled">Aukenni tkis virkju</string>
<string name="prefs_lock_device_credentials_not_setup">Engin aukenni tkis hafa veri sett inn.</string>
<string name="prefs_lock_none">Ekkert</string>
<string name="prefs_lock_title">Verja forriti me</string>
<string name="prefs_lock_using_device_credentials">Aukenni tkis</string>
<string name="prefs_lock_using_passcode">Lykilka</string>
<string name="prefs_manage_accounts">Ssla me notendaaganga</string>
<string name="prefs_recommend">Mla me vi vin</string>
<string name="prefs_remove_e2e">Fjarlgja stavra dulritun</string>
<string name="prefs_setup_e2e">Setja upp enda--enda dulritun</string>
<string name="prefs_show_ecosystem_apps">Sna forritaskipti</string>
<string name="prefs_show_ecosystem_apps_summary">Tillgur Nextcloud-forrita flakkfyrirsgn</string>
<string name="prefs_show_hidden_files">Sna faldar skrr</string>
<string name="prefs_sourcecode">Nu grunnkann</string>
<string name="prefs_storage_path">Mappa fyrir geymslu gagna</string>
<string name="prefs_sycned_folders_summary">Ssla me mppur vegna sjlfvirkra innsendinga</string>
<string name="prefs_synced_folders_local_path_title">Stavr mappa</string>
<string name="prefs_synced_folders_remote_path_title">Fjartengd mappa</string>
<string name="prefs_theme_title">ema</string>
<string name="prefs_value_theme_dark">Dkkt</string>
<string name="prefs_value_theme_light">Ljst</string>
<string name="prefs_value_theme_system">Fylgja kerfinu</string>
<string name="preview_image_description">Forskoun myndar</string>
<string name="preview_image_error_no_local_file">a er engin stavr skr til a forskoa</string>
<string name="preview_image_error_unknown_format">Get ekki birt mynd</string>
<string name="preview_sorry">v miur</string>
<string name="privacy">Gagnaleynd</string>
<string name="public_share_name">Ntt nafn</string>
<string name="push_notifications_not_implemented">ti-tilkynningar eru virkar vegna samhfis vi sreignahugbna Google Play jnustu.</string>
<string name="push_notifications_old_login">Engar titilkynningar vegna trunnirnnar innskrningarsetu. hugau a setja aganginn inn inn aftur.</string>
<string name="push_notifications_temp_error">ti-tilkynningar eru ekki tiltkar essa stundina.</string>
<string name="qr_could_not_be_read">Ekki tkst a lesa QR-ka!</string>
<string name="recommend_subject">Prfau %1$s snjalltkinu nu!</string>
<string name="recommend_text">Mr langar til a bja r a nota %1$s snjalltkinu nu.\nSktu a hr: %2$s</string>
<string name="recommend_urls">%1$s ea %2$s</string>
<string name="refresh_content">Endurlesa efni</string>
<string name="reload">Endurhlaa</string>
<string name="remote">(fjartengt)</string>
<string name="remote_file_fetch_failed">Mistkst a finna skr!</string>
<string name="remove_e2e"> getur fjarlgt stavra enda--enda dulritun r essu forriti</string>
<string name="remove_fail_msg">Mistkst a eya</string>
<string name="remove_local_account">Fjarlgja stavran agang</string>
<string name="remove_local_account_details">Fjarlgja notandaagang af tki og eya llum stavrum skrm</string>
<string name="remove_notification_failed">Mistkst a fjarlgja tilkynningu.</string>
<string name="remove_push_notification">Fjarlgja</string>
<string name="remove_success_msg">Eytt</string>
<string name="rename_dialog_title">Settu inn ntt nafn</string>
<string name="rename_local_fail_msg">Gat endurnefnt stavrt afrit, prfau anna heiti</string>
<string name="rename_server_fail_msg">Ekki hgt a endurnefna, heiti er frteki</string>
<string name="request_account_deletion">Bija um a agangi s eytt</string>
<string name="request_account_deletion_button">Bija um eyingu</string>
<string name="request_account_deletion_details">Bija um endanlega eyingu agangs hj jnustuveitu</string>
<string name="reshare_not_allowed">Endurdeiling er ekki leyf</string>
<string name="resharing_is_not_allowed">Endurdeiling er ekki leyf</string>
<string name="resized_image_not_possible_download">Engin strarbreytt mynd boi. Skja alla myndina?</string>
<string name="restore">Endurheimta skr</string>
<string name="restore_backup">Endurheimta r ryggisafriti</string>
<string name="restore_button_description">Endurheimta eydda skr</string>
<string name="restore_selected">Endurheimta vali</string>
<string name="retrieving_file">Ski skr</string>
<string name="richdocuments_failed_to_load_document">Mistkst a hlaa inn skjali!</string>
<string name="scanQR_description">Skr inn me QR-ka</string>
<string name="scan_page">Skanna su</string>
<string name="screenshot_01_gridView_heading">Verndar ggnin n</string>
<string name="screenshot_01_gridView_subline">vinnuggn hst eigin vegum</string>
<string name="screenshot_02_listView_heading">Skoa og deila</string>
<string name="screenshot_02_listView_subline">allar agerir innan seilingar</string>
<string name="screenshot_03_drawer_heading">Virkni, sameignir, </string>
<string name="screenshot_03_drawer_subline">allt vi hendina</string>
<string name="screenshot_04_accounts_heading">Allir agangarnir nir</string>
<string name="screenshot_04_accounts_subline"> einum sta</string>
<string name="screenshot_05_autoUpload_heading">Sjlfvirk innsending</string>
<string name="screenshot_06_davdroid_subline">Samstilla me DAVx5</string>
<string name="search_error">Villa vi a skja leitarniurstur</string>
<string name="select_all">Velja allt</string>
<string name="select_one_template">Veldu eitt snimt</string>
<string name="select_template">Veldu snimt</string>
<string name="send">Senda</string>
<string name="send_share">Senda sameign</string>
<string name="sendbutton_description">Tknmynd sendihnappi</string>
<string name="set_as">Setja sem</string>
<string name="set_note">Setja minnispunkt</string>
<string name="set_picture_as">Nota mynd sem</string>
<string name="set_status">Setja stu</string>
<string name="set_status_message">Setja stuskilabo</string>
<string name="share">Deila</string>
<string name="share_dialog_title">Deiling</string>
<string name="share_expiration_date_format">%1$s</string>
<string name="share_expiration_date_label">Rennur t %1$s</string>
<string name="share_file">Deila %1$s</string>
<string name="share_group_clarification">%s hpurinn</string>
<string name="share_internal_link">Deila innri tengli</string>
<string name="share_internal_link_to_file_text">Innri deilingartengill virkar bara fyrir notendur sem eiga agang a essari skr</string>
<string name="share_internal_link_to_folder_text">Innri deilingartengill virkar bara fyrir notendur sem eiga agang a essari mppu</string>
<string name="share_known_remote_on_clarification"> %1$s</string>
<string name="share_link">Deila tengli</string>
<string name="share_link_empty_password"> verur a setja lykilor</string>
<string name="share_link_file_error">Villa kom upp vi a reyna a deila essari skr ea mppu.</string>
<string name="share_link_file_no_exist">Get ekki deilt. Athugau hvort skrin s til.</string>
<string name="share_link_forbidden_permissions">til a deila essari skr</string>
<string name="share_link_optional_password_title">Settu inn valkvtt lykilor</string>
<string name="share_link_password_title">Settu inn lykilor</string>
<string name="share_link_with_label">Tengill sameign(%1$s)</string>
<string name="share_no_expiration_date_label">Setja gildistma</string>
<string name="share_no_password_title">Skr lykilor</string>
<string name="share_password_title">Verja me lykilori</string>
<string name="share_permission_can_edit">Getur breytt</string>
<string name="share_permission_file_drop">Slepping skra</string>
<string name="share_permission_view_only">Einungis skoa</string>
<string name="share_permissions">Heimildir sameignar</string>
<string name="share_remote_clarification">%1$s (fjartengt)</string>
<string name="share_room_clarification">%1$s (samtal)</string>
<string name="share_search">Nafn, skjasambandsaukenni ea tlvupstfang </string>
<string name="share_send_new_email">Senda njan tlvupst</string>
<string name="share_send_note">Minnispunktur til vitakanda</string>
<string name="share_settings">Stillingar</string>
<string name="share_via_link_hide_download">Fela niurhal</string>
<string name="share_via_link_section_title">Deila tengli</string>
<string name="share_via_link_send_link_label">Senda tengil...</string>
<string name="share_via_link_unset_password">Endurstilla</string>
<string name="share_with_title">Deila me %1</string>
<string name="shared_avatar_desc">Aukennismynd fr deildum notanda</string>
<string name="shared_icon_share">Deila</string>
<string name="shared_icon_shared">deilt</string>
<string name="shared_icon_shared_via_link">deilt me tengli</string>
<string name="shared_with_you_by">Deilt me r af %s</string>
<string name="sharee_add_failed">Mistkst a bta vi deilingu</string>
<string name="show_images">Sna ljsmyndir</string>
<string name="show_video">Sna myndskei</string>
<string name="signup_with_provider">Skru ig hj jnustu</string>
<string name="single_sign_on_request_token" formatted="true">Leyfa %1$s a a f agang a %2$s Nextcloud-agangnum num?</string>
<string name="sort_by">Raa eftir</string>
<string name="ssl_validator_btn_details_hide">Fela</string>
<string name="ssl_validator_btn_details_see">Nnar</string>
<string name="ssl_validator_header">Ekki tkst a sannvotta aukenni jnsins</string>
<string name="ssl_validator_label_C">Land:</string>
<string name="ssl_validator_label_CN">Almennt heiti:</string>
<string name="ssl_validator_label_L">Stasetning:</string>
<string name="ssl_validator_label_O">Fyrirtki/stofnun:</string>
<string name="ssl_validator_label_OU">Deild (OU):</string>
<string name="ssl_validator_label_ST">Staa:</string>
<string name="ssl_validator_label_certificate_fingerprint">Fingrafar:</string>
<string name="ssl_validator_label_issuer">Gefi t af</string>
<string name="ssl_validator_label_signature">Undirskrift</string>
<string name="ssl_validator_label_signature_algorithm">Reiknirit:</string>
<string name="ssl_validator_label_subject">Gefi t fyrir</string>
<string name="ssl_validator_label_validity">Gildistmi</string>
<string name="ssl_validator_label_validity_from">Fr:</string>
<string name="ssl_validator_label_validity_to">Til:</string>
<string name="ssl_validator_no_info_about_error">- Engar upplsingar um villuna</string>
<string name="ssl_validator_not_saved">Gat ekki vista skilrki</string>
<string name="ssl_validator_null_cert">Ekki var hgt a birta etta skilrki.</string>
<string name="ssl_validator_question">Viltu samt treysta essu skilrki?</string>
<string name="ssl_validator_reason_cert_expired">- Skilrki jnsins er trunni</string>
<string name="ssl_validator_reason_cert_not_trusted">- Skilrki jnsins er ekki treyst</string>
<string name="ssl_validator_reason_cert_not_yet_valid">- Skilrki jnsins er me gildistma framtinni</string>
<string name="ssl_validator_reason_hostname_not_verified">- Slin samsvarar ekki vlarheitinu skilrkinu</string>
<string name="status_message">Stuskilabo</string>
<string name="storage_camera">Myndavl</string>
<string name="storage_choose_location">Veldu stasetningu gagnageymslu</string>
<string name="storage_description_default">Sjlfgefi</string>
<string name="storage_documents">Skjl</string>
<string name="storage_downloads">Stt ggn</string>
<string name="storage_internal_storage">Innbygg geymsla</string>
<string name="storage_movies">Kvikmyndir</string>
<string name="storage_music">Tnlist</string>
<string name="storage_permission_full_access">Fullur agangur</string>
<string name="storage_permission_media_read_only">Skrifvarinn gagnamiill</string>
<string name="storage_pictures">Ljsmyndir</string>
<string name="store_full_dev_desc">Nextcloud-kerfi er opi og frjlst, og heldur r vi stjrnvlinn.\netta er opinbera runartgfan, sem kemur me daglegan skammt af prfuum njum eiginleikum, sem aftur gtu mgulega valdi truflunum og gagnatapi. Forriti er fyrir notendur sem vilja taka tt a prfa og tilkynna um villur, ef r eiga sr sta. Ekki nota etta alvru vinnuumhverfi!\n\nBi opinbera runartgfan og venjulega tgfan eru tiltkar F-droid, og er hgt a setja r upp samhlia hvorri annarri.</string>
<string name="store_short_desc">Nextcloud-kerfi er opi og frjlst, og heldur r vi stjrnvlinn</string>
<string name="store_short_dev_desc">Nextcloud-kerfi er opi og frjlst, og heldur r vi stjrnvlinn (fortgfa fyrir hnnui)</string>
<string name="stream">Streyma me</string>
<string name="stream_not_possible_headline">Innra streymi er ekki mgulegt</string>
<string name="stream_not_possible_message">Endilega sktu frekar gagnamiil ea notau utanakomandi forrit.</string>
<string name="strict_mode">Strangur hamur: engar HTTP-tengingar leyfar!</string>
<string name="sub_folder_rule_day">r/Mnuur/Dagur</string>
<string name="sub_folder_rule_month">r/Mnuur</string>
<string name="sub_folder_rule_year">r</string>
<string name="subject_shared_with_you">\"%1$s\" hefur veri deilt me r</string>
<string name="subject_user_shared_with_you">%1$s deildi \"%2$s\" me r</string>
<string name="subtitle_photos_only">Einungis ljsmyndir</string>
<string name="subtitle_videos_only">Einungis myndskei</string>
<string name="suggest">Stinga upp </string>
<string name="sync_conflicts_in_favourites_ticker">rekstrar fundust</string>
<string name="sync_current_folder_was_removed">Mappan %1$ser ekki lengur til</string>
<string name="sync_fail_content">Gat ekki samstillt %1$s</string>
<string name="sync_fail_content_unauthorized">Rangt lykilor fyrir %1$s</string>
<string name="sync_fail_in_favourites_ticker">Skrr merktar fyrir samstillingu mistkust</string>
<string name="sync_fail_ticker">Samstilling mistkst</string>
<string name="sync_fail_ticker_unauthorized">Samstilling mistkst, skru ig inn aftur</string>
<string name="sync_file_nothing_to_do_msg">Efni skrr er egar samstillt</string>
<string name="sync_folder_failed_content">Ekki var hgt a ljka samstillingu %1$s mppunni</string>
<string name="sync_foreign_files_forgotten_explanation">Fr og me tgfu 1.3.16, eru skrr sem sendar eru inn fr essu tki afritaar inn stavru %1$s mppuna, til a koma veg fyrir gagnatap egar stk skr er samstillt vi marga notendaaganga.\n\nVegna essarar breytingar, hafa allar skrr sem innsendar voru me eldri tgfum essa forrits n veri afritaar inn %2$s mppuna. Hinsvegar kom villa veg fyrir a hgt vri a ljka agerinni mean samstilling fr fram notandaagangnum. getur anna hvort lti skrna/skrrnar vera eins og r eru n og fjarlgt tengilinn %3$s, ea frt skrna/skrrnar inn %1$s mppuna og haldi tenglinum %4$s.\n\nHr fyrir nean eru stavru skrrnar taldar upp, samt eim fjartengdu skrm %5$s sem r voru tengdar.</string>
<string name="sync_foreign_files_forgotten_ticker">Sumar stavrar skrr gleymdust</string>
<string name="sync_in_progress">Ski njustu tgfu myndarinnar.</string>
<string name="sync_not_enough_space_dialog_action_choose">Veldu a sem a samstilla</string>
<string name="sync_not_enough_space_dialog_action_free_space">Losau um geymsluplss</string>
<string name="sync_not_enough_space_dialog_placeholder">%1$s er %2$s, en a eru aeins %3$s tiltk tkinu.</string>
<string name="sync_not_enough_space_dialog_title">Ekki ngilegt plss</string>
<string name="sync_status_button">Hnappur fyrir stu samstillingar</string>
<string name="sync_string_files">Skrr</string>
<string name="synced_folder_settings_button">Stillingahnappur</string>
<string name="synced_folders_configure_folders">Stilla mppur</string>
<string name="synced_folders_new_info">Beinar innsendingar hafa veri algerlega endurhannaar. Endurstilltu sjlfvirkar innsendingar beint aalvalmyndinni\n\nNjttu gs af nju og tarlegu vimti sjlfvirkra innsendinga.</string>
<string name="synced_folders_no_results">Engar margmilunarmppur fundust</string>
<string name="synced_folders_preferences_folder_path">Fyrir %1$s</string>
<string name="synced_folders_type">Tegund</string>
<string name="synced_icon">Samstillt</string>
<string name="tags">Merki</string>
<string name="test_server_button">Prfa tengingu jns</string>
<string name="thirtyMinutes">30 mntur</string>
<string name="thisWeek"> essari viku</string>
<string name="thumbnail">Smmynd</string>
<string name="thumbnail_for_existing_file_description">Smmynd fyrirliggjandi skrar</string>
<string name="thumbnail_for_new_file_desc">Smmynd nrrar skrar</string>
<string name="timeout_richDocuments">Hlesla tekur lengri tma en bist var vi</string>
<string name="today"> dag</string>
<string name="trashbin_activity_title">eyddar skrr</string>
<string name="trashbin_empty_headline">Engar eyddar skrr</string>
<string name="trashbin_empty_message"> getur endurheimt eyddar skrr han.</string>
<string name="trashbin_file_not_deleted">Ekki tkst a eya %1$s skrnni!</string>
<string name="trashbin_file_not_restored">Ekki tkst a endurheimta %1$s skrna!</string>
<string name="trashbin_file_remove">Eya varanlega</string>
<string name="trashbin_loading_failed">Mistkst a hlaa inn ruslinu!</string>
<string name="trashbin_not_emptied">Ekki tkst a eya skrnum endanlega!</string>
<string name="unlock_file">Aflsa skr</string>
<string name="unread_comments">lesnar athugasemdir eru fyrirliggjandi</string>
<string name="unset_encrypted">Gera dulritun virka</string>
<string name="unshare_link_file_error">Villa kom upp vi a reyna a htta deilingu essari skr ea mppu.</string>
<string name="unshare_link_file_no_exist">Get ekki htt deilingu. Athugau hvort skrin s til.</string>
<string name="unshare_link_forbidden_permissions">til a htta deilingu essari skr</string>
<string name="unsharing_failed">Mistkst a htta deilingu</string>
<string name="untrusted_domain">Agangur gegnum vantreyst ln. Endilega kktu hjlparskjlin til a sj tarlegri upplsingar.</string>
<string name="update_link_file_error">Villa kom upp vi a reyna a uppfra sameignina.</string>
<string name="update_link_file_no_exist">Get ekki uppfrt. Athugau hvort skrin s til.</string>
<string name="update_link_forbidden_permissions">til a uppfra essa sameign</string>
<string name="updating_share_failed">Mistkst a uppfra sameign</string>
<string name="upload_action_failed_clear">Hreinsa lista yfir innsendingar sem mistkust</string>
<string name="upload_action_failed_retry">Prfa aftur innsendingar sem mistkust</string>
<string name="upload_cannot_create_file">Get ekki bi til skr tlvu</string>
<string name="upload_chooser_title">Senda inn fr</string>
<string name="upload_content_from_other_apps">Senda inn efni fr rum forritum</string>
<string name="upload_direct_camera_upload">Senda inn r myndavl</string>
<string name="upload_file_dialog_filename">Skrarheiti</string>
<string name="upload_file_dialog_filetype">Skrarger</string>
<string name="upload_file_dialog_filetype_googlemap_shortcut">Google Maps fltileiarskr(%s)</string>
<string name="upload_file_dialog_filetype_internet_shortcut">Internet-fltileiarskr(%s)</string>
<string name="upload_file_dialog_filetype_snippet_text">Textabtsskr(.txt)</string>
<string name="upload_file_dialog_title">Settu inn skrarheiti og skrategund fyrir innsendingu</string>
<string name="upload_files">Hlaa inn skrm</string>
<string name="upload_item_action_button">Agerarhnappur til a senda inn atrii</string>
<string name="upload_list_delete">Eya</string>
<string name="upload_list_empty_headline">Engar innsendingar tiltkar</string>
<string name="upload_list_empty_text_auto_upload">Sendu inn einhverjar myndir ea virkjau sjlfvirka innsendingu.</string>
<string name="upload_list_resolve_conflict">Leysa rekstur</string>
<string name="upload_local_storage_full">Stavr gagnageymsla er full</string>
<string name="upload_local_storage_not_copied">Skr var ekki hgt a afrita stavra gagnageymslu</string>
<string name="upload_lock_failed">Lsing mppu mistkst</string>
<string name="upload_old_android">Dulritun er aeins mguleg me >= Android 5.0</string>
<string name="upload_query_move_foreign_files">ngt plss hamlar v a hgt s a afrita valdar skrr %1$s mppuna. Viltu fra r anga stainn?</string>
<string name="upload_quota_exceeded">Geymslukvti er uppurinn</string>
<string name="upload_scan_doc_upload">Skanna skjal me myndavl</string>
<string name="upload_sync_conflict">rekstur samstillingu, leystu etta handvirkt</string>
<string name="upload_unknown_error">ekkt villa</string>
<string name="uploader_btn_alternative_text">Velja</string>
<string name="uploader_btn_upload_text">Senda inn</string>
<string name="uploader_error_message_no_file_to_upload">Mttekin ggn innihldu ekki gilda skr.</string>
<string name="uploader_error_message_read_permission_not_granted">%1$s hefur ekki heimild til a lesa mttekna skr</string>
<string name="uploader_error_message_source_file_not_copied">Gat ekki afrita skr brabirgamppu. Prfau a endursenda hana.</string>
<string name="uploader_error_message_source_file_not_found">Skr sem valin var til sendingar fannst ekki. Athugau hvort skrin s til</string>
<string name="uploader_error_title_file_cannot_be_uploaded">essa skr er ekki hgt a senda inn</string>
<string name="uploader_error_title_no_file_to_upload">Engin skr til a senda inn</string>
<string name="uploader_info_dirname">Heiti mppu</string>
<string name="uploader_top_message">Veldu innsendingarmppu</string>
<string name="uploader_upload_failed_content_single">Gat ekki sent inn %1$s</string>
<string name="uploader_upload_failed_credentials_error">Innsending mistkst, skru ig inn aftur</string>
<string name="uploader_upload_failed_sync_conflict_error">rekstur vi innsendingu skra</string>
<string name="uploader_upload_failed_sync_conflict_error_content">Veldu hvaa tgfu vilt nota af %1$s</string>
<string name="uploader_upload_failed_ticker">Innsending mistkst</string>
<string name="uploader_upload_files_behaviour">Valkostir innsendingar:</string>
<string name="uploader_upload_files_behaviour_move_to_nextcloud_folder">Flytja skr %1$s-mppu</string>
<string name="uploader_upload_files_behaviour_not_writable">upprunamappan er skrifvarin; skrin verur aeins send inn</string>
<string name="uploader_upload_files_behaviour_only_upload">Halda skr upprunamppu</string>
<string name="uploader_upload_files_behaviour_upload_and_delete_from_source">Eya skr r upprunamppu</string>
<string name="uploader_upload_forbidden_permissions">til a senda inn essa mppu</string>
<string name="uploader_upload_in_progress_content">%1$d%% Sendi inn %2$s</string>
<string name="uploader_upload_in_progress_ticker">Sendi inn</string>
<string name="uploader_upload_succeeded_content_single">%1$s var sent inn!</string>
<string name="uploader_wrn_no_account_quit_btn_text">Htta</string>
<string name="uploader_wrn_no_account_setup_btn_text">Uppsetning</string>
<string name="uploader_wrn_no_account_text">a eru engir %1$s agangar tkinu nu. Settu fyrst upp notandaagang.</string>
<string name="uploader_wrn_no_account_title">Enginn notandaagangur fannst</string>
<string name="uploads_view_group_current_uploads">Nverandi</string>
<string name="uploads_view_group_failed_uploads">Mistkst/Bur endurrsingar</string>
<string name="uploads_view_group_finished_uploads">Hlai inn</string>
<string name="uploads_view_group_manually_cancelled_uploads">Htt vi</string>
<string name="uploads_view_later_waiting_to_upload">B eftir a senda inn</string>
<string name="uploads_view_title">Innsendingar</string>
<string name="uploads_view_upload_status_cancelled">Htt vi</string>
<string name="uploads_view_upload_status_conflict">Stangast </string>
<string name="uploads_view_upload_status_failed_connection_error">Tengingarvilla</string>
<string name="uploads_view_upload_status_failed_credentials_error">Villa aukennum</string>
<string name="uploads_view_upload_status_failed_file_error">Villa skr</string>
<string name="uploads_view_upload_status_failed_folder_error">Villa mppu</string>
<string name="uploads_view_upload_status_failed_localfile_error">Skr finnst ekki tkinu</string>
<string name="uploads_view_upload_status_failed_permission_error">Agangsheimildavilla</string>
<string name="uploads_view_upload_status_failed_ssl_certificate_not_trusted">Vantreyst skilrki jns</string>
<string name="uploads_view_upload_status_fetching_server_version">N tgfu jns</string>
<string name="uploads_view_upload_status_service_interrupted">Forrit htti</string>
<string name="uploads_view_upload_status_succeeded">Loki</string>
<string name="uploads_view_upload_status_unknown_fail">ekkt villa</string>
<string name="uploads_view_upload_status_virus_detected">Vrus fannst skrnni. Ekki er hgt a ljka innsendingu!</string>
<string name="uploads_view_upload_status_waiting_exit_power_save_mode">B eftir a htt s orkusparnaarham</string>
<string name="uploads_view_upload_status_waiting_for_charging">B eftir hleslu</string>
<string name="uploads_view_upload_status_waiting_for_wifi">B eftir Wi-Fi tengingu n mlingar gagnamagns</string>
<string name="user_icon">Notandi</string>
<string name="user_info_address">Vistfang</string>
<string name="user_info_email">Tlvupstur</string>
<string name="user_info_phone">Smanmer</string>
<string name="user_info_twitter">Twitter</string>
<string name="user_info_website">Vefsvi</string>
<string name="user_information_retrieval_error">Villa vi a skja upplsingar um notanda</string>
<string name="userinfo_no_info_headline">Engar persnulegar upplsingar stilltar</string>
<string name="userinfo_no_info_text">Bttu nafni, mynd og tengiliaupplsingum forsuna na.</string>
<string name="username">Notandanafn</string>
<string name="version_dev_download">Skja</string>
<string name="wait_a_moment">Bddu augnablik</string>
<string name="wait_checking_credentials">Athuga geymd aukenni</string>
<string name="wait_for_tmp_copy_from_private_storage">Afrita skr r einkageymslu</string>
<string name="webview_version_check_alert_dialog_positive_button_title">Uppfra</string>
<string name="what_s_new_image">Mynd fyrir \'Hva er ntt\'</string>
<string name="whats_new_skip">Sleppa</string>
<string name="whats_new_title">(Ntt %s)</string>
<string name="whats_your_status">Hver er staan r?</string>
<string name="widgets_not_available">Vimtshlutar eru einungis boi %1$s 25 ea nrra</string>
<string name="widgets_not_available_title">Not available</string>
<string name="worker_download">Ski skrr</string>
<string name="write_email">Senda tlvupst</string>
<string name="wrong_storage_path">Gagnageymslumappa er ekki til!</string>
<plurals name="sync_fail_in_favourites_content">
<item quantity="one">Ekki var hgt a samstilla %1$d skr (rekstrar: %2$d)</item>
<item quantity="other">Ekki var hgt a samstilla %1$d skrr (rekstrar: %2$d)</item>
</plurals>
<plurals name="sync_foreign_files_forgotten_content">
<item quantity="one">Mistkst a afrita %1$d skr r %2$s mppunni yfir </item>
<item quantity="other">Mistkst a afrita %1$d skrr r %2$s mppunni yfir </item>
</plurals>
<plurals name="wrote_n_events_to">
<item quantity="one">Skrifai %1$d atburi %2$s</item>
<item quantity="other">Skrifai %1$d atburi %2$s</item>
</plurals>
<plurals name="processed_n_entries">
<item quantity="one">Vann r %d frslu.</item>
<item quantity="other">Vann r %d frslum.</item>
</plurals>
<plurals name="found_n_duplicates">
<item quantity="one">Fann %d tvteknar frslu.</item>
<item quantity="other">Fann %d tvteknar frslur.</item>
</plurals>
<plurals name="export_successful">
<item quantity="one">Flutti t %d skr</item>
<item quantity="other">Flutti t %d skrr</item>
</plurals>
<plurals name="export_failed">
<item quantity="one">Mistkst a flytja t %d skr</item>
<item quantity="other">Mistkst a flytja t %d skrr</item>
</plurals>
<plurals name="export_partially_failed">
<item quantity="one">Flutti t %d skr, sleppti afgangnum vegna villu</item>
<item quantity="other">Flutti t %d skrr, sleppti afgangnum vegna villu</item>
</plurals>
<plurals name="export_start">
<item quantity="one">%d skr verur flutt t. Skoau tilkynningu til a sj nnari upplsingar.</item>
<item quantity="other">%d skrr vera fluttar t. Skoau tilkynningu til a sj nnari upplsingar.</item>
</plurals>
<plurals name="file_list__footer__folder">
<item quantity="one">%1$d mappa</item>
<item quantity="other">%1$d mppur</item>
</plurals>
<plurals name="file_list__footer__file">
<item quantity="one">%1$d skr</item>
<item quantity="other">%1$d skrr</item>
</plurals>
<plurals name="synced_folders_show_hidden_folders">
<item quantity="one">Birta %1$d falda skr</item>
<item quantity="other">Birta %1$d faldar skrr</item>
</plurals>
<plurals name="items_selected_count">
<item quantity="one">%d vali</item>
<item quantity="other">%d vali</item>
</plurals>
</resources>
``` | /content/code_sandbox/app/src/main/res/values-is/strings.xml | xml | 2016-06-06T21:23:36 | 2024-08-16T18:22:36 | android | nextcloud/android | 4,122 | 21,708 |
```xml
import { tokens, Injector, commonTokens, PluginContext } from '@stryker-mutator/api/plugin';
import { disableTypeChecks } from '@stryker-mutator/instrumenter';
import { coreTokens } from '../di/index.js';
import { TSConfigPreprocessor } from './ts-config-preprocessor.js';
import { FilePreprocessor } from './file-preprocessor.js';
import { MultiPreprocessor } from './multi-preprocessor.js';
import { DisableTypeChecksPreprocessor } from './disable-type-checks-preprocessor.js';
createPreprocessor.inject = tokens(commonTokens.injector);
export function createPreprocessor(injector: Injector<PluginContext>): FilePreprocessor {
return new MultiPreprocessor([
injector.provideValue(coreTokens.disableTypeChecksHelper, disableTypeChecks).injectClass(DisableTypeChecksPreprocessor),
injector.injectClass(TSConfigPreprocessor),
]);
}
``` | /content/code_sandbox/packages/core/src/sandbox/create-preprocessor.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 184 |
```xml
import { AsyncLocalStorage } from 'node:async_hooks'
import type { RequestStore } from '../../client/components/request-async-storage.external'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { IncrementalCache } from './incremental-cache'
import { createPatchedFetcher } from './patch-fetch'
describe('createPatchedFetcher', () => {
it('should not buffer a streamed response', async () => {
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
let streamChunk: () => void
const readableStream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('stream start'))
streamChunk = () => {
controller.enqueue(new TextEncoder().encode('stream end'))
controller.close()
}
},
})
mockFetch.mockResolvedValue(new Response(readableStream))
const staticGenerationAsyncStorage =
new AsyncLocalStorage<StaticGenerationStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
// requestAsyncStorage does not need to provide a store for this test.
requestAsyncStorage: new AsyncLocalStorage<RequestStore>(),
staticGenerationAsyncStorage,
})
let resolveIncrementalCacheSet: () => void
const incrementalCacheSetPromise = new Promise<void>((resolve) => {
resolveIncrementalCacheSet = resolve
})
const incrementalCache = {
get: jest.fn(),
set: jest.fn(() => resolveIncrementalCacheSet()),
generateCacheKey: jest.fn(() => 'test-cache-key'),
lock: jest.fn(() => resolveIncrementalCacheSet),
} as unknown as IncrementalCache
// We only need to provide a few of the StaticGenerationStore properties.
const staticGenerationStore: Partial<StaticGenerationStore> = {
page: '/',
route: '/',
incrementalCache,
}
await staticGenerationAsyncStorage.run(
staticGenerationStore as StaticGenerationStore,
async () => {
const response = await patchedFetch('path_to_url {
cache: 'force-cache',
})
if (!response.body) {
throw new Error(`Response body is ${JSON.stringify(response.body)}.`)
}
const reader = response.body.getReader()
let result = await reader.read()
const textDecoder = new TextDecoder()
expect(textDecoder.decode(result.value)).toBe('stream start')
streamChunk()
result = await reader.read()
expect(textDecoder.decode(result.value)).toBe('stream end')
await incrementalCacheSetPromise
expect(incrementalCache.set).toHaveBeenCalledWith(
'test-cache-key',
{
data: {
body: btoa('stream startstream end'),
headers: {},
status: 200,
url: '', // the mocked response does not have a URL
},
kind: 'FETCH',
revalidate: 31536000, // default of one year
},
{
fetchCache: true,
fetchIdx: 1,
fetchUrl: 'path_to_url
revalidate: false,
tags: [],
}
)
}
)
// Setting a lower timeout than default, because the test will fail with a
// timeout when we regress and buffer the response.
}, 1000)
})
``` | /content/code_sandbox/packages/next/src/server/lib/patch-fetch.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 692 |
```xml
import typeDefs from './graphql/typeDefs';
import resolvers from './graphql/resolvers';
import * as permissions from './permissions';
import { setupMessageConsumers } from './messageBroker';
import { getSubdomain } from '@erxes/api-utils/src/core';
import { generateModels } from './connectionResolver';
import logs from './logUtils';
export default {
name: 'pricing',
permissions,
graphql: async () => {
return {
typeDefs: await typeDefs(),
resolvers,
};
},
apolloServerContext: async (context, req) => {
const subdomain = getSubdomain(req);
const models = await generateModels(subdomain);
context.subdomain = subdomain;
context.models = models;
return context;
},
onServerInit: async () => {},
setupMessageConsumers,
meta: {
permissions,
logs: { consumers: logs },
},
};
``` | /content/code_sandbox/packages/plugin-pricing-api/src/configs.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 196 |
```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="ja" original="../LocalizableStrings.resx">
<body>
<trans-unit id="AppDescription">
<source>Publisher for the .NET Platform</source>
<target state="translated">.NET Platform </target>
<note />
</trans-unit>
<trans-unit id="CmdNoLogo">
<source>Do not display the startup banner or the copyright message.</source>
<target state="translated"></target>
<note />
</trans-unit>
<trans-unit id="FrameworkOption">
<source>FRAMEWORK</source>
<target state="translated">FRAMEWORK</target>
<note />
</trans-unit>
<trans-unit id="FrameworkOptionDescription">
<source>The target framework to publish for. The target framework has to be specified in the project file.</source>
<target state="translated"> </target>
<note />
</trans-unit>
<trans-unit id="OutputOption">
<source>OUTPUT_DIR</source>
<target state="translated">OUTPUT_DIR</target>
<note />
</trans-unit>
<trans-unit id="OutputOptionDescription">
<source>The output directory to place the published artifacts in.</source>
<target state="translated"></target>
<note />
</trans-unit>
<trans-unit id="ManifestOption">
<source>MANIFEST</source>
<target state="translated">MANIFEST</target>
<note />
</trans-unit>
<trans-unit id="ManifestOptionDescription">
<source>The path to a target manifest file that contains the list of packages to be excluded from the publish step.</source>
<target state="translated"> </target>
<note />
</trans-unit>
<trans-unit id="NoBuildOptionDescription">
<source>Do not build the project before publishing. Implies --no-restore.</source>
<target state="translated">--no-restore </target>
<note />
</trans-unit>
<trans-unit id="RuntimeOptionDescription">
<source>The target runtime to publish for. This is used when creating a self-contained deployment.
The default is to publish a framework-dependent application.</source>
<target state="translated">
</target>
<note />
</trans-unit>
<trans-unit id="ConfigurationOptionDescription">
<source>The configuration to publish for. The default is 'Release' for NET 8.0 projects and above, but 'Debug' for older projects.</source>
<target state="translated">NET 8.0 'Release' 'Debug' </target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Cli/dotnet/commands/dotnet-publish/xlf/LocalizableStrings.ja.xlf | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 677 |
```xml
<beans xmlns="path_to_url"
xmlns:xsi="path_to_url"
xmlns:context="path_to_url"
xsi:schemaLocation=" path_to_url
path_to_url
path_to_url
path_to_url">
<bean class="com.ctrip.platform.dal.dao.client.DalTransactionalEnabler"/>
<context:component-scan base-package="com.ctrip.platform.dal.dao.annotation.javaConfig.abnormal" />
<bean id="TransactionAnnoAbnormalClass" class="com.ctrip.platform.dal.dao.annotation.javaConfig.abnormal.TransactionAnnoAbnormalClass"/>
</beans>
``` | /content/code_sandbox/dal-client/src/test/resources/transactionAbnormalTest.xml | xml | 2016-07-26T03:07:03 | 2024-08-12T03:28:05 | dal | ctripcorp/dal | 1,246 | 137 |
```xml
import {
DecryptedPayloadInterface,
EncryptedPayloadInterface,
KeySystemRootKeyInterface,
ItemsKeyInterface,
RootKeyInterface,
KeySystemItemsKeyInterface,
} from '@standardnotes/models'
export interface AbstractKeySplit<T = EncryptedPayloadInterface | DecryptedPayloadInterface> {
usesRootKey?: {
items: T[]
key: RootKeyInterface
}
usesKeySystemRootKey?: {
items: T[]
key: KeySystemRootKeyInterface
}
usesItemsKey?: {
items: T[]
key: ItemsKeyInterface | KeySystemItemsKeyInterface
}
usesRootKeyWithKeyLookup?: {
items: T[]
}
usesKeySystemRootKeyWithKeyLookup?: {
items: T[]
}
usesItemsKeyWithKeyLookup?: {
items: T[]
}
}
``` | /content/code_sandbox/packages/encryption/src/Domain/Split/AbstractKeySplit.ts | xml | 2016-12-05T23:31:33 | 2024-08-16T06:51:19 | app | standardnotes/app | 5,180 | 185 |
```xml
import * as _ from "lodash";
import {
sendContactsMessage,
sendCoreMessage,
sendProductsMessage
} from "../messageBroker";
export const getConfig = async (subdomain, code, defaultValue?) => {
return await sendCoreMessage({
subdomain,
action: "getConfig",
data: { code, defaultValue },
isRPC: true
});
};
export const getChildCategories = async (subdomain: string, categoryIds) => {
const childs = await sendProductsMessage({
subdomain,
action: "categories.withChilds",
data: { ids: categoryIds },
isRPC: true,
defaultValue: []
});
const catIds: string[] = (childs || []).map(ch => ch._id) || [];
return Array.from(new Set(catIds));
};
export const getChildTags = async (subdomain: string, tagIds) => {
const childs = await sendCoreMessage({
subdomain,
action: "tagWithChilds",
data: { query: { _id: { $in: tagIds } }, fields: { _id: 1 } },
isRPC: true,
defaultValue: []
});
const foundTagIds: string[] = (childs || []).map(ch => ch._id) || [];
return Array.from(new Set(foundTagIds));
};
export const checkCondition = async (
subdomain,
pdata,
condition,
productById
) => {
let categoryRes = true;
let tagRes = true;
let segmentRes = true;
let numberRes = true;
let checkUomRes = true;
if (
condition.gtCount ||
condition.ltCount ||
condition.gtUnitPrice ||
condition.ltUnitPrice
) {
numberRes = false;
if (condition.gtCount) {
if (pdata.quantity <= condition.gtCount) {
numberRes = true;
} else {
numberRes = false;
}
}
if (condition.ltCount) {
if (pdata.quantity >= condition.ltCount) {
numberRes = true;
} else {
numberRes = false;
}
}
if (condition.gtUnitPrice) {
if (pdata.unitPrice <= condition.gtUnitPrice) {
numberRes = true;
} else {
numberRes = false;
}
}
if (condition.ltUnitPrice) {
if (pdata.unitPrice >= condition.ltUnitPrice) {
numberRes = true;
} else {
numberRes = false;
}
}
}
if (!numberRes) {
return false;
}
if (condition.subUomType) {
checkUomRes = false;
const product = productById[pdata.productId];
if (product.subUoms && product.subUoms.length) {
const ratio = product.subUoms[0].ratio || 0;
if (ratio) {
const checkCount = Math.round((1 / ratio) * 100) / 100;
if (
(condition.subUomType === "lt" && pdata.quantity < checkCount) ||
(condition.subUomType === "gte" && pdata.quantity >= checkCount)
) {
checkUomRes = true;
}
}
} else {
checkUomRes = true;
}
}
if (!checkUomRes) {
return false;
}
if (condition.productCategoryIds && condition.productCategoryIds.length) {
categoryRes = false;
const product = productById[pdata.productId];
if (
!(condition.excludeProductIds || []).includes(product._id) &&
condition.calcedCatIds.includes(product.categoryId)
) {
categoryRes = true;
}
}
if (!categoryRes) {
return false;
}
if (condition.productTagIds && condition.productTagIds.length) {
tagRes = false;
const product = productById[pdata.productId];
if (
!(condition.excludeProductIds || []).includes(product._id) &&
_.intersection(condition.calcedTagIds, product.tagIds).length
) {
tagRes = true;
}
}
if (!tagRes) {
return false;
}
if (condition.segmentIds && condition.segmentIds.length) {
segmentRes = false;
for (const segmentId of condition.segmentIds) {
if (
await sendCoreMessage({
subdomain,
action: "isInSegment",
data: { segmentId, idToCheck: pdata.productId }
})
) {
segmentRes = true;
continue;
}
}
}
if (!segmentRes) {
return false;
}
return categoryRes && segmentRes && numberRes && checkUomRes && tagRes;
};
const getCustomerName = customer => {
if (!customer) {
return "";
}
if (customer.firstName && customer.lastName) {
return `${customer.firstName} - ${customer.lastName}`;
}
if (customer.firstName) {
return customer.firstName;
}
if (customer.lastName) {
return customer.lastName;
}
if (customer.primaryEmail) {
return customer.primaryEmail;
}
if (customer.primaryPhone) {
return customer.primaryPhone;
}
return "";
};
export const getCustomer = async (subdomain, deal) => {
const companyIds = await sendCoreMessage({
subdomain,
action: "conformities.savedConformity",
data: { mainType: "deal", mainTypeId: deal._id, relTypes: ["company"] },
isRPC: true,
defaultValue: []
});
if (companyIds.length > 0) {
const companies = await sendContactsMessage({
subdomain,
action: "companies.findActiveCompanies",
data: {
selector: { _id: { $in: companyIds } },
fields: { _id: 1, code: 1, primaryName: 1 }
},
isRPC: true,
defaultValue: []
});
if (companies.length) {
const company = companies[0];
return {
customerCode: company.code,
customerName: company.primaryName
};
}
}
const customerIds = await sendCoreMessage({
subdomain,
action: "conformities.savedConformity",
data: { mainType: "deal", mainTypeId: deal._id, relTypes: ["customer"] },
isRPC: true,
defaultValue: []
});
if (customerIds.length > 0) {
const customers = await sendContactsMessage({
subdomain,
action: "customers.findActiveCustomers",
data: {
selector: { _id: { $in: customerIds } },
fields: {
_id: 1,
code: 1,
firstName: 1,
lastName: 1,
primaryEmail: 1,
primaryPhone: 1
}
},
isRPC: true,
defaultValue: []
});
let customer = customers.find(c => c.code && c.code.match(/^\d{8}$/g));
if (customer) {
return {
customerCode: customer.code || "",
customerName: getCustomerName(customer)
};
} else {
if (customers.length) {
customer = customers[0];
return {
customerCode: customer.code || "",
customerName: getCustomerName(customer)
};
}
}
}
return {};
};
``` | /content/code_sandbox/packages/plugin-productplaces-api/src/utils/utils.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,600 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<import type="android.view.View" />
<import type="com.eventyay.organizer.utils.DateUtils" />
<import type="android.text.TextUtils"/>
<variable
name="user"
type="com.eventyay.organizer.data.user.User" />
</data>
<androidx.core.widget.NestedScrollView xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/profile_picture"
android:layout_width="@dimen/avatar_size"
android:layout_height="@dimen/avatar_size"
android:layout_gravity="center"
android:layout_margin="@dimen/spacing_medium"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:padding="@dimen/spacing_normal"
android:contentDescription="@string/profile_picture"
android:scaleType="centerCrop"
app:circleImageUrl="@{ user.avatarUrl }"
app:placeholder="@{ @drawable/ic_account_circle }" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/delete_profile_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_size_large"
app:fabSize="mini"
android:backgroundTint="@color/material_red"
app:layout_constraintRight_toRightOf="@id/profile_picture"
app:layout_constraintBottom_toBottomOf="@id/profile_picture"
android:visibility="@{ user.avatarUrl != null ? View.VISIBLE : View.GONE }"
app:srcCompat="@drawable/ic_delete_white" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/spacing_medium">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dedede"
android:padding="@dimen/spacing_small"
android:text="@string/profile"
android:textAppearance="@style/TextAppearance.AppCompat.Headline"
android:textColor="?android:textColorSecondary" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_clock }"
android:drawableLeft="@{ @drawable/ic_clock }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ "Joined: " + DateUtils.formatDateWithDefault(DateUtils.FORMAT_DAY_COMPLETE, user.createdAt) }' />
<TextView
android:id="@+id/organizer_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_email }"
android:drawableLeft="@{ @drawable/ic_email }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.email }' />
<TextView
android:id="@+id/organizer_contact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_phone }"
android:drawableLeft="@{ @drawable/ic_phone }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.contact }'
android:visibility='@{ TextUtils.isEmpty(user.contact) ? View.GONE : View.VISIBLE }' />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_server_sync }"
android:drawableLeft="@{ @drawable/ic_server_sync }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.isVerified ? @string/verified : @string/not_verified }' />
<TextView
android:id="@+id/resend_verification_mail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/resend_verification_mail"
android:textColor="@color/color_accent"
android:padding="@dimen/spacing_small"
android:visibility="@{user.isVerified ? View.GONE : View.VISIBLE}" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_info }"
android:drawableLeft="@{ @drawable/ic_info }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.details }'
android:visibility='@{ TextUtils.isEmpty(user.details) ? View.GONE : View.VISIBLE}' />
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnChangePassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="@dimen/spacing_small"
app:backgroundTint="@color/color_accent"
android:text="@string/change_password"
android:textAllCaps="true"
android:textColor="@android:color/white" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/spacing_medium"
android:visibility="@{user.facebookUrl != null || user.twitterUrl != null || user.googlePlusUrl != null || user.instagramUrl != null ? View.VISIBLE : View.GONE}">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dedede"
android:padding="@dimen/spacing_small"
android:text="@string/social_media_profiles"
android:textAppearance="@style/TextAppearance.AppCompat.Headline"
android:textColor="?android:textColorSecondary" />
<TextView
android:id="@+id/organizer_facebook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_facebook }"
android:drawableLeft="@{ @drawable/ic_facebook }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.facebookUrl }'
android:visibility="@{user.facebookUrl == null ? View.GONE : View.VISIBLE}" />
<TextView
android:id="@+id/organizer_twitter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_twitter }"
android:drawableLeft="@{ @drawable/ic_twitter }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.twitterUrl }'
android:visibility="@{user.twitterUrl == null ? View.GONE : View.VISIBLE}" />
<TextView
android:id="@+id/organizer_google_plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_google_plus }"
android:drawableLeft="@{ @drawable/ic_google_plus }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.googlePlusUrl }'
android:visibility="@{user.googlePlusUrl == null ? View.GONE : View.VISIBLE}" />
<TextView
android:id="@+id/organizer_instagram"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@{ @drawable/ic_instagram }"
android:drawableLeft="@{ @drawable/ic_instagram }"
android:drawablePadding="@dimen/spacing_small"
android:gravity="center_vertical"
android:padding="@dimen/spacing_small"
android:text='@{ user.instagramUrl }'
android:visibility="@{user.instagramUrl == null ? View.GONE : View.VISIBLE}" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</layout>
``` | /content/code_sandbox/app/src/main/res/layout/organizer_detail_layout.xml | xml | 2016-08-13T08:08:39 | 2024-08-06T13:58:48 | open-event-organizer-android | fossasia/open-event-organizer-android | 1,783 | 2,098 |
```xml
<project xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.mockito.powermock</groupId>
<artifactId>Mockito-PowerMock-Examples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<testng.version>6.14.3</testng.version>
<junit4.version>4.12</junit4.version>
<mockito-core.version>2.19.0</mockito-core.version>
<powermock.version>2.0.0-beta.5</powermock.version>
<java.version>10</java.version>
</properties>
<dependencies>
<!-- TestNG -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<!-- JUnit 4 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit4.version}</version>
<scope>test</scope>
</dependency>
<!-- Mockito 2 -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<scope>test</scope>
</dependency>
<!-- PowerMock TestNG Module -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<!-- PowerMock JUnit 4.4+ Module -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<!-- PowerMock Mockito2 API -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.22.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-testng</artifactId>
<version>2.22.0</version>
</dependency>
</dependencies>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>src/test/java/</additionalClasspathElement>
</additionalClasspathElements>
<!-- TestNG Test Fails when executed from command line with message
"Cannot use a threadCount parameter less than 1"
Works when threadCount is explicitly specified
path_to_url
<threadCount>5</threadCount>
</configuration>
</plugin>
</plugins>
</build>
</project>
``` | /content/code_sandbox/Mockito-PowerMock-Examples/pom.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 921 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
xmlns="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id="transactionProcess">
<startEvent id="start" />
<sequenceFlow sourceRef="start" targetRef="tx" />
<transaction id="tx">
<startEvent id="txStart" />
<parallelGateway id="fork" />
<sequenceFlow sourceRef="txStart" targetRef="fork" />
<sequenceFlow sourceRef="fork" targetRef="bookFlight" />
<userTask id="bookFlight"/>
<boundaryEvent id="compensateBookFlightEvt" name="Boundary event" attachedToRef="bookFlight">
<compensateEventDefinition />
</boundaryEvent>
<serviceTask id="undoBookFlight" isForCompensation="true"
activiti:class="org.activiti.engine.test.bpmn.event.compensate.helper.UndoService">
<extensionElements>
<activiti:field name="counterName" stringValue="undoBookFlight" />
</extensionElements>
</serviceTask>
<sequenceFlow sourceRef="fork" targetRef="innerTx" />
<sequenceFlow sourceRef="bookFlight" targetRef="outerEndSuccess" />
<transaction id="innerTx">
<startEvent id="innerTxStart" />
<sequenceFlow sourceRef="innerTxStart" targetRef="innerTxFork" />
<parallelGateway id="innerTxFork" />
<sequenceFlow sourceRef="innerTxFork" targetRef="innerTxbookHotel" />
<sequenceFlow sourceRef="innerTxFork" targetRef="innerTxbookFlight" />
<serviceTask id="innerTxbookHotel" activiti:expression="${true}">
<multiInstanceLoopCharacteristics isSequential="true">
<loopCardinality>5</loopCardinality>
</multiInstanceLoopCharacteristics>
</serviceTask>
<serviceTask id="innerTxbookFlight" activiti:expression="${true}"/>
<boundaryEvent id="innerTxcompensateBookHotelEvt" name="Boundary event" attachedToRef="innerTxbookHotel">
<compensateEventDefinition />
</boundaryEvent>
<boundaryEvent id="innerTxcompensateBookFlightEvt" name="Boundary event" attachedToRef="innerTxbookFlight">
<compensateEventDefinition />
</boundaryEvent>
<serviceTask id="innerTxundoBookHotel" isForCompensation="true"
activiti:class="org.activiti.engine.test.bpmn.event.compensate.helper.UndoService">
<extensionElements>
<activiti:field name="counterName" stringValue="innerTxundoBookHotel" />
</extensionElements>
</serviceTask>
<serviceTask id="innerTxundoBookFlight" isForCompensation="true"
activiti:class="org.activiti.engine.test.bpmn.event.compensate.helper.UndoService">
<extensionElements>
<activiti:field name="counterName" stringValue="innerTxundoBookFlight" />
</extensionElements>
</serviceTask>
<sequenceFlow sourceRef="innerTxbookHotel" targetRef="innerTxreceive" />
<receiveTask id="innerTxreceive" />
<sequenceFlow sourceRef="innerTxbookFlight" targetRef="innerTxaskCustomer" />
<userTask id="innerTxaskCustomer" activiti:assignee="kermit" />
<exclusiveGateway id="innerTxconfirmed" />
<sequenceFlow sourceRef="innerTxaskCustomer" targetRef="innerTxconfirmed" />
<sequenceFlow sourceRef="innerTxconfirmed" targetRef="innerTxsuccess">
<conditionExpression>${confirmed}</conditionExpression>
</sequenceFlow>
<sequenceFlow sourceRef="innerTxconfirmed" targetRef="innerTxfailure">
<conditionExpression>${not confirmed}</conditionExpression>
</sequenceFlow>
<endEvent id="innerTxsuccess" />
<endEvent id="innerTxfailure" >
<cancelEventDefinition id="innerTxcancelTx" />
</endEvent>
<association associationDirection="One" sourceRef="innerTxcompensateBookHotelEvt" targetRef="innerTxundoBookHotel" />
<association associationDirection="One" sourceRef="innerTxcompensateBookFlightEvt" targetRef="innerTxundoBookFlight" />
</transaction>
<boundaryEvent attachedToRef="innerTx" id="catchCancelInnerTx">
<cancelEventDefinition />
</boundaryEvent>
<receiveTask id="afterInnerCancellation" />
<receiveTask id="afterInnerSuccess" />
<sequenceFlow sourceRef="catchCancelInnerTx" targetRef="afterInnerCancellation" />
<sequenceFlow sourceRef="afterInnerCancellation" targetRef="outerEndInnerCancel" />
<sequenceFlow sourceRef="innerTx" targetRef="afterInnerSuccess" />
<sequenceFlow sourceRef="afterInnerSuccess" targetRef="outerEndSuccess" />
<endEvent id="outerEndSuccess" />
<endEvent id="outerEndInnerCancel" />
<association associationDirection="One" sourceRef="compensateBookFlightEvt" targetRef="undoBookFlight" />
</transaction>
<endEvent id="end" />
<sequenceFlow sourceRef="tx" targetRef="end" />
<boundaryEvent attachedToRef="tx" id="catchCancelTx">
<cancelEventDefinition id="calcel"/>
</boundaryEvent>
<endEvent id="cancelled" />
<sequenceFlow sourceRef="catchCancelTx" targetRef="cancelled" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/bpmn/subprocess/transaction/TransactionSubProcessTest.testNestedCancelInner.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 1,379 |
```xml
<manifest xmlns:android="path_to_url"
package="xiaofei.library.hermeseventbus">
<application
android:label="@string/app_name">
<service android:name="HermesEventBus$Service"/>
</application>
</manifest>
``` | /content/code_sandbox/hermes-eventbus/src/main/AndroidManifest.xml | xml | 2016-07-11T13:52:10 | 2024-08-15T11:36:01 | HermesEventBus | Xiaofei-it/HermesEventBus | 1,611 | 58 |
```xml
import { observer } from "mobx-react";
import { CloseIcon, BackIcon } from "outline-icons";
import { transparentize } from "polished";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { Dialog, DialogBackdrop, useDialogState } from "reakit/Dialog";
import styled, { DefaultTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { depths, s } from "@shared/styles";
import Flex from "~/components/Flex";
import NudeButton from "~/components/NudeButton";
import Scrollable from "~/components/Scrollable";
import Text from "~/components/Text";
import useMobile from "~/hooks/useMobile";
import usePrevious from "~/hooks/usePrevious";
import useUnmount from "~/hooks/useUnmount";
import { fadeAndScaleIn } from "~/styles/animations";
import Desktop from "~/utils/Desktop";
import ErrorBoundary from "./ErrorBoundary";
let openModals = 0;
type Props = {
children?: React.ReactNode;
isOpen: boolean;
fullscreen?: boolean;
title?: React.ReactNode;
style?: React.CSSProperties;
onRequestClose: () => void;
};
const Modal: React.FC<Props> = ({
children,
isOpen,
fullscreen = true,
title = "Untitled",
style,
onRequestClose,
}: Props) => {
const dialog = useDialogState({
animated: 250,
});
const [depth, setDepth] = React.useState(0);
const wasOpen = usePrevious(isOpen);
const isMobile = useMobile();
const { t } = useTranslation();
React.useEffect(() => {
if (!wasOpen && isOpen) {
setDepth(openModals++);
dialog.show();
}
if (wasOpen && !isOpen) {
setDepth(openModals--);
dialog.hide();
}
}, [dialog, wasOpen, isOpen]);
useUnmount(() => {
if (isOpen) {
openModals--;
}
});
if (!isOpen && !wasOpen) {
return null;
}
return (
<DialogBackdrop {...dialog}>
{(props) => (
<Backdrop $fullscreen={fullscreen} {...props}>
<Dialog
{...dialog}
aria-label={typeof title === "string" ? title : undefined}
preventBodyScroll
hideOnEsc
hideOnClickOutside={!fullscreen}
hide={onRequestClose}
>
{(props) =>
fullscreen || isMobile ? (
<Fullscreen
$nested={!!depth}
style={
isMobile
? undefined
: {
marginLeft: `${depth * 12}px`,
}
}
{...props}
>
<Content>
<Centered onClick={(ev) => ev.stopPropagation()} column>
{title && (
<Text size="xlarge" weight="bold">
{title}
</Text>
)}
<ErrorBoundary>{children}</ErrorBoundary>
</Centered>
</Content>
<Close onClick={onRequestClose}>
<CloseIcon size={32} />
</Close>
<Back onClick={onRequestClose}>
<BackIcon size={32} />
<Text>{t("Back")} </Text>
</Back>
</Fullscreen>
) : (
<Small {...props}>
<Centered
onClick={(ev) => ev.stopPropagation()}
column
reverse
>
<SmallContent style={style} shadow>
<ErrorBoundary component="div">{children}</ErrorBoundary>
</SmallContent>
<Header>
{title && <Text size="large">{title}</Text>}
<NudeButton onClick={onRequestClose}>
<CloseIcon />
</NudeButton>
</Header>
</Centered>
</Small>
)
}
</Dialog>
</Backdrop>
)}
</DialogBackdrop>
);
};
const Backdrop = styled(Flex)<{ $fullscreen?: boolean }>`
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: ${(props) =>
props.$fullscreen
? transparentize(0.25, props.theme.background)
: props.theme.modalBackdrop} !important;
z-index: ${depths.modalOverlay};
transition: opacity 50ms ease-in-out;
opacity: 0;
&[data-enter] {
opacity: 1;
}
`;
type FullscreenProps = {
$nested: boolean;
theme: DefaultTheme;
};
const Fullscreen = styled.div<FullscreenProps>`
animation: ${fadeAndScaleIn} 250ms ease;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: ${depths.modal};
display: flex;
justify-content: center;
align-items: flex-start;
background: ${s("background")};
transition: ${s("backgroundTransition")};
outline: none;
${breakpoint("tablet")`
${(props: FullscreenProps) =>
props.$nested &&
`
box-shadow: 0 -2px 10px ${props.theme.shadow};
border-radius: 8px 0 0 8px;
overflow: hidden;
`}
`}
`;
const Content = styled(Scrollable)`
width: 100%;
padding: 8vh 12px;
${breakpoint("tablet")`
padding: 13vh 2rem 2rem;
`};
`;
const Centered = styled(Flex)`
width: 640px;
max-width: 100%;
position: relative;
margin: 0 auto;
`;
const Close = styled(NudeButton)`
position: absolute;
display: block;
top: 0;
right: 0;
margin: 12px;
opacity: 0.75;
color: ${s("text")};
width: auto;
height: auto;
&:hover {
opacity: 1;
}
${breakpoint("tablet")`
display: none;
`};
`;
const Back = styled(NudeButton)`
position: absolute;
display: none;
align-items: center;
top: ${Desktop.hasInsetTitlebar() ? "3rem" : "2rem"};
left: 2rem;
opacity: 0.75;
color: ${s("text")};
font-weight: 500;
width: auto;
height: auto;
&:hover {
opacity: 1;
}
${breakpoint("tablet")`
display: flex;
`};
`;
const Header = styled(Flex)`
color: ${s("textSecondary")};
align-items: center;
justify-content: space-between;
font-weight: 600;
padding: 24px 24px 4px;
`;
const Small = styled.div`
animation: ${fadeAndScaleIn} 250ms ease;
margin: 25vh auto auto auto;
width: 75vw;
min-width: 350px;
max-width: 450px;
z-index: ${depths.modal};
display: flex;
justify-content: center;
align-items: flex-start;
background: ${s("modalBackground")};
transition: ${s("backgroundTransition")};
box-shadow: ${s("modalShadow")};
border-radius: 8px;
outline: none;
${NudeButton} {
&:hover,
&[aria-expanded="true"] {
background: ${s("sidebarControlHoverBackground")};
}
vertical-align: middle;
}
${Header} {
align-items: start;
}
`;
const SmallContent = styled(Scrollable)`
padding: 12px 24px 24px;
`;
export default observer(Modal);
``` | /content/code_sandbox/app/components/Modal.tsx | xml | 2016-05-22T21:31:47 | 2024-08-16T19:57:22 | outline | outline/outline | 26,751 | 1,689 |
```xml
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m4,4c-1.657,0 -3,1.343 -3,3v10c0,1.657 1.343,3 3,3 0.552,0 1,-0.448 1,-1s-0.448,-1 -1,-1 -1,-0.448 -1,-1v-10c0,-0.552 0.448,-1 1,-1h10c0.552,0 1,0.448 1,1v3,4 3c0,0.552 -0.448,1 -1,1s-1,0.448 -1,1 0.448,1 1,1c1.657,0 3,-1.343 3,-3v-1.382l4.553,2.276c0.31,0.155 0.678,0.139 0.973,-0.044 0.295,-0.182 0.474,-0.504 0.474,-0.851v-10c0,-0.347 -0.179,-0.668 -0.474,-0.851s-0.663,-0.199 -0.973,-0.044l-4.553,2.276v-1.382c0,-1.657 -1.343,-3 -3,-3zM17,10.618v2.764l4,2v-6.764zM9.383,12.076c0.118,0.049 0.228,0.121 0.324,0.217l3,3c0.391,0.391 0.391,1.024 0,1.414s-1.024,0.391 -1.414,0l-1.293,-1.293v7.586c0,0.552 -0.448,1 -1,1s-1,-0.448 -1,-1v-7.586l-1.293,1.293c-0.391,0.391 -1.024,0.391 -1.414,0 -0.391,-0.391 -0.391,-1.024 0,-1.414l2.999,-2.999c0.002,-0.002 0.005,-0.005 0.007,-0.007 0.18,-0.177 0.428,-0.286 0.701,-0.286 0.136,0 0.265,0.027 0.383,0.076z"
android:fillColor="#04101e"
android:fillType="evenOdd"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_video_join.xml | xml | 2016-05-04T11:46:20 | 2024-08-15T16:29:10 | android | meganz/android | 1,537 | 648 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import {shallow} from 'enzyme';
import EmptyState from './EmptyState';
it('should render properly', () => {
const node = shallow(
<EmptyState title="some title" description="here is a description" icon="report" />
);
expect(node.find('.title')).toHaveText('some title');
expect(node.find('.description')).toHaveText('here is a description');
expect(node.find('.icon')).toHaveText('report');
});
it('should render actions', () => {
const spy = jest.fn();
const node = shallow(
<EmptyState
title="test"
description="test description"
actions={<button onClick={spy}>Click Me</button>}
/>
);
node.find('button').simulate('click');
expect(spy).toHaveBeenCalled();
});
``` | /content/code_sandbox/optimize/client/src/modules/components/EmptyState/EmptyState.test.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 197 |
```xml
/*
* @license Identity
* file except in compliance with the proprietary license.
*/
import styled from "styled-components";
import { TableContainer } from "@carbon/react";
import { layer01, productiveHeading01, spacing04 } from "@carbon/themes";
export const NoDataContainer = styled.div`
padding: ${spacing04};
background: ${layer01};
`;
export const NoDataHeader = styled.p`
margin: ${spacing04};
text-align: center;
font-size: ${productiveHeading01.fontSize};
font-weight: ${productiveHeading01.fontWeight};
`;
export const NoDataBody = styled.p`
text-align: center;
margin: 0 auto 1em;
max-width: 840px;
`;
export const DocumentationDescription = styled.p`
margin-top: ${spacing04};
max-width: none;
text-align: left;
`;
export const StyledTableContainer = styled(TableContainer)`
.cds--skeleton {
padding: 0;
}
`;
``` | /content/code_sandbox/identity/client/src/components/entityList/components.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 210 |
```xml
import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class HttpErrorReporterService {
private _reporter$ = new Subject<HttpErrorResponse>();
private _errors$ = new BehaviorSubject<HttpErrorResponse[]>([]);
get reporter$() {
return this._reporter$.asObservable();
}
get errors$() {
return this._errors$.asObservable();
}
get errors() {
return this._errors$.value;
}
reportError(error: HttpErrorResponse) {
this._reporter$.next(error);
this._errors$.next([...this.errors, error]);
}
}
``` | /content/code_sandbox/npm/ng-packs/packages/core/src/lib/services/http-error-reporter.service.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 156 |
```xml
export default interface IAppDataFolderExistsOutput {
isError: boolean;
errorMessage: string;
folderExists: boolean;
}
``` | /content/code_sandbox/samples/react-followed-drag-and-drop-grid/src/webparts/model/IAppDataFolderExistsOutput.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 28 |
```xml
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="nav_header_vertical_spacing">10dp</dimen>
<dimen name="nav_header_height">160dp</dimen>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>
``` | /content/code_sandbox/app/src/main/res/values/dimens.xml | xml | 2016-03-13T05:16:32 | 2024-04-29T09:08:01 | RxJavaApp | jiang111/RxJavaApp | 1,045 | 113 |
```xml
export class SecretVerificationRequest {
masterPasswordHash: string;
otp: string;
authRequestAccessCode: string;
}
``` | /content/code_sandbox/libs/common/src/auth/models/request/secret-verification.request.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 28 |
```xml
export default function Home() {
return <h1>This is the HOME page</h1>;
}
``` | /content/code_sandbox/examples/with-prefetching/pages/index.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 22 |
```xml
import {
INotebookModel,
NotebookPanel,
NotebookToCModel
} from '@jupyterlab/notebook';
import { Context } from '@jupyterlab/docregistry';
import { NBTestUtils } from '@jupyterlab/notebook/lib/testutils';
import { Sanitizer } from '@jupyterlab/apputils';
import { signalToPromise } from '@jupyterlab/testing';
import * as utils from './utils';
describe('@jupyterlab/notebook', () => {
describe('NotebookToCModel', () => {
let context: Context<INotebookModel>;
let panel: NotebookPanel;
let model: NotebookToCModel;
const sanitizer = new Sanitizer();
const initialCells = [{ cell_type: 'markdown', source: '# heading' }];
beforeEach(async () => {
context = await NBTestUtils.createMockContext(false);
panel = utils.createNotebookPanel(context);
model = new NotebookToCModel(panel, null, sanitizer);
panel.model!.sharedModel.insertCells(0, initialCells);
});
afterEach(() => {
context.dispose();
});
describe('#headingsChanged', () => {
it('should be emitted on cell insertion/deletion', async () => {
// Should be called on insertion
panel.model!.sharedModel.insertCells(0, [
{ cell_type: 'markdown', source: '# heading 2' }
]);
let promise = signalToPromise(model.headingsChanged);
await model.refresh();
await promise;
expect(model.headings).toHaveLength(2);
// Should be called on deletion
panel.model!.sharedModel.deleteCell(0);
promise = signalToPromise(model.headingsChanged);
await model.refresh();
await promise;
expect(model.headings).toHaveLength(1);
});
it('should be emitted when reloading notebook model', async () => {
// Note: if in future the `NotebookPanel` gets reworked to retain
// widgets for cells which did not change (rather than re-created
// them each time), this test may be no longer needed.
// Setup the notebook model
const content = {
...utils.DEFAULT_CONTENT,
cells: initialCells
};
let promise = signalToPromise(model.headingsChanged);
panel.model!.fromJSON(content);
await model.refresh();
await promise;
// Simulate update via "Revert" button, which will rebuilding the notebook
// widget from scratch (delete old cells and add new cells).
panel.model!.fromJSON(content);
// Should emit because cell references would have changed.
promise = signalToPromise(model.headingsChanged);
await model.refresh();
await promise;
});
});
});
});
``` | /content/code_sandbox/packages/notebook/test/toc.spec.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 583 |
```xml
import {Store} from "@tsed/core";
import {INJECTABLE_PROP} from "../constants/constants.js";
import type {InjectableProperties} from "../interfaces/InjectableProperties.js";
import {InjectablePropertyType} from "../domain/InjectablePropertyType.js";
/**
* Return value from Configuration.
*
* ## Example
*
* ```typescript
* import {Env} from "@tsed/core";
* import {Constant, Value} from "@tsed/di";
*
* export class MyClass {
*
* @Constant("env")
* env: Env;
*
* @Value("swagger.path")
* swaggerPath: string;
*
* @Value("swagger.path", "defaultValue")
* swaggerPath: string;
*
* constructor() {
* console.log(this.swaggerPath) // undefined. Not available on constructor
* }
*
* $onInit() {
* console.log(this.swaggerPath) // something
* }
* }
* ```
*
* @param expression
* @param defaultValue
* @returns {(targetClass: any, attributeName: string) => any}
* @decorator
*/
export function Value(expression: any, defaultValue?: any) {
return (target: any, propertyKey: string) => {
Store.from(target).merge(INJECTABLE_PROP, {
[propertyKey]: {
bindingType: InjectablePropertyType.VALUE,
propertyKey,
expression,
defaultValue
}
} as InjectableProperties);
};
}
``` | /content/code_sandbox/packages/di/src/common/decorators/value.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 313 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<AWSProjectType>Lambda</AWSProjectType>
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<!-- Generate ready to run images during publishing to improve cold start time. -->
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="2.2.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.1" />
<PackageReference Include="Amazon.Lambda.S3Events" Version="3.1.0" />
<PackageReference Include="AWSSDK.S3" Version="3.7.305.28" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/Blueprints/BlueprintDefinitions/vs2022/SimpleS3FunctionServerless/template/src/BlueprintBaseName.1/BlueprintBaseName.1.csproj | xml | 2016-11-11T20:43:34 | 2024-08-15T16:57:53 | aws-lambda-dotnet | aws/aws-lambda-dotnet | 1,558 | 252 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/// <reference types="@stdlib/types"/>
import * as random from '@stdlib/types/random';
/**
* Interface defining `factory` options.
*/
interface Options {
/**
* Pseudorandom number generator seed.
*/
seed?: random.PRNGSeedMINSTD;
/**
* Pseudorandom number generator state.
*/
state?: random.PRNGStateMINSTD;
/**
* Specifies whether to copy a provided pseudorandom number generator state.
*/
copy?: boolean;
}
/**
* Interface for PRNG properties and methods.
*/
interface PRNG {
/**
* Generator name.
*/
readonly NAME: string;
/**
* Minimum possible value.
*/
readonly MIN: number;
/**
* Maximum possible value.
*/
readonly MAX: number;
/**
* PRNG seed.
*/
readonly seed: random.PRNGSeedMINSTD;
/**
* PRNG seed length.
*/
readonly seedLength: number;
/**
* PRNG state.
*/
state: random.PRNGStateMINSTD;
/**
* PRNG state length.
*/
readonly stateLength: number;
/**
* PRNG state size (in bytes).
*/
readonly byteLength: number;
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* @returns JSON representation
*/
toJSON(): string;
}
/**
* Interface for generating pseudorandom integers on the interval `[1, 2147483646]`.
*/
interface NullaryFunction extends PRNG {
/**
* Returns a pseudorandom integer on the interval `[1, 2147483646]`.
*
* @returns pseudorandom number
*/
(): number;
}
/**
* Interface for generating pseudorandom integers on the interval `[1, 2147483646]`.
*/
interface Random extends PRNG {
/**
* Returns a pseudorandom integer on the interval `[1, 2147483646]`.
*
* ## Notes
*
* - This pseudorandom number generator (PRNG) is a linear congruential pseudorandom number generator (LCG) whose output is shuffled using the Bays- Durham algorithm. The shuffle step considerably strengthens the "randomness quality" of a simple LCG's output.
* - The generator has a period of approximately `2.1e9`.
* - An LCG is fast and uses little memory. On the other hand, because the generator is a simple LCG, the generator has recognized shortcomings. By today's PRNG standards, the generator's period is relatively short. In general, this generator is unsuitable for Monte Carlo simulations and cryptographic applications.
*
* @returns pseudorandom number
*
* @example
* var v = minstd();
* // returns <number>
*/
(): number;
/**
* Returns a pseudorandom number on the interval `[0,1)`.
*
* @returns pseudorandom number
*
* @example
* var r = minstd.normalized();
* // returns <number>
*/
normalized(): number;
/**
* Returns a linear congruential pseudorandom number generator (LCG) whose output is shuffled.
*
* @param options - function options
* @param options.seed - pseudorandom number generator seed
* @param options.state - pseudorandom number generator state
* @param options.copy - boolean indicating whether to copy a provided pseudorandom number generator state (default: true)
* @throws must provide valid options
* @returns pseudorandom number generator
*
* @example
* var rand = minstd.factory();
* var v = rand();
* // returns <number>
*
* @example
* var rand = minstd.factory({
* 'seed': 12345
* });
* var v = rand();
* // returns <number>
*/
factory( options?: Options ): NullaryFunction;
}
/**
* Returns a pseudorandom integer on the interval `[1, 2147483646]`.
*
* ## Notes
*
* - This pseudorandom number generator (PRNG) is a linear congruential pseudorandom number generator (LCG) whose output is shuffled using the Bays- Durham algorithm. The shuffle step considerably strengthens the "randomness quality" of a simple LCG's output.
* - The generator has a period of approximately `2.1e9`.
* - An LCG is fast and uses little memory. On the other hand, because the generator is a simple LCG, the generator has recognized shortcomings. By today's PRNG standards, the generator's period is relatively short. In general, this generator is unsuitable for Monte Carlo simulations and cryptographic applications.
*
* @returns pseudorandom number
*
* @example
* var v = minstd();
* // returns <number>
*
* @example
* var v = minstd.normalized();
* // returns <number>
*
* @example
* var rand = minstd.factory({
* 'seed': 12345
* });
* var v = rand();
* // returns <number>
*/
declare var minstd: Random;
// EXPORTS //
export = minstd;
``` | /content/code_sandbox/lib/node_modules/@stdlib/random/base/minstd-shuffle/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 1,189 |
```xml
/* eslint-disable @typescript-eslint/no-explicit-any */
import registerDownloader, { download, Options } from 'electron-dl';
import { inject, injectable } from 'inversify';
import _ from 'lodash';
import * as Youtube from '@nuclear/core/src/rest/Youtube';
import { StreamQuery } from '@nuclear/core/src/plugins/plugins.types';
import Store from '../store';
import Config from '../config';
import Window from '../window';
import { DownloadItem } from 'electron';
type DownloadParams = {
query: StreamQuery;
filename: string;
} & Pick<Options, 'onStarted' | 'onProgress' | 'onCompleted'>
/**
* Download file via youtube api with electron-dl
* @see {@link path_to_url}
*/
@injectable()
class Download {
constructor(
@inject(Window) private window: Window,
@inject(Store) private store: Store,
@inject(Config) private config: Config
) {
registerDownloader();
}
/**
* Download a track using Youtube
*/
async start({
query,
filename,
onStarted,
onProgress,
onCompleted
}: DownloadParams): Promise<any> {
const tracks = await Youtube.trackSearchByString(query, undefined, false);
const videoWithStream = await Youtube.getStreamForId(tracks[0]?.id, undefined);
return download(this.window.getBrowserWindow(), videoWithStream?.stream, {
filename: `${filename}.${videoWithStream?.format}`,
directory: this.store.getOption('downloads.dir'),
onStarted,
onProgress: _.throttle(onProgress, 1000),
onCompleted
});
}
}
export default Download;
``` | /content/code_sandbox/packages/main/src/services/download/index.ts | xml | 2016-09-22T22:58:21 | 2024-08-16T15:47:39 | nuclear | nukeop/nuclear | 11,862 | 360 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:id="@+id/insert_filename_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/activity_margin">
<com.simplemobiletools.commons.views.MyTextInputLayout
android:id="@+id/insert_filename_hint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/activity_margin"
android:hint="@string/filename">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/insert_filename_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapSentences"
android:singleLine="true"
android:textCursorDrawable="@null"
android:textSize="@dimen/bigger_text_size" />
</com.simplemobiletools.commons.views.MyTextInputLayout>
<com.simplemobiletools.commons.views.MyTextInputLayout
android:id="@+id/insert_filename_extension_hint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/activity_margin"
android:hint="@string/extension">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/insert_filename_extension_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapSentences"
android:singleLine="true"
android:textCursorDrawable="@null"
android:textSize="@dimen/bigger_text_size" />
</com.simplemobiletools.commons.views.MyTextInputLayout>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/dialog_insert_filename.xml | xml | 2016-07-12T20:06:21 | 2024-08-16T13:08:21 | Simple-File-Manager | SimpleMobileTools/Simple-File-Manager | 1,490 | 384 |
```xml
import { Account } from '../models/account'
/** Get the auth key for the user. */
export function getKeyForAccount(account: Account): string {
return getKeyForEndpoint(account.endpoint)
}
/** Get the auth key for the endpoint. */
export function getKeyForEndpoint(endpoint: string): string {
const appName = __DEV__ ? 'GitHub Desktop Dev' : 'GitHub'
return `${appName} - ${endpoint}`
}
``` | /content/code_sandbox/app/src/lib/auth.ts | xml | 2016-05-11T15:59:00 | 2024-08-16T17:00:41 | desktop | desktop/desktop | 19,544 | 88 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.jak_linux.dns66.main.DNSFragment">
<include layout="@layout/extra_bar_dns"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/dns_entries"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/extra_bar"
android:scrollbars="vertical" />
</RelativeLayout>
``` | /content/code_sandbox/app/src/main/res/layout/fragment_dns.xml | xml | 2016-10-15T15:27:17 | 2024-08-16T06:53:53 | dns66 | julian-klode/dns66 | 2,104 | 139 |
```xml
<Grid x:Class="Telegram.Controls.Cells.SharedLinkCell"
xmlns="path_to_url"
xmlns:x="path_to_url"
xmlns:local="using:Telegram.Controls.Items"
xmlns:controls="using:Telegram.Controls"
xmlns:d="path_to_url"
xmlns:mc="path_to_url"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400"
Padding="12,6"
Background="{ThemeResource SettingsItemBackground}"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="48" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border x:Name="Thumbnail"
VerticalAlignment="Top"
CornerRadius="4">
<controls:ProfilePicture x:Name="Photo"
Click="Thumbnail_Click"
Shape="None"
Width="48"
Height="48" />
</Border>
<StackPanel Margin="12,0,0,0"
Grid.Column="1">
<TextBlock x:Name="TitleLabel"
MaxLines="1"
TextTrimming="CharacterEllipsis"
Foreground="{ThemeResource MessageForegroundBrush}"
FontFamily="{ThemeResource EmojiThemeFontFamily}"
Style="{StaticResource BaseTextBlockStyle}" />
<TextBlock x:Name="DescriptionLabel"
MaxLines="3"
TextTrimming="CharacterEllipsis"
Foreground="{ThemeResource MessageForegroundBrush}"
FontFamily="{ThemeResource EmojiThemeFontFamily}"
Style="{StaticResource BodyTextBlockStyle}" />
<TextBlock x:Name="Description2Label"
MaxLines="3"
TextTrimming="CharacterEllipsis"
Foreground="{ThemeResource MessageForegroundBrush}"
FontFamily="{ThemeResource EmojiThemeFontFamily}"
Style="{StaticResource BodyTextBlockStyle}" />
<Grid x:Name="LinksPanel" />
</StackPanel>
</Grid>
``` | /content/code_sandbox/Telegram/Controls/Cells/SharedLinkCell.xaml | xml | 2016-05-23T09:03:33 | 2024-08-16T16:17:48 | Unigram | UnigramDev/Unigram | 3,744 | 419 |
```xml
import * as React from 'react';
import { Autofill } from '../../Autofill';
import type { IPickerItemProps } from './PickerItem.types';
import type { IReactProps, IRefObject, IStyleFunctionOrObject } from '../../Utilities';
import type { ISuggestionModel, ISuggestionsProps } from './Suggestions/Suggestions.types';
import type { ICalloutProps } from '../../Callout';
import type { ITheme, IStyle } from '../../Styling';
import type { ISuggestionItemProps } from '../pickers/Suggestions/SuggestionsItem.types';
import { IIconProps } from '../Icon/Icon.types';
/**
* BasePicker component.
* {@docCategory Pickers}
*/
export interface IBasePicker<T> {
/** Gets the current value of the input. */
items: T[] | undefined;
/** Sets focus to the focus zone. */
focus: () => void;
/** Set focus to the input */
focusInput: () => void;
/**
* When called, will take the currently selected suggestion and complete it.
* If called with forceComplete true, it will attempt to force the current suggestion
* to complete, must provide both createGenericSuggestion, so the text can be turned into
* an object in the right shape, and onValidateInput, so the object knows if it's correct or not.
*/
completeSuggestion: (forceComplete?: boolean) => void;
}
/**
* Type T is the type of the item that is displayed
* and searched for by the picker. For example, if the picker is
* displaying persona's then type T could either be of Persona or IPersona props
* {@docCategory Pickers}
*/
export interface IBasePickerProps<T> extends IReactProps<any> {
/**
* Optional callback to access the IBasePicker interface. Use this instead of ref for accessing
* the public methods and properties of the component.
*/
componentRef?: IRefObject<IBasePicker<T>>;
/**
* Function that specifies how the selected item will appear.
*/
onRenderItem?: (props: IPickerItemProps<T>) => JSX.Element;
/**
* Function that specifies how an individual suggestion item will appear.
*/
onRenderSuggestionsItem?: (props: T, itemProps: ISuggestionItemProps<T>) => JSX.Element;
/**
* A callback for what should happen when a person types text into the input.
* Returns the already selected items so the resolver can filter them out.
* If used in conjunction with resolveDelay this will only kick off after the delay throttle.
*/
onResolveSuggestions: (filter: string, selectedItems?: T[]) => T[] | PromiseLike<T[]>;
/**
* The delay time in ms before resolving suggestions, which is kicked off when input has been changed.
* e.g. If a second input change happens within the resolveDelay time, the timer will start over.
* Only until after the timer completes will onResolveSuggestions be called.
*/
resolveDelay?: number;
/**
* A callback for what should happen when a user clicks within the input area.
* @deprecated Please use `onEmptyResolveSuggestions` instead, as the suggestions aren't about
* setting focus as they are about resolving suggestions when there is no input.
*/
onEmptyInputFocus?: (selectedItems?: T[]) => T[] | PromiseLike<T[]>;
/**
* A callback for what should happen when suggestions are shown without
* input provided.
* Returns the already selected items so the resolver can filter them out.
* If used in conjunction with resolveDelay this will only kick off after the delay throttle.
*/
onEmptyResolveSuggestions?: (selectedItems?: T[]) => T[] | PromiseLike<T[]>;
/**
* Initial items that have already been selected and should appear in the people picker.
*/
defaultSelectedItems?: T[];
/**
* A callback for when the selected list of items changes.
*/
onChange?: (items?: T[]) => void;
/**
* A callback for when the user put focus on the picker
* @deprecated Use `inputProps.onFocus` instead
*/
onFocus?: React.FocusEventHandler<HTMLInputElement | Autofill>;
/**
* A callback for when the user moves the focus away from the picker
*/
onBlur?: React.FocusEventHandler<HTMLInputElement | Autofill>;
/**
* A callback to get text from an item. Used to autofill text in the pickers.
*/
getTextFromItem?: (item: T, currentValue?: string) => string;
/**
* A callback that gets the rest of the results when a user clicks get more results.
*/
onGetMoreResults?: (filter: string, selectedItems?: T[]) => T[] | PromiseLike<T[]>;
/**
* ClassName for the picker.
*/
className?: string;
/**
* The properties that will get passed to the Suggestions component.
*/
pickerSuggestionsProps?: IBasePickerSuggestionsProps;
/**
* The properties that will get passed to the Callout component.
*/
pickerCalloutProps?: ICalloutProps;
/**
* AutoFill input native props
* @defaultvalue undefined
*/
inputProps?: IInputProps;
/**
* A callback for when an item is removed from the suggestion list
*/
onRemoveSuggestion?: (item: T) => void;
/**
* A function used to validate if raw text entered into the well can be added into the selected items list
*/
onValidateInput?: (input: string) => ValidationState;
/**
* The text to display while searching for more results in a limited suggestions list
*/
searchingText?: ((props: { input: string }) => string) | string;
/**
* Flag for disabling the picker.
* @defaultvalue false
*/
disabled?: boolean;
/**
* Restrict the amount of selectable items.
* @defaultvalue undefined
*/
itemLimit?: number;
/**
* Function that specifies how arbitrary text entered into the well is handled.
*/
createGenericItem?: (input: string, ValidationState: ValidationState) => ISuggestionModel<T> | T;
/**
* Aria label for the "X" button in the selected item component.
* @defaultvalue ''
*/
removeButtonAriaLabel?: string;
/**
* The text that will be announced when a suggestion is removed. A default value is only provided for English.
* @default 'removed \{0\}'
*/
suggestionRemovedText?: string;
/**
* Optional aria-label that will be placed on the element that has the role "combobox"
* attached. Additionally aria-labelled by will get added to the supporting input element contained
* with in the combobox container
*/
['aria-label']?: string;
/**
* A callback to process a selection after the user selects something from the picker. If the callback returns null,
* the item will not be added to the picker.
*/
onItemSelected?: (selectedItem?: T) => T | PromiseLike<T> | null;
/**
* The items that the base picker should currently display as selected.
* If this is provided then the picker will act as a controlled component.
*/
selectedItems?: T[];
/**
* Aria label for the displayed selection. A good value would be something like "Selected Contacts".
* @defaultvalue ''
*/
selectionAriaLabel?: string;
/**
* Override the role used for the element containing selected items.
* Update this if onRenderItem does not return elements with role="listitem".
* A good alternative would be 'group'.
* @defaultvalue 'list'
*/
selectionRole?: string;
/**
* A callback used to modify the input string.
*/
onInputChange?: (input: string) => string;
/**
* A callback to override the default behavior of adding the selected suggestion on dismiss. If it returns true or
* nothing, the selected item will be added on dismiss. If false, the selected item will not be added on dismiss.
*
*/
onDismiss?: (ev?: any, selectedItem?: T) => boolean | void;
/**
* Adds an additional alert for the currently selected suggestion. This prop should be set to true for IE11 and below,
* as it enables proper screen reader behavior for each suggestion (since aria-activedescendant does not work
* with IE11). It should not be set for modern browsers (Edge, Chrome).
* @defaultvalue false
*/
enableSelectedSuggestionAlert?: boolean;
/**
* Call to provide customized styling that will layer on top of the variant rules.
*/
styles?: IStyleFunctionOrObject<IBasePickerStyleProps, IBasePickerStyles>;
/**
* Theme provided by styled() function.
*/
theme?: ITheme;
/**
* Props for the icon used in the item's remove button.
* @defaultvalue `{ iconName:'Cancel' }`
*/
removeButtonIconProps?: IIconProps;
}
/**
* Subset of picker options that may be legally passed through a picker to its
* internal Suggestions component.
* {@docCategory Pickers}
*/
export interface IBasePickerSuggestionsProps<T = any>
extends Pick<
ISuggestionsProps<T>,
| 'onRenderNoResultFound'
| 'suggestionsHeaderText'
| 'mostRecentlyUsedHeaderText'
| 'noResultsFoundText'
| 'className'
| 'suggestionsClassName'
| 'suggestionsItemClassName'
| 'searchForMoreIcon'
| 'searchForMoreText'
| 'forceResolveText'
| 'loadingText'
| 'searchingText'
| 'resultsFooterFull'
| 'resultsFooter'
| 'resultsMaximumNumber'
| 'showRemoveButtons'
| 'suggestionsAvailableAlertText'
| 'suggestionsContainerAriaLabel'
| 'showForceResolve'
| 'removeButtonIconProps'
> {}
/**
* Validation state of the user's input.
* {@docCategory Pickers}
*/
export enum ValidationState {
/** User input is valid. */
valid,
/** User input could be valid or invalid, its state is not known yet. */
warning,
/** User input is invalid. */
invalid,
}
/**
* Pickers' input props interface
* {@docCategory Pickers}
*/
export interface IInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
/**
* Screen reader label to apply to an input element.
*/
'aria-label'?: string;
/**
* The default value to be visible when the autofill first created.
* This is different than placeholder text because the placeholder text will disappear and re-appear. This
* text persists until deleted or changed.
*/
defaultVisibleValue?: string;
}
/**
* The props needed to construct styles.
* {@docCategory Pickers}
*/
export type IBasePickerStyleProps = Pick<IBasePickerProps<any>, 'theme' | 'className' | 'disabled'> & {
/** Whether text style area is focused */
isFocused?: boolean;
/** Optional pickerInput className */
inputClassName?: string;
};
/**
* Represents the stylable areas of the control.
* {@docCategory Pickers}
*/
export interface IBasePickerStyles {
/** Root element of any picker extending from BasePicker (wraps all the elements). */
root: IStyle;
/**
* Refers to the elements already selected (picked) wrapped by `itemsWrapper` along with the input to type
* a new selection.
*/
text: IStyle;
/** Refers to the items already selected (picked). */
itemsWrapper: IStyle;
/** Refers to the input were to type new selections (picks). */
input: IStyle;
/** Refers to helper element used for accessibility tools (hidden from view on screen). */
screenReaderText: IStyle;
}
``` | /content/code_sandbox/packages/react/src/components/pickers/BasePicker.types.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 2,578 |
```xml
import { mergeClasses } from '@expo/styleguide';
import { ELEMENT_SPACING, STYLES_SECONDARY } from './styles';
import {
DefaultPropsDefinitionData,
PropData,
PropsDefinitionData,
TypeDefinitionData,
} from '~/components/plugins/api/APIDataTypes';
import { APISectionDeprecationNote } from '~/components/plugins/api/APISectionDeprecationNote';
import { APISectionPlatformTags } from '~/components/plugins/api/APISectionPlatformTags';
import {
BoxSectionHeader,
CommentTextBlock,
getCommentContent,
getCommentOrSignatureComment,
getH3CodeWithBaseNestingLevel,
getTagData,
getTagNamesList,
renderTypeOrSignatureType,
resolveTypeName,
STYLES_APIBOX,
STYLES_APIBOX_NESTED,
STYLES_NOT_EXPOSED_HEADER,
TypeDocKind,
} from '~/components/plugins/api/APISectionUtils';
import { CODE, H2, H3, H4, LI, MONOSPACE, P, UL } from '~/ui/components/Text';
export type APISectionPropsProps = {
data: PropsDefinitionData[];
sdkVersion: string;
defaultProps?: DefaultPropsDefinitionData;
header?: string;
};
export type RenderPropOptions = {
exposeInSidebar?: boolean;
baseNestingLevel?: number;
};
const UNKNOWN_VALUE = '...';
const extractDefaultPropValue = (
{ comment, name }: PropData,
defaultProps?: DefaultPropsDefinitionData
): string | undefined => {
const annotationDefault = getTagData('default', comment);
if (annotationDefault) {
return getCommentContent(annotationDefault.content);
}
return defaultProps?.type?.declaration?.children?.filter(
(defaultProp: PropData) => defaultProp.name === name
)[0]?.defaultValue;
};
const renderInheritedProp = (ip: TypeDefinitionData, sdkVersion: string) => {
return (
<LI key={`inherited-prop-${ip.name}-${ip.type}`}>
<CODE>{resolveTypeName(ip, sdkVersion)}</CODE>
</LI>
);
};
const renderInheritedProps = (
data: PropsDefinitionData | undefined,
sdkVersion: string,
exposeInSidebar?: boolean
): JSX.Element | undefined => {
const inheritedData = data?.type?.types ?? data?.extendedTypes ?? [];
const inheritedProps =
inheritedData.filter((ip: TypeDefinitionData) => ip.type === 'reference') ?? [];
if (inheritedProps.length) {
return (
<>
{exposeInSidebar ? <H3>Inherited Props</H3> : <H4>Inherited Props</H4>}
<UL>{inheritedProps.map(i => renderInheritedProp(i, sdkVersion))}</UL>
</>
);
}
return undefined;
};
const getPropsBaseTypes = (def: PropsDefinitionData) => {
if (def.kind === TypeDocKind.TypeAlias || def.kind === TypeDocKind.TypeAlias_Legacy) {
const baseTypes = def?.type?.types
? def.type.types?.filter((t: TypeDefinitionData) => t.declaration)
: [def.type];
return baseTypes.map(def => def?.declaration?.children);
} else if (def.kind === TypeDocKind.Interface) {
return def.children?.filter(child => !child.inheritedFrom) ?? [];
}
return [];
};
const renderProps = (
def: PropsDefinitionData,
sdkVersion: string,
defaultValues?: DefaultPropsDefinitionData,
exposeInSidebar?: boolean
): JSX.Element => {
const propsDeclarations = getPropsBaseTypes(def)
.flat()
.filter((dec, i, arr) => arr.findIndex(t => t?.name === dec?.name) === i);
return (
<div key={`props-definition-${def.name}`} className="[&>*:last-child]:!mb-0">
{propsDeclarations?.map(prop =>
prop
? renderProp(prop, sdkVersion, extractDefaultPropValue(prop, defaultValues), {
exposeInSidebar,
})
: null
)}
{renderInheritedProps(def, sdkVersion, exposeInSidebar)}
</div>
);
};
export const renderProp = (
{ comment, name, type, flags, signatures }: PropData,
sdkVersion: string,
defaultValue?: string,
{ exposeInSidebar, ...options }: RenderPropOptions = {}
) => {
const baseNestingLevel = options.baseNestingLevel ?? (exposeInSidebar ? 3 : 4);
const HeaderComponent = getH3CodeWithBaseNestingLevel(baseNestingLevel);
const extractedSignatures = signatures || type?.declaration?.signatures;
const extractedComment = getCommentOrSignatureComment(comment, extractedSignatures);
return (
<div
key={`prop-entry-${name}`}
css={[STYLES_APIBOX, STYLES_APIBOX_NESTED]}
className="!pb-4 [&>*:last-child]:!mb-0">
<APISectionDeprecationNote comment={extractedComment} sticky />
<APISectionPlatformTags comment={comment} />
<HeaderComponent tags={getTagNamesList(comment)}>
<MONOSPACE
weight="medium"
css={!exposeInSidebar && STYLES_NOT_EXPOSED_HEADER}
className="wrap-anywhere">
{name}
</MONOSPACE>
</HeaderComponent>
<P className={mergeClasses(extractedComment && ELEMENT_SPACING)}>
{flags?.isOptional && <span className={STYLES_SECONDARY}>Optional • </span>}
<span className={STYLES_SECONDARY}>Type:</span>{' '}
{renderTypeOrSignatureType({ type, signatures: extractedSignatures, sdkVersion })}
{defaultValue && defaultValue !== UNKNOWN_VALUE ? (
<span>
<span className={STYLES_SECONDARY}> • Default:</span>{' '}
<CODE>{defaultValue}</CODE>
</span>
) : null}
</P>
<CommentTextBlock comment={extractedComment} includePlatforms={false} />
</div>
);
};
const APISectionProps = ({
data,
defaultProps,
header = 'Props',
sdkVersion,
}: APISectionPropsProps) => {
const baseProp = data.find(prop => prop.name === header);
return data?.length > 0 ? (
<>
{header === 'Props' ? (
<H2 key="props-header">{header}</H2>
) : (
<div>
{baseProp && <APISectionDeprecationNote comment={baseProp.comment} />}
<BoxSectionHeader
text={header}
className="!text-secondary !font-medium"
exposeInSidebar
baseNestingLevel={99}
/>
{baseProp && baseProp.comment ? <CommentTextBlock comment={baseProp.comment} /> : null}
</div>
)}
{data.map((propsDefinition: PropsDefinitionData) =>
renderProps(propsDefinition, sdkVersion, defaultProps, header === 'Props')
)}
</>
) : null;
};
export default APISectionProps;
``` | /content/code_sandbox/docs/components/plugins/api/APISectionProps.tsx | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 1,527 |
```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="zh-Hant" original="../LocalizableStrings.resx">
<body>
<trans-unit id="CommandDescription">
<source>Repair workload installations.</source>
<target state="translated"></target>
<note />
</trans-unit>
<trans-unit id="NoWorkloadsToRepair">
<source>No workloads are installed, nothing to repair. Run `dotnet workload search` to find workloads to install.</source>
<target state="translated"> `dotnet workload search` </target>
<note />
</trans-unit>
<trans-unit id="RepairSucceeded">
<source>Successfully repaired workloads: {0}</source>
<target state="translated">: {0}</target>
<note />
</trans-unit>
<trans-unit id="RepairingWorkloads">
<source>Repairing workload installation for workloads: {0}</source>
<target state="translated">: {0}</target>
<note />
</trans-unit>
<trans-unit id="WorkloadRepairFailed">
<source>Workload repair failed: {0}</source>
<target state="translated">: {0}</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Cli/dotnet/commands/dotnet-workload/repair/xlf/LocalizableStrings.zh-Hant.xlf | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 372 |
```xml
import type { DialogProps } from '@fluentui/react-dialog';
import type { PresenceMotionSlotProps } from '@fluentui/react-motion';
import type { ComponentProps, ComponentState, Slot } from '@fluentui/react-utilities';
import type { DrawerMotionParams, OverlayDrawerSurfaceMotionParams } from '../../shared/drawerMotions';
import type { DrawerBaseProps, DrawerBaseState } from '../../shared/DrawerBase.types';
import type { OverlayDrawerSurfaceProps } from './OverlayDrawerSurface';
/**
* OverlayDrawer slots
*/
export type OverlayDrawerSlots = {
/**
* Slot for the root element.
*/
root: Slot<OverlayDrawerSurfaceProps>;
backdropMotion?: Slot<PresenceMotionSlotProps<OverlayDrawerSurfaceMotionParams>>;
surfaceMotion?: Slot<PresenceMotionSlotProps<DrawerMotionParams>>;
};
/**
* OverlayDrawer internal slots for when using with composition API
*/
export type OverlayDrawerInternalSlots = Pick<OverlayDrawerSlots, 'root'> & {
/**
* Slot for the dialog component that wraps the drawer.
*/
dialog: Slot<DialogProps>;
};
/**
* OverlayDrawer Props
*/
export type OverlayDrawerProps = ComponentProps<OverlayDrawerSlots> &
Pick<DialogProps, 'modalType' | 'onOpenChange' | 'inertTrapFocus'> &
DrawerBaseProps & {
/**
* @deprecated OverlayDrawer can work only as a controlled component
* and does not support uncontrolled mode i.e. defaultOpen prop
*/
defaultOpen?: boolean;
};
/**
* State used in rendering OverlayDrawer
*/
export type OverlayDrawerState = ComponentState<OverlayDrawerInternalSlots> & Required<DrawerBaseState>;
``` | /content/code_sandbox/packages/react-components/react-drawer/library/src/components/OverlayDrawer/OverlayDrawer.types.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 355 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>com.sunsetlakesoftware.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
<key>UIPrerenderedIcon</key>
<true/>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
``` | /content/code_sandbox/framework/SwiftOCR/GPUImage-master/examples/iOS/FeatureExtractionTest/FeatureExtractionTest/FeatureExtractionTest-Info.plist | xml | 2016-04-22T08:39:02 | 2024-08-16T08:32:39 | SwiftOCR | NMAC427/SwiftOCR | 4,616 | 459 |
```xml
import { execAsync } from '@expo/osascript';
import spawnAsync from '@expo/spawn-async';
import { SimulatorAppPrerequisite } from '../SimulatorAppPrerequisite';
jest.mock(`../../../../log`);
it(`detects that Simulator.app is installed`, async () => {
// Mock Simulator.app installed for CI
jest
.mocked(execAsync)
.mockReset()
.mockResolvedValueOnce(`com.apple.CoreSimulator.SimulatorTrampoline`);
jest
.mocked(spawnAsync)
.mockReset()
.mockResolvedValueOnce({} as any);
await SimulatorAppPrerequisite.instance.assertImplementation();
expect(execAsync).toBeCalledWith('id of app "Simulator"');
expect(spawnAsync).toBeCalledWith('xcrun', ['simctl', 'help']);
});
it(`asserts that Simulator.app is installed with invalid Simulator.app`, async () => {
// Mock Simulator.app installed with invalid binary
jest.mocked(execAsync).mockResolvedValueOnce(`com.apple.CoreSimulator.bacon`);
jest.mocked(spawnAsync).mockReset();
await expect(SimulatorAppPrerequisite.instance.assertImplementation()).rejects.toThrow(/\.bacon/);
expect(spawnAsync).not.toBeCalled();
});
it(`asserts that Simulator.app is installed but simctl doesn't work`, async () => {
// Mock Simulator.app installed for CI
jest.mocked(execAsync).mockResolvedValueOnce(`com.apple.CoreSimulator.SimulatorTrampoline`);
jest.mocked(spawnAsync).mockImplementationOnce(() => {
throw new Error('foobar');
});
await expect(SimulatorAppPrerequisite.instance.assertImplementation()).rejects.toThrow(
/xcrun is not configured correctly/
);
});
``` | /content/code_sandbox/packages/@expo/cli/src/start/doctor/apple/__tests__/SimulatorAppPrerequisite-test.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 371 |
```xml
import * as path from "path"
import * as semver from "semver"
import * as fs from "fs"
import * as lockfile from "proper-lockfile"
import {spawn} from "child_process"
import * as zmq from "../../src"
console.log(`ZeroMQ version ${zmq.version}`)
if (semver.satisfies(zmq.version, ">= 4.2")) {
/* Stop pending messages in test suite from preventing process exit. */
zmq.context.blocky = false
}
/**
* Get a unique id to be used as a port number or IPC path.
* This function is thread-safe and will use a lock file to ensure that the id is unique.
*/
let idFallback = 5000
async function getUniqueId() {
const idPath = path.resolve(__dirname, "../../tmp/id")
await fs.promises.mkdir(path.dirname(idPath), {recursive: true})
try {
// Create the file if it doesn't exist
if (!fs.existsSync(idPath)) {
await fs.promises.writeFile(idPath, "5000", "utf8")
/* Windows cannot bind on a ports just above 1014; start higher to be safe. */
return 5000
}
await lockfile.lock(idPath, {retries: 10})
// Read the current number from the file
const idString = await fs.promises.readFile(idPath, "utf8")
let id = parseInt(idString, 10)
// Increment the number
id++
// Ensure the number is within the valid port range
if (id > 65535) {
idFallback++
id = idFallback
}
// Write the new number back to the file
await fs.promises.writeFile(idPath, id.toString(), "utf8")
return id
} catch (err) {
console.error(`Error getting unique id via id file: ${err}`)
return idFallback++
} finally {
// Release the lock
try {
await lockfile.unlock(idPath)
} catch {
// ignore
}
}
}
type Proto = "ipc" | "tcp" | "udp" | "inproc"
export async function uniqAddress(proto: Proto) {
const id = await getUniqueId()
switch (proto) {
case "ipc": {
const sock = path.resolve(__dirname, `../../tmp/${proto}-${id}`)
return `${proto}://${sock}`
}
case "tcp":
case "udp":
return `${proto}://127.0.0.1:${id}`
case "inproc":
default:
return `${proto}://${proto}-${id}`
}
}
export function testProtos(...requested: Proto[]) {
const set = new Set(requested)
/* Do not test with ipc if unsupported. */
if (zmq.capability.ipc !== true) {
set.delete("ipc")
}
/* Only test inproc with version 4.2+, earlier versions are unreliable. */
if (semver.satisfies(zmq.version, "< 4.2")) {
set.delete("inproc")
}
if (!set.size) {
console.error("Warning: test protocol set is empty")
}
return [...set]
}
export async function createWorker<T, D extends {}>(
data: D,
fn: (data: D) => Promise<T>,
): Promise<T> {
const src = `
const {parentPort, workerData} = require("worker_threads")
const zmq = require(${JSON.stringify(path.resolve(__dirname, "../.."))})
async function run() {
const fn = ${fn.toString()}
const msg = await fn(workerData)
parentPort.postMessage(msg)
}
run()
`
const {Worker} = await import("worker_threads")
return new Promise<T>((resolve, reject) => {
const worker = new Worker(src, {
eval: true,
workerData: data,
})
let message: T
worker.on("message", msg => {
message = msg
})
worker.on("exit", code => {
if (code === 0) {
resolve(message)
} else {
reject(new Error(`Worker stopped with exit code ${code}`))
}
})
})
}
interface Result {
code: number
stdout: Buffer
stderr: Buffer
isTimeout: boolean
}
export function createProcess(fn: () => void): Promise<Result> {
const src = `
const zmq = require(${JSON.stringify(path.resolve(__dirname, "../.."))})
const fn = ${fn.toString()}
const result = fn()
if (result instanceof Promise) {
result.catch(err => {
if (error instanceof Error) {
console.error(error.message)
console.error(error.stack)
} else {
console.error(error)
}
process.exit(10)
})
}
`
const child = spawn(process.argv[0], ["--expose_gc"])
child.stdin.write(src)
child.stdin.end()
let stdout: Buffer = Buffer.alloc(0)
let stderr: Buffer = Buffer.alloc(0)
child.stdout.on("data", (data: Buffer) => {
stdout = Buffer.concat([stdout, data])
})
child.stderr.on("data", (data: Buffer) => {
stderr = Buffer.concat([stderr, data])
})
return new Promise((resolve, reject) => {
child.on("close", (code: number, signal: string) => {
if (signal) {
reject(
new Error(
`Child exited with ${signal}:\n${stdout.toString()}\n${stderr.toString()}`,
),
)
} else {
if (code !== 0) {
console.error(
`Child exited with code ${code}:\n${stdout.toString()}\n${stderr.toString()}`,
)
}
resolve({code, stdout, stderr, isTimeout: false})
}
})
setTimeout(() => {
resolve({code: -1, stdout, stderr, isTimeout: true})
console.error(
`Child timed out\n${stdout.toString()}\n${stderr.toString()}`,
)
child.kill()
}, 750)
})
}
export function captureEvent<E extends zmq.EventType>(
socket: zmq.Socket,
type: E,
): Promise<zmq.EventOfType<E>> {
return new Promise(resolve => {
socket.events.on<E>(type, resolve)
})
}
export async function captureEventsUntil(
socket: zmq.Socket,
type: zmq.EventType,
): Promise<zmq.Event[]> {
const events = []
for await (const event of socket.events) {
events.push(event)
if (event.type === type) {
break
}
}
return events
}
// REAL typings for global.gc per
// path_to_url
interface GCFunction {
(options: {
execution?: "sync"
flavor?: "regular" | "last-resort"
type?: "major-snapshot" | "major" | "minor"
filename?: string
}): void
(options: {
execution?: "async"
flavor?: "regular" | "last-resort"
type?: "major-snapshot" | "major" | "minor"
filename?: string
}): Promise<void>
(options: {
execution?: "async" | "sync"
flavor?: "regular" | "last-resort"
type?: "major-snapshot" | "major" | "minor"
filename?: string
}): void | Promise<void>
}
export function getGcOrSkipTest(test?: Mocha.Context) {
if (process.env.SKIP_GC_TESTS === "true") {
test?.skip()
}
const gc = global.gc as undefined | GCFunction
if (typeof gc !== "function") {
throw new Error(
"Garbage collection is not exposed. It may be enabled by the node --expose-gc flag or v8-expose-gc flag in Mocha. To skip GC tests, set the environment variable `SKIP_GC_TESTS`",
)
}
// path_to_url
// per docs, we we're using use case 2 (Test that certain objects indeed are reclaimed)
const asyncMajorGc = () => gc({type: "major", execution: "async"})
return asyncMajorGc
}
``` | /content/code_sandbox/test/unit/helpers.ts | xml | 2016-02-04T04:42:22 | 2024-08-15T08:36:05 | zeromq.js | zeromq/zeromq.js | 1,440 | 1,801 |
```xml
<clickhouse>
<http_authentication_servers>
<basic_server>
<uri>path_to_url
<connection_timeout_ms>1000</connection_timeout_ms>
<receive_timeout_ms>1000</receive_timeout_ms>
<send_timeout_ms>1000</send_timeout_ms>
<max_tries>3</max_tries>
<retry_initial_backoff_ms>50</retry_initial_backoff_ms>
<retry_max_backoff_ms>1000</retry_max_backoff_ms>
</basic_server>
</http_authentication_servers>
<custom_settings_prefixes>auth_</custom_settings_prefixes>
</clickhouse>
``` | /content/code_sandbox/tests/integration/test_external_http_authenticator/configs/config.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 138 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:id="@+id/small_window_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:theme="@style/MyThemeBlue">
<FrameLayout
android:id="@+id/small_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/bg_float_lyric" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<LinearLayout
android:id="@+id/rl_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="@+id/music_app"
android:layout_width="@dimen/dp_24"
android:layout_height="@dimen/dp_24"
android:layout_margin="@dimen/dp_8"
android:background="@drawable/ic_music" />
<TextView
android:id="@+id/music_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/app_name"
android:textColor="@color/white" />
<ImageButton
android:id="@+id/btn_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@drawable/ic_clear" />
</LinearLayout>
<com.cyl.musiclake.ui.widget.lyric.LyricTextView
android:id="@+id/lyric"
android:layout_width="match_parent"
android:layout_height="84dp" />
<LinearLayout
android:id="@+id/ll_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<net.steamcrafted.materialiconlib.MaterialIconView
android:id="@+id/btn_lock"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="center"
app:materialIcon="lock_open"
app:materialIconColor="@color/white"
app:materialIconSize="24dp" />
<net.steamcrafted.materialiconlib.MaterialIconView
android:id="@+id/btn_previous"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="center"
app:materialIcon="skip_previous"
app:materialIconColor="@color/white"
app:materialIconSize="24dp" />
<net.steamcrafted.materialiconlib.MaterialIconView
android:id="@+id/btn_play"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="center"
app:materialIcon="play"
app:materialIconColor="@color/white"
app:materialIconSize="24dp" />
<net.steamcrafted.materialiconlib.MaterialIconView
android:id="@+id/btn_next"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="center"
app:materialIcon="skip_next"
app:materialIconColor="@color/white"
app:materialIconSize="24dp" />
<net.steamcrafted.materialiconlib.MaterialIconView
android:id="@+id/btn_settings"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="center"
app:materialIcon="settings"
app:materialIconColor="@color/white"
app:materialIconSize="24dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/ll_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone">
<SeekBar
android:id="@+id/sb_size"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp" />
<com.rtugeek.android.colorseekbar.ColorSeekBar
android:id="@+id/sb_color"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:colorSeeds="@array/material_colors" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
``` | /content/code_sandbox/app/src/main/res/layout/float_lyric_view.xml | xml | 2016-04-09T15:47:45 | 2024-08-14T04:30:04 | MusicLake | caiyonglong/MusicLake | 2,654 | 1,277 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<countries>
<country id="4" alpha2="af" alpha3="afg" name="Afganistan"/>
<country id="248" alpha2="ax" alpha3="ala" name="Insulele land"/>
<country id="8" alpha2="al" alpha3="alb" name="Albania"/>
<country id="12" alpha2="dz" alpha3="dza" name="Algeria"/>
<country id="16" alpha2="as" alpha3="asm" name="Samoa american"/>
<country id="20" alpha2="ad" alpha3="and" name="Andorra"/>
<country id="24" alpha2="ao" alpha3="ago" name="Angola"/>
<country id="660" alpha2="ai" alpha3="aia" name="Anguilla"/>
<country id="10" alpha2="aq" alpha3="ata" name="Antarctica"/>
<country id="28" alpha2="ag" alpha3="atg" name="Antigua i Barbuda"/>
<country id="32" alpha2="ar" alpha3="arg" name="Argentina"/>
<country id="51" alpha2="am" alpha3="arm" name="Armenia"/>
<country id="533" alpha2="aw" alpha3="abw" name="Aruba"/>
<country id="36" alpha2="au" alpha3="aus" name="Australia"/>
<country id="40" alpha2="at" alpha3="aut" name="Austria"/>
<country id="31" alpha2="az" alpha3="aze" name="Azerbaidjan"/>
<country id="44" alpha2="bs" alpha3="bhs" name="Bahamas"/>
<country id="48" alpha2="bh" alpha3="bhr" name="Bahrain"/>
<country id="50" alpha2="bd" alpha3="bgd" name="Bangladesh"/>
<country id="52" alpha2="bb" alpha3="brb" name="Barbados"/>
<country id="112" alpha2="by" alpha3="blr" name="Belarus"/>
<country id="56" alpha2="be" alpha3="bel" name="Belgia"/>
<country id="84" alpha2="bz" alpha3="blz" name="Belize"/>
<country id="204" alpha2="bj" alpha3="ben" name="Benin"/>
<country id="60" alpha2="bm" alpha3="bmu" name="Bermude"/>
<country id="64" alpha2="bt" alpha3="btn" name="Bhutan"/>
<country id="68" alpha2="bo" alpha3="bol" name="Bolivia"/>
<country id="535" alpha2="bq" alpha3="bes" name="Insulele Bonaire, Sint Eustatius i Saba"/>
<country id="70" alpha2="ba" alpha3="bih" name="Bosnia i Heregovina"/>
<country id="72" alpha2="bw" alpha3="bwa" name="Botswana"/>
<country id="74" alpha2="bv" alpha3="bvt" name="Insula Bouvet"/>
<country id="76" alpha2="br" alpha3="bra" name="Brazilia"/>
<country id="86" alpha2="io" alpha3="iot" name="Teritoriul Britanic din Oceanul Indian"/>
<country id="96" alpha2="bn" alpha3="brn" name="Brunei"/>
<country id="100" alpha2="bg" alpha3="bgr" name="Bulgaria"/>
<country id="854" alpha2="bf" alpha3="bfa" name="Burkina Faso"/>
<country id="108" alpha2="bi" alpha3="bdi" name="Burundi"/>
<country id="116" alpha2="kh" alpha3="khm" name="Cambodgia"/>
<country id="120" alpha2="cm" alpha3="cmr" name="Camerun"/>
<country id="124" alpha2="ca" alpha3="can" name="Canada"/>
<country id="531" alpha2="cw" alpha3="cuw" name="Curaao"/>
<country id="132" alpha2="cv" alpha3="cpv" name="Republica Capului Verde"/>
<country id="136" alpha2="ky" alpha3="cym" name="Insulele Cayman"/>
<country id="140" alpha2="cf" alpha3="caf" name="Republica Centrafrican"/>
<country id="148" alpha2="td" alpha3="tcd" name="Ciad"/>
<country id="152" alpha2="cl" alpha3="chl" name="Chile"/>
<country id="156" alpha2="cn" alpha3="chn" name="Republica Popular Chinez"/>
<country id="162" alpha2="cx" alpha3="cxr" name="Insula Crciunului"/>
<country id="166" alpha2="cc" alpha3="cck" name="Insulele Cocos"/>
<country id="170" alpha2="co" alpha3="col" name="Columbia"/>
<country id="174" alpha2="km" alpha3="com" name="Comore"/>
<country id="178" alpha2="cg" alpha3="cog" name="Congo"/>
<country id="180" alpha2="cd" alpha3="cod" name="Republica Democrat Congo"/>
<country id="184" alpha2="ck" alpha3="cok" name="Insulele Cook"/>
<country id="188" alpha2="cr" alpha3="cri" name="Costa Rica"/>
<country id="384" alpha2="ci" alpha3="civ" name="Coasta de Filde"/>
<country id="191" alpha2="hr" alpha3="hrv" name="Croaia"/>
<country id="192" alpha2="cu" alpha3="cub" name="Cuba"/>
<country id="196" alpha2="cy" alpha3="cyp" name="Cipru"/>
<country id="203" alpha2="cz" alpha3="cze" name="Cehia"/>
<country id="208" alpha2="dk" alpha3="dnk" name="Danemarca"/>
<country id="262" alpha2="dj" alpha3="dji" name="Djibouti"/>
<country id="212" alpha2="dm" alpha3="dma" name="Dominica"/>
<country id="214" alpha2="do" alpha3="dom" name="Republica Dominican"/>
<country id="218" alpha2="ec" alpha3="ecu" name="Ecuador"/>
<country id="818" alpha2="eg" alpha3="egy" name="Egipt"/>
<country id="222" alpha2="sv" alpha3="slv" name="El Salvador"/>
<country id="226" alpha2="gq" alpha3="gnq" name="Guineea Ecuatorial"/>
<country id="232" alpha2="er" alpha3="eri" name="Eritreea"/>
<country id="233" alpha2="ee" alpha3="est" name="Estonia"/>
<country id="748" alpha2="sz" alpha3="swz" name="Eswatini"/>
<country id="231" alpha2="et" alpha3="eth" name="Etiopia"/>
<country id="238" alpha2="fk" alpha3="flk" name="Insulele Falkland"/>
<country id="234" alpha2="fo" alpha3="fro" name="Insulele Feroe"/>
<country id="242" alpha2="fj" alpha3="fji" name="Fiji"/>
<country id="246" alpha2="fi" alpha3="fin" name="Finlanda"/>
<country id="250" alpha2="fr" alpha3="fra" name="Frana"/>
<country id="254" alpha2="gf" alpha3="guf" name="Guiana Francez"/>
<country id="258" alpha2="pf" alpha3="pyf" name="Polinezia francez"/>
<country id="260" alpha2="tf" alpha3="atf" name="Teritoriile australe i antarctice franceze"/>
<country id="266" alpha2="ga" alpha3="gab" name="Gabon"/>
<country id="270" alpha2="gm" alpha3="gmb" name="Gambia"/>
<country id="268" alpha2="ge" alpha3="geo" name="Georgia"/>
<country id="276" alpha2="de" alpha3="deu" name="Germania"/>
<country id="288" alpha2="gh" alpha3="gha" name="Ghana"/>
<country id="292" alpha2="gi" alpha3="gib" name="Gibraltar"/>
<country id="300" alpha2="gr" alpha3="grc" name="Grecia"/>
<country id="304" alpha2="gl" alpha3="grl" name="Groenlanda"/>
<country id="308" alpha2="gd" alpha3="grd" name="Grenada"/>
<country id="312" alpha2="gp" alpha3="glp" name="Guadelupa"/>
<country id="316" alpha2="gu" alpha3="gum" name="Guam"/>
<country id="320" alpha2="gt" alpha3="gtm" name="Guatemala"/>
<country id="831" alpha2="gg" alpha3="ggy" name="Guernsey"/>
<country id="324" alpha2="gn" alpha3="gin" name="Guineea"/>
<country id="624" alpha2="gw" alpha3="gnb" name="Guineea-Bissau"/>
<country id="328" alpha2="gy" alpha3="guy" name="Guyana"/>
<country id="332" alpha2="ht" alpha3="hti" name="Haiti"/>
<country id="334" alpha2="hm" alpha3="hmd" name="Insula Heard i Insulele McDonald"/>
<country id="336" alpha2="va" alpha3="vat" name="Vatican"/>
<country id="340" alpha2="hn" alpha3="hnd" name="Honduras"/>
<country id="344" alpha2="hk" alpha3="hkg" name="Hong Kong"/>
<country id="348" alpha2="hu" alpha3="hun" name="Ungaria"/>
<country id="352" alpha2="is" alpha3="isl" name="Islanda"/>
<country id="356" alpha2="in" alpha3="ind" name="India"/>
<country id="360" alpha2="id" alpha3="idn" name="Indonezia"/>
<country id="364" alpha2="ir" alpha3="irn" name="Iran"/>
<country id="368" alpha2="iq" alpha3="irq" name="Irak"/>
<country id="372" alpha2="ie" alpha3="irl" name="Republica Irlanda"/>
<country id="833" alpha2="im" alpha3="imn" name="Insula Man"/>
<country id="376" alpha2="il" alpha3="isr" name="Israel"/>
<country id="380" alpha2="it" alpha3="ita" name="Italia"/>
<country id="388" alpha2="jm" alpha3="jam" name="Jamaica"/>
<country id="392" alpha2="jp" alpha3="jpn" name="Japonia"/>
<country id="832" alpha2="je" alpha3="jey" name="Insula Jersey"/>
<country id="400" alpha2="jo" alpha3="jor" name="Iordania"/>
<country id="398" alpha2="kz" alpha3="kaz" name="Kazahstan"/>
<country id="404" alpha2="ke" alpha3="ken" name="Kenya"/>
<country id="296" alpha2="ki" alpha3="kir" name="Kiribati"/>
<country id="408" alpha2="kp" alpha3="prk" name="Coreea de Nord"/>
<country id="410" alpha2="kr" alpha3="kor" name="Coreea de Sud"/>
<country id="414" alpha2="kw" alpha3="kwt" name="Kuweit"/>
<country id="417" alpha2="kg" alpha3="kgz" name="Krgzstan"/>
<country id="418" alpha2="la" alpha3="lao" name="Laos"/>
<country id="428" alpha2="lv" alpha3="lva" name="Letonia"/>
<country id="422" alpha2="lb" alpha3="lbn" name="Liban"/>
<country id="426" alpha2="ls" alpha3="lso" name="Lesotho"/>
<country id="430" alpha2="lr" alpha3="lbr" name="Liberia"/>
<country id="434" alpha2="ly" alpha3="lby" name="Libia"/>
<country id="438" alpha2="li" alpha3="lie" name="Liechtenstein"/>
<country id="440" alpha2="lt" alpha3="ltu" name="Lituania"/>
<country id="442" alpha2="lu" alpha3="lux" name="Luxemburg"/>
<country id="446" alpha2="mo" alpha3="mac" name="Macao"/>
<country id="807" alpha2="mk" alpha3="mkd" name="Republica Macedonia"/>
<country id="450" alpha2="mg" alpha3="mdg" name="Madagascar"/>
<country id="454" alpha2="mw" alpha3="mwi" name="Malawi"/>
<country id="458" alpha2="my" alpha3="mys" name="Malaezia"/>
<country id="462" alpha2="mv" alpha3="mdv" name="Maldive"/>
<country id="466" alpha2="ml" alpha3="mli" name="Mali"/>
<country id="470" alpha2="mt" alpha3="mlt" name="Malta"/>
<country id="584" alpha2="mh" alpha3="mhl" name="Insulele Marshall"/>
<country id="474" alpha2="mq" alpha3="mtq" name="Martinica"/>
<country id="478" alpha2="mr" alpha3="mrt" name="Mauritania"/>
<country id="480" alpha2="mu" alpha3="mus" name="Mauritius"/>
<country id="175" alpha2="yt" alpha3="myt" name="Mayotte"/>
<country id="484" alpha2="mx" alpha3="mex" name="Mexic"/>
<country id="583" alpha2="fm" alpha3="fsm" name="Micronezia"/>
<country id="498" alpha2="md" alpha3="mda" name="Republica Moldova"/>
<country id="492" alpha2="mc" alpha3="mco" name="Monaco"/>
<country id="496" alpha2="mn" alpha3="mng" name="Mongolia"/>
<country id="499" alpha2="me" alpha3="mne" name="Muntenegru"/>
<country id="500" alpha2="ms" alpha3="msr" name="Montserrat"/>
<country id="504" alpha2="ma" alpha3="mar" name="Maroc"/>
<country id="508" alpha2="mz" alpha3="moz" name="Mozambic"/>
<country id="104" alpha2="mm" alpha3="mmr" name="Myanmar"/>
<country id="516" alpha2="na" alpha3="nam" name="Namibia"/>
<country id="520" alpha2="nr" alpha3="nru" name="Nauru"/>
<country id="524" alpha2="np" alpha3="npl" name="Nepal"/>
<country id="528" alpha2="nl" alpha3="nld" name="rile de Jos"/>
<country id="540" alpha2="nc" alpha3="ncl" name="Noua Caledonie"/>
<country id="554" alpha2="nz" alpha3="nzl" name="Noua Zeeland"/>
<country id="558" alpha2="ni" alpha3="nic" name="Nicaragua"/>
<country id="562" alpha2="ne" alpha3="ner" name="Niger"/>
<country id="566" alpha2="ng" alpha3="nga" name="Nigeria"/>
<country id="570" alpha2="nu" alpha3="niu" name="Niue"/>
<country id="574" alpha2="nf" alpha3="nfk" name="Insula Norfolk"/>
<country id="580" alpha2="mp" alpha3="mnp" name="Insulele Mariane de Nord"/>
<country id="578" alpha2="no" alpha3="nor" name="Norvegia"/>
<country id="512" alpha2="om" alpha3="omn" name="Oman"/>
<country id="586" alpha2="pk" alpha3="pak" name="Pakistan"/>
<country id="585" alpha2="pw" alpha3="plw" name="Palau"/>
<country id="275" alpha2="ps" alpha3="pse" name="Teritoriile Palestiniene Ocupate"/>
<country id="591" alpha2="pa" alpha3="pan" name="Panama"/>
<country id="598" alpha2="pg" alpha3="png" name="Papua Noua Guinee"/>
<country id="600" alpha2="py" alpha3="pry" name="Paraguay"/>
<country id="604" alpha2="pe" alpha3="per" name="Peru"/>
<country id="608" alpha2="ph" alpha3="phl" name="Filipine"/>
<country id="612" alpha2="pn" alpha3="pcn" name="Pitcairn"/>
<country id="616" alpha2="pl" alpha3="pol" name="Polonia"/>
<country id="620" alpha2="pt" alpha3="prt" name="Portugalia"/>
<country id="630" alpha2="pr" alpha3="pri" name="Puerto Rico"/>
<country id="634" alpha2="qa" alpha3="qat" name="Qatar"/>
<country id="638" alpha2="re" alpha3="reu" name="Runion"/>
<country id="642" alpha2="ro" alpha3="rou" name="Romnia"/>
<country id="643" alpha2="ru" alpha3="rus" name="Rusia"/>
<country id="646" alpha2="rw" alpha3="rwa" name="Rwanda"/>
<country id="652" alpha2="bl" alpha3="blm" name="Saint Barthlemy"/>
<country id="654" alpha2="sh" alpha3="shn" name="Sfnta Elena"/>
<country id="659" alpha2="kn" alpha3="kna" name="Sfntul Kitts i Nevis"/>
<country id="662" alpha2="lc" alpha3="lca" name="Sfnta Lucia"/>
<country id="663" alpha2="mf" alpha3="maf" name="Sint Maarten (partea francez)"/>
<country id="666" alpha2="pm" alpha3="spm" name="Sfntul Pierre i Miquelon"/>
<country id="670" alpha2="vc" alpha3="vct" name="Sfntul Vincent i Grenadine"/>
<country id="882" alpha2="ws" alpha3="wsm" name="Samoa"/>
<country id="674" alpha2="sm" alpha3="smr" name="San Marino"/>
<country id="678" alpha2="st" alpha3="stp" name="Sao Tome i Principe"/>
<country id="682" alpha2="sa" alpha3="sau" name="Arabia Saudit"/>
<country id="686" alpha2="sn" alpha3="sen" name="Senegal"/>
<country id="688" alpha2="rs" alpha3="srb" name="Serbia"/>
<country id="690" alpha2="sc" alpha3="syc" name="Seychelles"/>
<country id="694" alpha2="sl" alpha3="sle" name="Sierra Leone"/>
<country id="702" alpha2="sg" alpha3="sgp" name="Singapore"/>
<country id="534" alpha2="sx" alpha3="sxm" name="Sint Maarten (partea olandez)"/>
<country id="703" alpha2="sk" alpha3="svk" name="Slovacia"/>
<country id="705" alpha2="si" alpha3="svn" name="Slovenia"/>
<country id="90" alpha2="sb" alpha3="slb" name="Insulele Solomon"/>
<country id="706" alpha2="so" alpha3="som" name="Somalia"/>
<country id="710" alpha2="za" alpha3="zaf" name="Africa de Sud"/>
<country id="239" alpha2="gs" alpha3="sgs" name="Georgia de Sud i Insulele Sandwich de Sud"/>
<country id="724" alpha2="es" alpha3="esp" name="Spania"/>
<country id="144" alpha2="lk" alpha3="lka" name="Sri Lanka"/>
<country id="729" alpha2="sd" alpha3="sdn" name="Sudan"/>
<country id="728" alpha2="ss" alpha3="ssd" name="Sudanul de Sud"/>
<country id="740" alpha2="sr" alpha3="sur" name="Surinam"/>
<country id="744" alpha2="sj" alpha3="sjm" name="Svalbard i Jan Mayen"/>
<country id="752" alpha2="se" alpha3="swe" name="Suedia"/>
<country id="756" alpha2="ch" alpha3="che" name="Elveia"/>
<country id="760" alpha2="sy" alpha3="syr" name="Siria"/>
<country id="158" alpha2="tw" alpha3="twn" name="Taiwan"/>
<country id="762" alpha2="tj" alpha3="tjk" name="Tadjikistan"/>
<country id="834" alpha2="tz" alpha3="tza" name="Tanzania"/>
<country id="764" alpha2="th" alpha3="tha" name="Thailanda"/>
<country id="626" alpha2="tl" alpha3="tls" name="Timorul de Est"/>
<country id="768" alpha2="tg" alpha3="tgo" name="Togo"/>
<country id="772" alpha2="tk" alpha3="tkl" name="Tokelau"/>
<country id="776" alpha2="to" alpha3="ton" name="Tonga"/>
<country id="780" alpha2="tt" alpha3="tto" name="Trinidad i Tobago"/>
<country id="788" alpha2="tn" alpha3="tun" name="Tunisia"/>
<country id="792" alpha2="tr" alpha3="tur" name="Turcia"/>
<country id="795" alpha2="tm" alpha3="tkm" name="Turkmenistan"/>
<country id="796" alpha2="tc" alpha3="tca" name="Insulele Turks i Caicos"/>
<country id="798" alpha2="tv" alpha3="tuv" name="Tuvalu"/>
<country id="800" alpha2="ug" alpha3="uga" name="Uganda"/>
<country id="804" alpha2="ua" alpha3="ukr" name="Ucraina"/>
<country id="784" alpha2="ae" alpha3="are" name="Emiratele Arabe Unite"/>
<country id="826" alpha2="gb" alpha3="gbr" name="Regatul Unit"/>
<country id="840" alpha2="us" alpha3="usa" name="Statele Unite ale Americii"/>
<country id="581" alpha2="um" alpha3="umi" name="United States Minor Outlying Islands"/>
<country id="858" alpha2="uy" alpha3="ury" name="Uruguay"/>
<country id="860" alpha2="uz" alpha3="uzb" name="Uzbekistan"/>
<country id="548" alpha2="vu" alpha3="vut" name="Vanuatu"/>
<country id="862" alpha2="ve" alpha3="ven" name="Venezuela"/>
<country id="704" alpha2="vn" alpha3="vnm" name="Vietnam"/>
<country id="92" alpha2="vg" alpha3="vgb" name="Insulele Virgine Britanice"/>
<country id="850" alpha2="vi" alpha3="vir" name="Insulele Virgine Americane"/>
<country id="876" alpha2="wf" alpha3="wlf" name="Wallis i Futuna"/>
<country id="732" alpha2="eh" alpha3="esh" name="Sahara Occidental"/>
<country id="887" alpha2="ye" alpha3="yem" name="Yemen"/>
<country id="894" alpha2="zm" alpha3="zmb" name="Zambia"/>
<country id="716" alpha2="zw" alpha3="zwe" name="Zimbabwe"/>
</countries>
``` | /content/code_sandbox/data/countries/ro/world.xml | xml | 2016-01-27T21:41:04 | 2024-08-16T10:07:17 | world_countries | stefangabos/world_countries | 1,364 | 6,020 |
```xml
import { HeadlessSuperConverter } from '@/Components/SuperEditor/Tools/HeadlessSuperConverter'
const InitialHTML = `<div>
<h1>This is a demo of Super notes</h1>
<p><br></p>
<p>Super notes are our new <b>rich text</b> experience. With Super notes, you can create <b>rich</b>, <i>dynamic</i> text with powerful options.</p>
<p><br></p>
<h2><span>Lists</span></h2>
<p><br></p>
<ul>
<li value="1"><span>Type </span><code spellcheck="false"><span>-</span></code><span> followed by a space in begin a
list</span></li>
<li value="2"><span>Type </span><code spellcheck="false"><span>1.</span></code><span> followed by a space in begin a numbered
list</span></li>
<li value="3"><span>Type </span><code spellcheck="false"><span>[]</span></code><span> followed by a space
to begin a checklist </span></li>
</ul>
<p><br></p>
<ul>
<li value="1"><span>A list</span></li>
<li value="2">
<ul>
<li value="1"><span>Indent the list</span></li>
<li value="2">
<ul>
<li value="1"><span>And even more</span></li>
</ul>
</li>
</ul>
</li>
</ul>
<p><br></p>
<ol>
<li value="1"><span>A numbered list</span></li>
<li value="2"><span>With multiple levels</span></li>
<li value="3"><span>And even more</span></li>
</ol>
<p><br></p>
<ul __lexicallisttype="check">
<li role="checkbox" tabindex="-1" aria-checked="false" value="1">
<span>Create</span>
</li>
<li role="checkbox" tabindex="-1" aria-checked="true" value="2">
<span>a</span>
</li>
<li role="checkbox" tabindex="-1" aria-checked="true" value="3">
<span>checklist</span>
</li>
</ul>
<p><br></p>
<h2><span>Images</span></h2>
<p><br></p>
<p>You can add images to your note by selecting the "Image from URL" option from the <code spellcheck="false"><span>/</span></code> menu or Insert menu in the toolbar.</p>
<p><br></p>
<p><img src="path_to_url" /></p>
<p><br></p>
<h2><span>Collapsible sections</span></h2>
<p><br></p>
<details open="">
<summary><span>Collapsible section</span></summary>
<div data-lexical-collapsible-content="true">
<p><span>Collapsible sections can include all
other types of content like</span></p>
<p><br></p>
<h2><span>Heading</span></h2>
<p><br></p>
<ul>
<li value="1"><span>a list</span></li>
</ul>
<ol>
<li value="1"><span>numbered</span></li>
</ol>
<ul __lexicallisttype="check">
<li role="checkbox" tabindex="-1" aria-checked="false" value="1"><span>check
list</span>
</li>
</ul>
<p><br></p>
<pre spellcheck="false" data-highlight-language="javascript"><span>A</span><span> code block</span></pre>
<p><br></p>
<p><span>You can even nest collapsible
sections.</span></p>
<p><br></p>
<details open="">
<summary><span>Nested collapsible section</span></summary>
<div data-lexical-collapsible-content="true">
<blockquote><span>Quote</span></blockquote>
</div>
</details>
</div>
</details>
<p><br></p>
<h2><span>Code blocks</span></h2>
<p><br></p>
<p><span>Type </span><code spellcheck="false"><span >\`\`\`</span></code><span> followed by a space to create a code
block. You can choose the language when your
cursor is within the code block.</span></p>
<p><br></p>
<pre spellcheck="false"
data-highlight-language="js"><span >function</span><span> </span><span >main</span><span >(</span><span >)</span><span> </span><span >{</span><br><span> </span><span >const</span><span> variable </span><span >=</span><span> </span><span >"string"</span><span >;</span><br><span> </span><span >return</span><span> </span><span >TEST</span><span >;</span><br><span >}</span></pre>
<p><br></p>
<h2><span>Tables</span></h2>
<table>
<colgroup>
<col>
<col>
<col>
</colgroup>
<tbody>
<tr>
<th>
<p><span>Header</span></p>
</th>
<th>
<p><span>Column 1</span></p>
</th>
<th>
<p><span>Column 2</span></p>
</th>
</tr>
<tr>
<th>
<p><span>Row 1</span></p>
</th>
<td>
<p><span>Row 1 x Column 1</span></p>
</td>
<td>
<p><span>Row 1 x Column 2</span></p>
</td>
</tr>
<tr>
<th>
<p><span>Row 2</span></p>
</th>
<td>
<p><span>Row 2 x Column 1</span></p>
</td>
<td>
<p><span>Row 2 x Column 2</span></p>
</td>
</tr>
</tbody>
</table>
<p><br></p>
<h2><span>Passwords</span></h2>
<p><span>You can generate a secure password using
the "Generate password" command using the </span><code spellcheck="false"><span >/</span></code><span>
menu.</span></p>
<p><br></p>
<ul>
<li value="1"><span>}:hcMrIFgaijpkyz</span></li>
<li value="2"><span>*raF/qi$m?y?iiBS</span></li>
<li value="3"><span>YuVmWf(gOD&=vjbB</span></li>
</ul>
</div>`
export function SuperDemoInitialValue() {
return new HeadlessSuperConverter().convertOtherFormatToSuperString(InitialHTML, 'html', {
html: {
addLineBreaks: false,
},
})
}
``` | /content/code_sandbox/packages/web/src/javascripts/Components/PremiumFeaturesModal/Subviews/SuperDemoInitialValue.ts | xml | 2016-12-05T23:31:33 | 2024-08-16T06:51:19 | app | standardnotes/app | 5,180 | 1,716 |
```xml
import { RequestResponseChannels, RequestChannels } from './ipc-shared'
// eslint-disable-next-line no-restricted-imports
import { ipcRenderer, IpcRendererEvent } from 'electron'
/**
* Send a message to the main process via channel and expect a result
* asynchronously. This is the equivalent of ipcRenderer.invoke except with
* strong typing guarantees.
*/
export function invoke<T extends keyof RequestResponseChannels>(
channel: T,
...args: Parameters<RequestResponseChannels[T]>
): ReturnType<RequestResponseChannels[T]> {
return ipcRenderer.invoke(channel, ...args) as any
}
/**
* Send a message to the main process via channel asynchronously. This is the
* equivalent of ipcRenderer.send except with strong typing guarantees.
*/
export function send<T extends keyof RequestChannels>(
channel: T,
...args: Parameters<RequestChannels[T]>
): void {
return ipcRenderer.send(channel, ...args) as any
}
/**
* Send a message to the main process via channel synchronously. This is the
* equivalent of ipcRenderer.sendSync except with strong typing guarantees.
*/
export function sendSync<T extends keyof RequestChannels>(
channel: T,
...args: Parameters<RequestChannels[T]>
): void {
// eslint-disable-next-line no-sync
return ipcRenderer.sendSync(channel, ...args) as any
}
/**
* Subscribes to the specified IPC channel and provides strong typing of
* the channel name, and request parameters. This is the equivalent of
* using ipcRenderer.on.
*/
export function on<T extends keyof RequestChannels>(
channel: T,
listener: (
event: IpcRendererEvent,
...args: Parameters<RequestChannels[T]>
) => void
) {
ipcRenderer.on(channel, listener as any)
}
/**
* Subscribes to the specified IPC channel and provides strong typing of
* the channel name, and request parameters. This is the equivalent of
* using ipcRenderer.once
*/
export function once<T extends keyof RequestChannels>(
channel: T,
listener: (
event: IpcRendererEvent,
...args: Parameters<RequestChannels[T]>
) => void
) {
ipcRenderer.once(channel, listener as any)
}
/**
* Unsubscribes from the specified IPC channel and provides strong typing of
* the channel name, and request parameters. This is the equivalent of
* using ipcRenderer.removeListener
*/
export function removeListener<T extends keyof RequestChannels>(
channel: T,
listener: (
event: IpcRendererEvent,
...args: Parameters<RequestChannels[T]>
) => void
) {
ipcRenderer.removeListener(channel, listener as any)
}
``` | /content/code_sandbox/app/src/lib/ipc-renderer.ts | xml | 2016-05-11T15:59:00 | 2024-08-16T17:00:41 | desktop | desktop/desktop | 19,544 | 558 |
```xml
import { Subject, filter, firstValueFrom, map, merge, timeout } from "rxjs";
import {
PinServiceAbstraction,
PinService,
InternalUserDecryptionOptionsServiceAbstraction,
UserDecryptionOptionsService,
AuthRequestServiceAbstraction,
AuthRequestService,
LoginEmailServiceAbstraction,
LogoutReason,
} from "@bitwarden/auth/common";
import { ApiService as ApiServiceAbstraction } from "@bitwarden/common/abstractions/api.service";
import { AuditService as AuditServiceAbstraction } from "@bitwarden/common/abstractions/audit.service";
import { EventCollectionService as EventCollectionServiceAbstraction } from "@bitwarden/common/abstractions/event/event-collection.service";
import { EventUploadService as EventUploadServiceAbstraction } from "@bitwarden/common/abstractions/event/event-upload.service";
import { NotificationsService as NotificationsServiceAbstraction } from "@bitwarden/common/abstractions/notifications.service";
import { SearchService as SearchServiceAbstraction } from "@bitwarden/common/abstractions/search.service";
import { VaultTimeoutSettingsService as VaultTimeoutSettingsServiceAbstraction } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service";
import { InternalOrganizationServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
import { InternalPolicyService as InternalPolicyServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { ProviderService as ProviderServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { OrganizationService } from "@bitwarden/common/admin-console/services/organization/organization.service";
import { PolicyApiService } from "@bitwarden/common/admin-console/services/policy/policy-api.service";
import { PolicyService } from "@bitwarden/common/admin-console/services/policy/policy.service";
import { ProviderService } from "@bitwarden/common/admin-console/services/provider.service";
import { AccountService as AccountServiceAbstraction } from "@bitwarden/common/auth/abstractions/account.service";
import { AuthService as AuthServiceAbstraction } from "@bitwarden/common/auth/abstractions/auth.service";
import { AvatarService as AvatarServiceAbstraction } from "@bitwarden/common/auth/abstractions/avatar.service";
import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust.service.abstraction";
import { DevicesServiceAbstraction } from "@bitwarden/common/auth/abstractions/devices/devices.service.abstraction";
import { DevicesApiServiceAbstraction } from "@bitwarden/common/auth/abstractions/devices-api.service.abstraction";
import { KdfConfigService as kdfConfigServiceAbstraction } from "@bitwarden/common/auth/abstractions/kdf-config.service";
import { KeyConnectorService as KeyConnectorServiceAbstraction } from "@bitwarden/common/auth/abstractions/key-connector.service";
import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction";
import { SsoLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/sso-login.service.abstraction";
import { TokenService as TokenServiceAbstraction } from "@bitwarden/common/auth/abstractions/token.service";
import { UserVerificationApiServiceAbstraction } from "@bitwarden/common/auth/abstractions/user-verification/user-verification-api.service.abstraction";
import { UserVerificationService as UserVerificationServiceAbstraction } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/force-set-password-reason";
import { AccountServiceImplementation } from "@bitwarden/common/auth/services/account.service";
import { AuthService } from "@bitwarden/common/auth/services/auth.service";
import { AvatarService } from "@bitwarden/common/auth/services/avatar.service";
import { DeviceTrustService } from "@bitwarden/common/auth/services/device-trust.service.implementation";
import { DevicesServiceImplementation } from "@bitwarden/common/auth/services/devices/devices.service.implementation";
import { DevicesApiServiceImplementation } from "@bitwarden/common/auth/services/devices-api.service.implementation";
import { KdfConfigService } from "@bitwarden/common/auth/services/kdf-config.service";
import { KeyConnectorService } from "@bitwarden/common/auth/services/key-connector.service";
import { MasterPasswordService } from "@bitwarden/common/auth/services/master-password/master-password.service";
import { SsoLoginService } from "@bitwarden/common/auth/services/sso-login.service";
import { TokenService } from "@bitwarden/common/auth/services/token.service";
import { UserVerificationApiService } from "@bitwarden/common/auth/services/user-verification/user-verification-api.service";
import { UserVerificationService } from "@bitwarden/common/auth/services/user-verification/user-verification.service";
import {
AutofillSettingsServiceAbstraction,
AutofillSettingsService,
} from "@bitwarden/common/autofill/services/autofill-settings.service";
import {
BadgeSettingsServiceAbstraction,
BadgeSettingsService,
} from "@bitwarden/common/autofill/services/badge-settings.service";
import {
DomainSettingsService,
DefaultDomainSettingsService,
} from "@bitwarden/common/autofill/services/domain-settings.service";
import {
UserNotificationSettingsService,
UserNotificationSettingsServiceAbstraction,
} from "@bitwarden/common/autofill/services/user-notification-settings.service";
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
import { DefaultBillingAccountProfileStateService } from "@bitwarden/common/billing/services/account/billing-account-profile-state.service";
import { ClientType } from "@bitwarden/common/enums";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
import { AppIdService as AppIdServiceAbstraction } from "@bitwarden/common/platform/abstractions/app-id.service";
import { ConfigApiServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config-api.service.abstraction";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto-function.service";
import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service";
import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service";
import { Fido2AuthenticatorService as Fido2AuthenticatorServiceAbstraction } from "@bitwarden/common/platform/abstractions/fido2/fido2-authenticator.service.abstraction";
import { Fido2ClientService as Fido2ClientServiceAbstraction } from "@bitwarden/common/platform/abstractions/fido2/fido2-client.service.abstraction";
import { Fido2UserInterfaceService as Fido2UserInterfaceServiceAbstraction } from "@bitwarden/common/platform/abstractions/fido2/fido2-user-interface.service.abstraction";
import { FileUploadService as FileUploadServiceAbstraction } from "@bitwarden/common/platform/abstractions/file-upload/file-upload.service";
import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platform/abstractions/i18n.service";
import { KeyGenerationService as KeyGenerationServiceAbstraction } from "@bitwarden/common/platform/abstractions/key-generation.service";
import { LogService as LogServiceAbstraction } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { StateService as StateServiceAbstraction } from "@bitwarden/common/platform/abstractions/state.service";
import {
AbstractStorageService,
ObservableStorageService,
} from "@bitwarden/common/platform/abstractions/storage.service";
import { SystemService as SystemServiceAbstraction } from "@bitwarden/common/platform/abstractions/system.service";
import {
BiometricStateService,
DefaultBiometricStateService,
} from "@bitwarden/common/platform/biometrics/biometric-state.service";
import { StateFactory } from "@bitwarden/common/platform/factories/state-factory";
import { Message, MessageListener, MessageSender } from "@bitwarden/common/platform/messaging";
// eslint-disable-next-line no-restricted-imports -- Used for dependency creation
import { SubjectMessageSender } from "@bitwarden/common/platform/messaging/internal";
import { Lazy } from "@bitwarden/common/platform/misc/lazy";
import { clearCaches } from "@bitwarden/common/platform/misc/sequentialize";
import { Account } from "@bitwarden/common/platform/models/domain/account";
import { GlobalState } from "@bitwarden/common/platform/models/domain/global-state";
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
import { ScheduledTaskNames } from "@bitwarden/common/platform/scheduling";
import { AppIdService } from "@bitwarden/common/platform/services/app-id.service";
import { ConfigApiService } from "@bitwarden/common/platform/services/config/config-api.service";
import { DefaultConfigService } from "@bitwarden/common/platform/services/config/default-config.service";
import { ConsoleLogService } from "@bitwarden/common/platform/services/console-log.service";
import { ContainerService } from "@bitwarden/common/platform/services/container.service";
import { BulkEncryptServiceImplementation } from "@bitwarden/common/platform/services/cryptography/bulk-encrypt.service.implementation";
import { EncryptServiceImplementation } from "@bitwarden/common/platform/services/cryptography/encrypt.service.implementation";
import { FallbackBulkEncryptService } from "@bitwarden/common/platform/services/cryptography/fallback-bulk-encrypt.service";
import { MultithreadEncryptServiceImplementation } from "@bitwarden/common/platform/services/cryptography/multithread-encrypt.service.implementation";
import { Fido2ActiveRequestManager } from "@bitwarden/common/platform/services/fido2/fido2-active-request-manager";
import { Fido2AuthenticatorService } from "@bitwarden/common/platform/services/fido2/fido2-authenticator.service";
import { Fido2ClientService } from "@bitwarden/common/platform/services/fido2/fido2-client.service";
import { FileUploadService } from "@bitwarden/common/platform/services/file-upload/file-upload.service";
import { KeyGenerationService } from "@bitwarden/common/platform/services/key-generation.service";
import { MigrationBuilderService } from "@bitwarden/common/platform/services/migration-builder.service";
import { MigrationRunner } from "@bitwarden/common/platform/services/migration-runner";
import { StateService } from "@bitwarden/common/platform/services/state.service";
import { SystemService } from "@bitwarden/common/platform/services/system.service";
import { UserAutoUnlockKeyService } from "@bitwarden/common/platform/services/user-auto-unlock-key.service";
import { WebCryptoFunctionService } from "@bitwarden/common/platform/services/web-crypto-function.service";
import {
ActiveUserStateProvider,
DerivedStateProvider,
GlobalStateProvider,
SingleUserStateProvider,
StateEventRunnerService,
StateProvider,
} from "@bitwarden/common/platform/state";
/* eslint-disable import/no-restricted-paths -- We need the implementation to inject, but generally these should not be accessed */
import { DefaultActiveUserStateProvider } from "@bitwarden/common/platform/state/implementations/default-active-user-state.provider";
import { DefaultGlobalStateProvider } from "@bitwarden/common/platform/state/implementations/default-global-state.provider";
import { DefaultSingleUserStateProvider } from "@bitwarden/common/platform/state/implementations/default-single-user-state.provider";
import { DefaultStateProvider } from "@bitwarden/common/platform/state/implementations/default-state.provider";
import { InlineDerivedStateProvider } from "@bitwarden/common/platform/state/implementations/inline-derived-state";
import { StateEventRegistrarService } from "@bitwarden/common/platform/state/state-event-registrar.service";
/* eslint-enable import/no-restricted-paths */
import { PrimarySecondaryStorageService } from "@bitwarden/common/platform/storage/primary-secondary-storage.service";
import { WindowStorageService } from "@bitwarden/common/platform/storage/window-storage.service";
import { SyncService } from "@bitwarden/common/platform/sync";
// eslint-disable-next-line no-restricted-imports -- Needed for service creation
import { DefaultSyncService } from "@bitwarden/common/platform/sync/internal";
import { DefaultThemeStateService } from "@bitwarden/common/platform/theming/theme-state.service";
import { ApiService } from "@bitwarden/common/services/api.service";
import { AuditService } from "@bitwarden/common/services/audit.service";
import { EventCollectionService } from "@bitwarden/common/services/event/event-collection.service";
import { EventUploadService } from "@bitwarden/common/services/event/event-upload.service";
import { NotificationsService } from "@bitwarden/common/services/notifications.service";
import { SearchService } from "@bitwarden/common/services/search.service";
import { VaultTimeoutSettingsService } from "@bitwarden/common/services/vault-timeout/vault-timeout-settings.service";
import {
PasswordStrengthService,
PasswordStrengthServiceAbstraction,
} from "@bitwarden/common/tools/password-strength";
import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service";
import { SendApiService as SendApiServiceAbstraction } from "@bitwarden/common/tools/send/services/send-api.service.abstraction";
import { SendStateProvider } from "@bitwarden/common/tools/send/services/send-state.provider";
import { SendService } from "@bitwarden/common/tools/send/services/send.service";
import { InternalSendService as InternalSendServiceAbstraction } from "@bitwarden/common/tools/send/services/send.service.abstraction";
import { UserId } from "@bitwarden/common/types/guid";
import { VaultTimeoutStringType } from "@bitwarden/common/types/vault-timeout.type";
import { CipherService as CipherServiceAbstraction } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CollectionService as CollectionServiceAbstraction } from "@bitwarden/common/vault/abstractions/collection.service";
import { CipherFileUploadService as CipherFileUploadServiceAbstraction } from "@bitwarden/common/vault/abstractions/file-upload/cipher-file-upload.service";
import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction";
import { InternalFolderService as InternalFolderServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction";
import { TotpService as TotpServiceAbstraction } from "@bitwarden/common/vault/abstractions/totp.service";
import { VaultSettingsService as VaultSettingsServiceAbstraction } from "@bitwarden/common/vault/abstractions/vault-settings/vault-settings.service";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { CipherService } from "@bitwarden/common/vault/services/cipher.service";
import { CollectionService } from "@bitwarden/common/vault/services/collection.service";
import { CipherFileUploadService } from "@bitwarden/common/vault/services/file-upload/cipher-file-upload.service";
import { FolderApiService } from "@bitwarden/common/vault/services/folder/folder-api.service";
import { FolderService } from "@bitwarden/common/vault/services/folder/folder.service";
import { TotpService } from "@bitwarden/common/vault/services/totp.service";
import { VaultSettingsService } from "@bitwarden/common/vault/services/vault-settings/vault-settings.service";
import {
legacyPasswordGenerationServiceFactory,
PasswordGenerationServiceAbstraction,
legacyUsernameGenerationServiceFactory,
UsernameGenerationServiceAbstraction,
} from "@bitwarden/generator-legacy";
import {
ImportApiService,
ImportApiServiceAbstraction,
ImportService,
ImportServiceAbstraction,
} from "@bitwarden/importer/core";
import {
IndividualVaultExportService,
IndividualVaultExportServiceAbstraction,
OrganizationVaultExportService,
OrganizationVaultExportServiceAbstraction,
VaultExportService,
VaultExportServiceAbstraction,
} from "@bitwarden/vault-export-core";
import { OverlayBackground as OverlayBackgroundInterface } from "../autofill/background/abstractions/overlay.background";
import { AutoSubmitLoginBackground } from "../autofill/background/auto-submit-login.background";
import ContextMenusBackground from "../autofill/background/context-menus.background";
import NotificationBackground from "../autofill/background/notification.background";
import { OverlayBackground } from "../autofill/background/overlay.background";
import TabsBackground from "../autofill/background/tabs.background";
import WebRequestBackground from "../autofill/background/web-request.background";
import { CipherContextMenuHandler } from "../autofill/browser/cipher-context-menu-handler";
import { ContextMenuClickedHandler } from "../autofill/browser/context-menu-clicked-handler";
import { MainContextMenuHandler } from "../autofill/browser/main-context-menu-handler";
import LegacyOverlayBackground from "../autofill/deprecated/background/overlay.background.deprecated";
import { Fido2Background as Fido2BackgroundAbstraction } from "../autofill/fido2/background/abstractions/fido2.background";
import { Fido2Background } from "../autofill/fido2/background/fido2.background";
import { BrowserFido2UserInterfaceService } from "../autofill/fido2/services/browser-fido2-user-interface.service";
import { AutofillService as AutofillServiceAbstraction } from "../autofill/services/abstractions/autofill.service";
import AutofillService from "../autofill/services/autofill.service";
import { SafariApp } from "../browser/safariApp";
import { BrowserApi } from "../platform/browser/browser-api";
import { UpdateBadge } from "../platform/listeners/update-badge";
/* eslint-disable no-restricted-imports */
import { ChromeMessageSender } from "../platform/messaging/chrome-message.sender";
/* eslint-enable no-restricted-imports */
import { OffscreenDocumentService } from "../platform/offscreen-document/abstractions/offscreen-document";
import { DefaultOffscreenDocumentService } from "../platform/offscreen-document/offscreen-document.service";
import { BrowserTaskSchedulerService } from "../platform/services/abstractions/browser-task-scheduler.service";
import { BrowserCryptoService } from "../platform/services/browser-crypto.service";
import { BrowserEnvironmentService } from "../platform/services/browser-environment.service";
import BrowserLocalStorageService from "../platform/services/browser-local-storage.service";
import BrowserMemoryStorageService from "../platform/services/browser-memory-storage.service";
import { BrowserScriptInjectorService } from "../platform/services/browser-script-injector.service";
import I18nService from "../platform/services/i18n.service";
import { LocalBackedSessionStorageService } from "../platform/services/local-backed-session-storage.service";
import { BackgroundPlatformUtilsService } from "../platform/services/platform-utils/background-platform-utils.service";
import { BrowserPlatformUtilsService } from "../platform/services/platform-utils/browser-platform-utils.service";
import { PopupViewCacheBackgroundService } from "../platform/services/popup-view-cache-background.service";
import { BackgroundTaskSchedulerService } from "../platform/services/task-scheduler/background-task-scheduler.service";
import { ForegroundTaskSchedulerService } from "../platform/services/task-scheduler/foreground-task-scheduler.service";
import { BackgroundMemoryStorageService } from "../platform/storage/background-memory-storage.service";
import { BrowserStorageServiceProvider } from "../platform/storage/browser-storage-service.provider";
import { ForegroundMemoryStorageService } from "../platform/storage/foreground-memory-storage.service";
import { OffscreenStorageService } from "../platform/storage/offscreen-storage.service";
import { ForegroundSyncService } from "../platform/sync/foreground-sync.service";
import { SyncServiceListener } from "../platform/sync/sync-service.listener";
import { fromChromeRuntimeMessaging } from "../platform/utils/from-chrome-runtime-messaging";
import VaultTimeoutService from "../services/vault-timeout/vault-timeout.service";
import FilelessImporterBackground from "../tools/background/fileless-importer.background";
import { VaultFilterService } from "../vault/services/vault-filter.service";
import CommandsBackground from "./commands.background";
import IdleBackground from "./idle.background";
import { NativeMessagingBackground } from "./nativeMessaging.background";
import RuntimeBackground from "./runtime.background";
export default class MainBackground {
messagingService: MessageSender;
storageService: BrowserLocalStorageService;
secureStorageService: AbstractStorageService;
memoryStorageService: AbstractStorageService;
memoryStorageForStateProviders: AbstractStorageService & ObservableStorageService;
largeObjectMemoryStorageForStateProviders: AbstractStorageService & ObservableStorageService;
i18nService: I18nServiceAbstraction;
platformUtilsService: PlatformUtilsServiceAbstraction;
logService: LogServiceAbstraction;
keyGenerationService: KeyGenerationServiceAbstraction;
cryptoService: CryptoServiceAbstraction;
cryptoFunctionService: CryptoFunctionServiceAbstraction;
masterPasswordService: InternalMasterPasswordServiceAbstraction;
tokenService: TokenServiceAbstraction;
appIdService: AppIdServiceAbstraction;
apiService: ApiServiceAbstraction;
environmentService: BrowserEnvironmentService;
cipherService: CipherServiceAbstraction;
folderService: InternalFolderServiceAbstraction;
userDecryptionOptionsService: InternalUserDecryptionOptionsServiceAbstraction;
collectionService: CollectionServiceAbstraction;
vaultTimeoutService: VaultTimeoutService;
vaultTimeoutSettingsService: VaultTimeoutSettingsServiceAbstraction;
passwordGenerationService: PasswordGenerationServiceAbstraction;
syncService: SyncService;
passwordStrengthService: PasswordStrengthServiceAbstraction;
totpService: TotpServiceAbstraction;
autofillService: AutofillServiceAbstraction;
containerService: ContainerService;
auditService: AuditServiceAbstraction;
authService: AuthServiceAbstraction;
loginEmailService: LoginEmailServiceAbstraction;
importApiService: ImportApiServiceAbstraction;
importService: ImportServiceAbstraction;
exportService: VaultExportServiceAbstraction;
searchService: SearchServiceAbstraction;
notificationsService: NotificationsServiceAbstraction;
stateService: StateServiceAbstraction;
userNotificationSettingsService: UserNotificationSettingsServiceAbstraction;
autofillSettingsService: AutofillSettingsServiceAbstraction;
badgeSettingsService: BadgeSettingsServiceAbstraction;
domainSettingsService: DomainSettingsService;
systemService: SystemServiceAbstraction;
eventCollectionService: EventCollectionServiceAbstraction;
eventUploadService: EventUploadServiceAbstraction;
policyService: InternalPolicyServiceAbstraction;
sendService: InternalSendServiceAbstraction;
sendStateProvider: SendStateProvider;
fileUploadService: FileUploadServiceAbstraction;
cipherFileUploadService: CipherFileUploadServiceAbstraction;
organizationService: InternalOrganizationServiceAbstraction;
providerService: ProviderServiceAbstraction;
keyConnectorService: KeyConnectorServiceAbstraction;
userVerificationService: UserVerificationServiceAbstraction;
vaultFilterService: VaultFilterService;
usernameGenerationService: UsernameGenerationServiceAbstraction;
encryptService: EncryptService;
bulkEncryptService: FallbackBulkEncryptService;
folderApiService: FolderApiServiceAbstraction;
policyApiService: PolicyApiServiceAbstraction;
sendApiService: SendApiServiceAbstraction;
userVerificationApiService: UserVerificationApiServiceAbstraction;
fido2UserInterfaceService: Fido2UserInterfaceServiceAbstraction;
fido2AuthenticatorService: Fido2AuthenticatorServiceAbstraction;
fido2ClientService: Fido2ClientServiceAbstraction;
avatarService: AvatarServiceAbstraction;
mainContextMenuHandler: MainContextMenuHandler;
cipherContextMenuHandler: CipherContextMenuHandler;
configService: ConfigService;
configApiService: ConfigApiServiceAbstraction;
devicesApiService: DevicesApiServiceAbstraction;
devicesService: DevicesServiceAbstraction;
deviceTrustService: DeviceTrustServiceAbstraction;
authRequestService: AuthRequestServiceAbstraction;
accountService: AccountServiceAbstraction;
globalStateProvider: GlobalStateProvider;
pinService: PinServiceAbstraction;
singleUserStateProvider: SingleUserStateProvider;
activeUserStateProvider: ActiveUserStateProvider;
derivedStateProvider: DerivedStateProvider;
stateProvider: StateProvider;
taskSchedulerService: BrowserTaskSchedulerService;
fido2Background: Fido2BackgroundAbstraction;
individualVaultExportService: IndividualVaultExportServiceAbstraction;
organizationVaultExportService: OrganizationVaultExportServiceAbstraction;
vaultSettingsService: VaultSettingsServiceAbstraction;
biometricStateService: BiometricStateService;
stateEventRunnerService: StateEventRunnerService;
ssoLoginService: SsoLoginServiceAbstraction;
billingAccountProfileStateService: BillingAccountProfileStateService;
// eslint-disable-next-line rxjs/no-exposed-subjects -- Needed to give access to services module
intraprocessMessagingSubject: Subject<Message<Record<string, unknown>>>;
userAutoUnlockKeyService: UserAutoUnlockKeyService;
scriptInjectorService: BrowserScriptInjectorService;
kdfConfigService: kdfConfigServiceAbstraction;
offscreenDocumentService: OffscreenDocumentService;
syncServiceListener: SyncServiceListener;
themeStateService: DefaultThemeStateService;
autoSubmitLoginBackground: AutoSubmitLoginBackground;
onUpdatedRan: boolean;
onReplacedRan: boolean;
loginToAutoFill: CipherView = null;
private commandsBackground: CommandsBackground;
private contextMenusBackground: ContextMenusBackground;
private idleBackground: IdleBackground;
private notificationBackground: NotificationBackground;
private overlayBackground: OverlayBackgroundInterface;
private filelessImporterBackground: FilelessImporterBackground;
private runtimeBackground: RuntimeBackground;
private tabsBackground: TabsBackground;
private webRequestBackground: WebRequestBackground;
private syncTimeout: any;
private isSafari: boolean;
private nativeMessagingBackground: NativeMessagingBackground;
private popupViewCacheBackgroundService: PopupViewCacheBackgroundService;
constructor(public popupOnlyContext: boolean = false) {
// Services
const lockedCallback = async (userId?: string) => {
if (this.notificationsService != null) {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.notificationsService.updateConnection(false);
}
await this.refreshBadge();
await this.refreshMenu(true);
if (this.systemService != null) {
await this.systemService.clearPendingClipboard();
await this.systemService.startProcessReload(this.authService);
}
};
const logoutCallback = async (logoutReason: LogoutReason, userId?: UserId) =>
await this.logout(logoutReason, userId);
const refreshAccessTokenErrorCallback = () => {
// Send toast to popup
this.messagingService.send("showToast", {
type: "error",
title: this.i18nService.t("errorRefreshingAccessToken"),
message: this.i18nService.t("errorRefreshingAccessTokenDesc"),
});
};
const isDev = process.env.ENV === "development";
this.logService = new ConsoleLogService(isDev);
this.cryptoFunctionService = new WebCryptoFunctionService(self);
this.keyGenerationService = new KeyGenerationService(this.cryptoFunctionService);
this.storageService = new BrowserLocalStorageService();
this.intraprocessMessagingSubject = new Subject<Message<Record<string, unknown>>>();
this.messagingService = MessageSender.combine(
new SubjectMessageSender(this.intraprocessMessagingSubject),
new ChromeMessageSender(this.logService),
);
const messageListener = new MessageListener(
merge(
this.intraprocessMessagingSubject.asObservable(), // For messages from the same context
fromChromeRuntimeMessaging(), // For messages from other contexts
),
);
this.offscreenDocumentService = new DefaultOffscreenDocumentService(this.logService);
this.platformUtilsService = new BackgroundPlatformUtilsService(
this.messagingService,
(clipboardValue, clearMs) => this.clearClipboard(clipboardValue, clearMs),
async () => this.biometricUnlock(),
self,
this.offscreenDocumentService,
);
// Creates a session key for mv3 storage of large memory items
const sessionKey = new Lazy(async () => {
// Key already in session storage
const sessionStorage = new BrowserMemoryStorageService();
const existingKey = await sessionStorage.get<SymmetricCryptoKey>("session-key");
if (existingKey) {
if (sessionStorage.valuesRequireDeserialization) {
return SymmetricCryptoKey.fromJSON(existingKey);
}
return existingKey;
}
// New key
const { derivedKey } = await this.keyGenerationService.createKeyWithPurpose(
128,
"ephemeral",
"bitwarden-ephemeral",
);
await sessionStorage.save("session-key", derivedKey);
return derivedKey;
});
const mv3MemoryStorageCreator = () => {
if (this.popupOnlyContext) {
return new ForegroundMemoryStorageService();
}
// For local backed session storage, we expect that the encrypted data on disk will persist longer than the encryption key in memory
// and failures to decrypt because of that are completely expected. For this reason, we pass in `false` to the `EncryptServiceImplementation`
// so that MAC failures are not logged.
return new LocalBackedSessionStorageService(
sessionKey,
this.storageService,
new EncryptServiceImplementation(this.cryptoFunctionService, this.logService, false),
this.platformUtilsService,
this.logService,
);
};
this.secureStorageService = this.storageService; // secure storage is not supported in browsers, so we use local storage and warn users when it is used
if (BrowserApi.isManifestVersion(3)) {
// manifest v3 can reuse the same storage. They are split for v2 due to lacking a good sync mechanism, which isn't true for v3
this.memoryStorageForStateProviders = new BrowserMemoryStorageService(); // mv3 stores to storage.session
this.memoryStorageService = this.memoryStorageForStateProviders;
} else {
if (popupOnlyContext) {
this.memoryStorageForStateProviders = new ForegroundMemoryStorageService();
this.memoryStorageService = new ForegroundMemoryStorageService();
} else {
this.memoryStorageForStateProviders = new BackgroundMemoryStorageService(); // mv2 stores to memory
this.memoryStorageService = this.memoryStorageForStateProviders;
}
}
this.largeObjectMemoryStorageForStateProviders = BrowserApi.isManifestVersion(3)
? mv3MemoryStorageCreator() // mv3 stores to local-backed session storage
: this.memoryStorageForStateProviders; // mv2 stores to the same location
const localStorageStorageService = BrowserApi.isManifestVersion(3)
? new OffscreenStorageService(this.offscreenDocumentService)
: new WindowStorageService(self.localStorage);
const storageServiceProvider = new BrowserStorageServiceProvider(
this.storageService,
this.memoryStorageForStateProviders,
this.largeObjectMemoryStorageForStateProviders,
new PrimarySecondaryStorageService(this.storageService, localStorageStorageService),
);
this.globalStateProvider = new DefaultGlobalStateProvider(
storageServiceProvider,
this.logService,
);
const stateEventRegistrarService = new StateEventRegistrarService(
this.globalStateProvider,
storageServiceProvider,
);
this.stateEventRunnerService = new StateEventRunnerService(
this.globalStateProvider,
storageServiceProvider,
);
this.encryptService = BrowserApi.isManifestVersion(2)
? new MultithreadEncryptServiceImplementation(
this.cryptoFunctionService,
this.logService,
true,
)
: new EncryptServiceImplementation(this.cryptoFunctionService, this.logService, true);
this.singleUserStateProvider = new DefaultSingleUserStateProvider(
storageServiceProvider,
stateEventRegistrarService,
this.logService,
);
this.accountService = new AccountServiceImplementation(
this.messagingService,
this.logService,
this.globalStateProvider,
);
this.activeUserStateProvider = new DefaultActiveUserStateProvider(
this.accountService,
this.singleUserStateProvider,
);
this.derivedStateProvider = new InlineDerivedStateProvider();
this.stateProvider = new DefaultStateProvider(
this.activeUserStateProvider,
this.singleUserStateProvider,
this.globalStateProvider,
this.derivedStateProvider,
);
this.taskSchedulerService = this.popupOnlyContext
? new ForegroundTaskSchedulerService(this.logService, this.stateProvider)
: new BackgroundTaskSchedulerService(this.logService, this.stateProvider);
this.taskSchedulerService.registerTaskHandler(ScheduledTaskNames.scheduleNextSyncInterval, () =>
this.fullSync(),
);
this.environmentService = new BrowserEnvironmentService(
this.logService,
this.stateProvider,
this.accountService,
);
this.biometricStateService = new DefaultBiometricStateService(this.stateProvider);
this.userNotificationSettingsService = new UserNotificationSettingsService(this.stateProvider);
this.tokenService = new TokenService(
this.singleUserStateProvider,
this.globalStateProvider,
this.platformUtilsService.supportsSecureStorage(),
this.secureStorageService,
this.keyGenerationService,
this.encryptService,
this.logService,
logoutCallback,
);
this.popupViewCacheBackgroundService = new PopupViewCacheBackgroundService(
this.globalStateProvider,
);
const migrationRunner = new MigrationRunner(
this.storageService,
this.logService,
new MigrationBuilderService(),
ClientType.Browser,
);
this.stateService = new StateService(
this.storageService,
this.secureStorageService,
this.memoryStorageService,
this.logService,
new StateFactory(GlobalState, Account),
this.accountService,
this.environmentService,
this.tokenService,
migrationRunner,
);
this.themeStateService = new DefaultThemeStateService(this.globalStateProvider);
this.masterPasswordService = new MasterPasswordService(
this.stateProvider,
this.stateService,
this.keyGenerationService,
this.encryptService,
);
this.i18nService = new I18nService(BrowserApi.getUILanguage(), this.globalStateProvider);
this.kdfConfigService = new KdfConfigService(this.stateProvider);
this.pinService = new PinService(
this.accountService,
this.cryptoFunctionService,
this.encryptService,
this.kdfConfigService,
this.keyGenerationService,
this.logService,
this.masterPasswordService,
this.stateProvider,
this.stateService,
);
this.cryptoService = new BrowserCryptoService(
this.pinService,
this.masterPasswordService,
this.keyGenerationService,
this.cryptoFunctionService,
this.encryptService,
this.platformUtilsService,
this.logService,
this.stateService,
this.accountService,
this.stateProvider,
this.biometricStateService,
this.kdfConfigService,
);
this.appIdService = new AppIdService(this.globalStateProvider);
this.userDecryptionOptionsService = new UserDecryptionOptionsService(this.stateProvider);
this.organizationService = new OrganizationService(this.stateProvider);
this.policyService = new PolicyService(this.stateProvider, this.organizationService);
this.vaultTimeoutSettingsService = new VaultTimeoutSettingsService(
this.accountService,
this.pinService,
this.userDecryptionOptionsService,
this.cryptoService,
this.tokenService,
this.policyService,
this.biometricStateService,
this.stateProvider,
this.logService,
VaultTimeoutStringType.OnRestart, // default vault timeout
);
this.apiService = new ApiService(
this.tokenService,
this.platformUtilsService,
this.environmentService,
this.appIdService,
refreshAccessTokenErrorCallback,
this.logService,
(logoutReason: LogoutReason, userId?: UserId) => this.logout(logoutReason, userId),
this.vaultTimeoutSettingsService,
);
this.domainSettingsService = new DefaultDomainSettingsService(this.stateProvider);
this.fileUploadService = new FileUploadService(this.logService);
this.cipherFileUploadService = new CipherFileUploadService(
this.apiService,
this.fileUploadService,
);
this.searchService = new SearchService(this.logService, this.i18nService, this.stateProvider);
this.collectionService = new CollectionService(
this.cryptoService,
this.i18nService,
this.stateProvider,
);
this.autofillSettingsService = new AutofillSettingsService(
this.stateProvider,
this.policyService,
);
this.badgeSettingsService = new BadgeSettingsService(this.stateProvider);
this.policyApiService = new PolicyApiService(this.policyService, this.apiService);
this.keyConnectorService = new KeyConnectorService(
this.accountService,
this.masterPasswordService,
this.cryptoService,
this.apiService,
this.tokenService,
this.logService,
this.organizationService,
this.keyGenerationService,
logoutCallback,
this.stateProvider,
);
this.passwordStrengthService = new PasswordStrengthService();
this.passwordGenerationService = legacyPasswordGenerationServiceFactory(
this.encryptService,
this.cryptoService,
this.policyService,
this.accountService,
this.stateProvider,
);
this.userDecryptionOptionsService = new UserDecryptionOptionsService(this.stateProvider);
this.devicesApiService = new DevicesApiServiceImplementation(this.apiService);
this.deviceTrustService = new DeviceTrustService(
this.keyGenerationService,
this.cryptoFunctionService,
this.cryptoService,
this.encryptService,
this.appIdService,
this.devicesApiService,
this.i18nService,
this.platformUtilsService,
this.stateProvider,
this.secureStorageService,
this.userDecryptionOptionsService,
this.logService,
this.configService,
);
this.devicesService = new DevicesServiceImplementation(this.devicesApiService);
this.authRequestService = new AuthRequestService(
this.appIdService,
this.accountService,
this.masterPasswordService,
this.cryptoService,
this.apiService,
this.stateProvider,
);
this.authService = new AuthService(
this.accountService,
this.messagingService,
this.cryptoService,
this.apiService,
this.stateService,
this.tokenService,
);
this.billingAccountProfileStateService = new DefaultBillingAccountProfileStateService(
this.stateProvider,
);
this.ssoLoginService = new SsoLoginService(this.stateProvider);
this.userVerificationApiService = new UserVerificationApiService(this.apiService);
this.configApiService = new ConfigApiService(this.apiService, this.tokenService);
this.configService = new DefaultConfigService(
this.configApiService,
this.environmentService,
this.logService,
this.stateProvider,
this.authService,
);
this.cipherService = new CipherService(
this.cryptoService,
this.domainSettingsService,
this.apiService,
this.i18nService,
this.searchService,
this.stateService,
this.autofillSettingsService,
this.encryptService,
this.bulkEncryptService,
this.cipherFileUploadService,
this.configService,
this.stateProvider,
);
this.folderService = new FolderService(
this.cryptoService,
this.i18nService,
this.cipherService,
this.stateProvider,
);
this.folderApiService = new FolderApiService(this.folderService, this.apiService);
this.userVerificationService = new UserVerificationService(
this.cryptoService,
this.accountService,
this.masterPasswordService,
this.i18nService,
this.userVerificationApiService,
this.userDecryptionOptionsService,
this.pinService,
this.logService,
this.vaultTimeoutSettingsService,
this.platformUtilsService,
this.kdfConfigService,
);
this.vaultFilterService = new VaultFilterService(
this.organizationService,
this.folderService,
this.cipherService,
this.collectionService,
this.policyService,
this.stateProvider,
this.accountService,
);
this.vaultSettingsService = new VaultSettingsService(this.stateProvider);
this.vaultTimeoutService = new VaultTimeoutService(
this.accountService,
this.masterPasswordService,
this.cipherService,
this.folderService,
this.collectionService,
this.platformUtilsService,
this.messagingService,
this.searchService,
this.stateService,
this.authService,
this.vaultTimeoutSettingsService,
this.stateEventRunnerService,
this.taskSchedulerService,
this.logService,
lockedCallback,
logoutCallback,
);
this.containerService = new ContainerService(this.cryptoService, this.encryptService);
this.sendStateProvider = new SendStateProvider(this.stateProvider);
this.sendService = new SendService(
this.cryptoService,
this.i18nService,
this.keyGenerationService,
this.sendStateProvider,
this.encryptService,
);
this.sendApiService = new SendApiService(
this.apiService,
this.fileUploadService,
this.sendService,
);
this.avatarService = new AvatarService(this.apiService, this.stateProvider);
this.providerService = new ProviderService(this.stateProvider);
if (this.popupOnlyContext) {
this.syncService = new ForegroundSyncService(
this.stateService,
this.folderService,
this.folderApiService,
this.messagingService,
this.logService,
this.cipherService,
this.collectionService,
this.apiService,
this.accountService,
this.authService,
this.sendService,
this.sendApiService,
messageListener,
this.stateProvider,
);
} else {
this.syncService = new DefaultSyncService(
this.masterPasswordService,
this.accountService,
this.apiService,
this.domainSettingsService,
this.folderService,
this.cipherService,
this.cryptoService,
this.collectionService,
this.messagingService,
this.policyService,
this.sendService,
this.logService,
this.keyConnectorService,
this.stateService,
this.providerService,
this.folderApiService,
this.organizationService,
this.sendApiService,
this.userDecryptionOptionsService,
this.avatarService,
logoutCallback,
this.billingAccountProfileStateService,
this.tokenService,
this.authService,
this.stateProvider,
);
this.syncServiceListener = new SyncServiceListener(
this.syncService,
messageListener,
this.messagingService,
this.logService,
);
}
this.eventUploadService = new EventUploadService(
this.apiService,
this.stateProvider,
this.logService,
this.authService,
this.taskSchedulerService,
);
this.eventCollectionService = new EventCollectionService(
this.cipherService,
this.stateProvider,
this.organizationService,
this.eventUploadService,
this.authService,
this.accountService,
);
this.totpService = new TotpService(this.cryptoFunctionService, this.logService);
this.scriptInjectorService = new BrowserScriptInjectorService(
this.platformUtilsService,
this.logService,
);
this.autofillService = new AutofillService(
this.cipherService,
this.autofillSettingsService,
this.totpService,
this.eventCollectionService,
this.logService,
this.domainSettingsService,
this.userVerificationService,
this.billingAccountProfileStateService,
this.scriptInjectorService,
this.accountService,
this.authService,
this.configService,
messageListener,
);
this.auditService = new AuditService(this.cryptoFunctionService, this.apiService);
this.importApiService = new ImportApiService(this.apiService);
this.importService = new ImportService(
this.cipherService,
this.folderService,
this.importApiService,
this.i18nService,
this.collectionService,
this.cryptoService,
this.pinService,
this.accountService,
);
this.individualVaultExportService = new IndividualVaultExportService(
this.folderService,
this.cipherService,
this.pinService,
this.cryptoService,
this.cryptoFunctionService,
this.kdfConfigService,
);
this.organizationVaultExportService = new OrganizationVaultExportService(
this.cipherService,
this.apiService,
this.pinService,
this.cryptoService,
this.cryptoFunctionService,
this.collectionService,
this.kdfConfigService,
this.accountService,
);
this.exportService = new VaultExportService(
this.individualVaultExportService,
this.organizationVaultExportService,
);
this.notificationsService = new NotificationsService(
this.logService,
this.syncService,
this.appIdService,
this.apiService,
this.environmentService,
logoutCallback,
this.stateService,
this.authService,
this.messagingService,
this.taskSchedulerService,
);
this.fido2UserInterfaceService = new BrowserFido2UserInterfaceService(this.authService);
this.fido2AuthenticatorService = new Fido2AuthenticatorService(
this.cipherService,
this.fido2UserInterfaceService,
this.syncService,
this.accountService,
this.logService,
);
const fido2ActiveRequestManager = new Fido2ActiveRequestManager();
this.fido2ClientService = new Fido2ClientService(
this.fido2AuthenticatorService,
this.configService,
this.authService,
this.vaultSettingsService,
this.domainSettingsService,
this.taskSchedulerService,
fido2ActiveRequestManager,
this.logService,
);
const systemUtilsServiceReloadCallback = async () => {
const forceWindowReload =
this.platformUtilsService.isSafari() ||
this.platformUtilsService.isFirefox() ||
this.platformUtilsService.isOpera();
await this.taskSchedulerService.clearAllScheduledTasks();
BrowserApi.reloadExtension(forceWindowReload ? self : null);
};
this.systemService = new SystemService(
this.pinService,
this.messagingService,
this.platformUtilsService,
systemUtilsServiceReloadCallback,
this.autofillSettingsService,
this.vaultTimeoutSettingsService,
this.biometricStateService,
this.accountService,
this.taskSchedulerService,
);
// Other fields
this.isSafari = this.platformUtilsService.isSafari();
// Background
if (!this.popupOnlyContext) {
this.fido2Background = new Fido2Background(
this.logService,
this.fido2ClientService,
this.vaultSettingsService,
this.scriptInjectorService,
this.configService,
);
this.runtimeBackground = new RuntimeBackground(
this,
this.autofillService,
this.platformUtilsService as BrowserPlatformUtilsService,
this.notificationsService,
this.autofillSettingsService,
this.systemService,
this.environmentService,
this.messagingService,
this.logService,
this.configService,
this.fido2Background,
messageListener,
this.accountService,
);
this.nativeMessagingBackground = new NativeMessagingBackground(
this.cryptoService,
this.cryptoFunctionService,
this.runtimeBackground,
this.messagingService,
this.appIdService,
this.platformUtilsService,
this.logService,
this.authService,
this.biometricStateService,
this.accountService,
);
this.commandsBackground = new CommandsBackground(
this,
this.passwordGenerationService,
this.platformUtilsService,
this.vaultTimeoutService,
this.authService,
);
this.notificationBackground = new NotificationBackground(
this.autofillService,
this.cipherService,
this.authService,
this.policyService,
this.folderService,
this.userNotificationSettingsService,
this.domainSettingsService,
this.environmentService,
this.logService,
this.themeStateService,
this.configService,
this.accountService,
);
this.filelessImporterBackground = new FilelessImporterBackground(
this.configService,
this.authService,
this.policyService,
this.notificationBackground,
this.importService,
this.syncService,
this.scriptInjectorService,
);
this.autoSubmitLoginBackground = new AutoSubmitLoginBackground(
this.logService,
this.autofillService,
this.scriptInjectorService,
this.authService,
this.configService,
this.platformUtilsService,
this.policyService,
);
const contextMenuClickedHandler = new ContextMenuClickedHandler(
(options) => this.platformUtilsService.copyToClipboard(options.text),
async (_tab) => {
const options = (await this.passwordGenerationService.getOptions())?.[0] ?? {};
const password = await this.passwordGenerationService.generatePassword(options);
this.platformUtilsService.copyToClipboard(password);
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.passwordGenerationService.addHistory(password);
},
async (tab, cipher) => {
this.loginToAutoFill = cipher;
if (tab == null) {
return;
}
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
BrowserApi.tabSendMessage(tab, {
command: "collectPageDetails",
tab: tab,
sender: "contextMenu",
});
},
this.authService,
this.cipherService,
this.totpService,
this.eventCollectionService,
this.userVerificationService,
this.accountService,
);
this.contextMenusBackground = new ContextMenusBackground(contextMenuClickedHandler);
}
this.idleBackground = new IdleBackground(
this.vaultTimeoutService,
this.notificationsService,
this.accountService,
this.vaultTimeoutSettingsService,
);
this.usernameGenerationService = legacyUsernameGenerationServiceFactory(
this.apiService,
this.i18nService,
this.cryptoService,
this.encryptService,
this.policyService,
this.accountService,
this.stateProvider,
);
if (!this.popupOnlyContext) {
this.mainContextMenuHandler = new MainContextMenuHandler(
this.stateService,
this.autofillSettingsService,
this.i18nService,
this.logService,
this.billingAccountProfileStateService,
);
this.cipherContextMenuHandler = new CipherContextMenuHandler(
this.mainContextMenuHandler,
this.authService,
this.cipherService,
);
if (chrome.webRequest != null && chrome.webRequest.onAuthRequired != null) {
this.webRequestBackground = new WebRequestBackground(
this.platformUtilsService,
this.cipherService,
this.authService,
chrome.webRequest,
);
}
}
this.userAutoUnlockKeyService = new UserAutoUnlockKeyService(this.cryptoService);
}
async bootstrap() {
this.containerService.attachToGlobal(self);
// Only the "true" background should run migrations
await this.stateService.init({ runMigrations: !this.popupOnlyContext });
// This is here instead of in in the InitService b/c we don't plan for
// side effects to run in the Browser InitService.
const accounts = await firstValueFrom(this.accountService.accounts$);
const setUserKeyInMemoryPromises = [];
for (const userId of Object.keys(accounts) as UserId[]) {
// For each acct, we must await the process of setting the user key in memory
// if the auto user key is set to avoid race conditions of any code trying to access
// the user key from mem.
setUserKeyInMemoryPromises.push(
this.userAutoUnlockKeyService.setUserKeyInMemoryIfAutoUserKeySet(userId),
);
}
await Promise.all(setUserKeyInMemoryPromises);
await (this.i18nService as I18nService).init();
(this.eventUploadService as EventUploadService).init(true);
this.popupViewCacheBackgroundService.startObservingTabChanges();
if (this.popupOnlyContext) {
return;
}
await this.vaultTimeoutService.init(true);
this.fido2Background.init();
await this.runtimeBackground.init();
await this.notificationBackground.init();
this.filelessImporterBackground.init();
await this.commandsBackground.init();
this.contextMenusBackground?.init();
await this.idleBackground.init();
this.webRequestBackground?.startListening();
this.syncServiceListener?.listener$().subscribe();
await this.autoSubmitLoginBackground.init();
if (
BrowserApi.isManifestVersion(2) &&
(await this.configService.getFeatureFlag(FeatureFlag.PM4154_BulkEncryptionService))
) {
await this.bulkEncryptService.setFeatureFlagEncryptService(
new BulkEncryptServiceImplementation(this.cryptoFunctionService, this.logService),
);
}
await this.initOverlayAndTabsBackground();
return new Promise<void>((resolve) => {
setTimeout(async () => {
await this.refreshBadge();
await this.fullSync(true);
this.taskSchedulerService.setInterval(
ScheduledTaskNames.scheduleNextSyncInterval,
5 * 60 * 1000, // check every 5 minutes
);
setTimeout(() => this.notificationsService.init(), 2500);
await this.taskSchedulerService.verifyAlarmsState();
resolve();
}, 500);
});
}
async refreshBadge() {
await new UpdateBadge(self, this).run();
}
async refreshMenu(forLocked = false) {
if (!chrome.windows || !chrome.contextMenus) {
return;
}
await MainContextMenuHandler.removeAll();
if (forLocked) {
await this.mainContextMenuHandler?.noAccess();
this.onUpdatedRan = this.onReplacedRan = false;
return;
}
await this.mainContextMenuHandler?.init();
const tab = await BrowserApi.getTabFromCurrentWindow();
if (tab) {
await this.cipherContextMenuHandler?.update(tab.url);
this.onUpdatedRan = this.onReplacedRan = false;
}
}
async updateOverlayCiphers() {
// overlayBackground null in popup only contexts
if (this.overlayBackground) {
await this.overlayBackground.updateOverlayCiphers();
}
}
/**
* Switch accounts to indicated userId -- null is no active user
*/
async switchAccount(userId: UserId) {
let nextAccountStatus: AuthenticationStatus;
try {
// HACK to ensure account is switched before proceeding
const switchPromise = firstValueFrom(
this.accountService.activeAccount$.pipe(
filter((account) => (account?.id ?? null) === (userId ?? null)),
timeout({
first: 1_000,
with: () => {
throw new Error(
"The account switch process did not complete in a reasonable amount of time.",
);
},
}),
),
);
await this.popupViewCacheBackgroundService.clearState();
await this.accountService.switchAccount(userId);
await switchPromise;
// Clear sequentialized caches
clearCaches();
if (userId == null) {
await this.refreshBadge();
await this.refreshMenu();
await this.updateOverlayCiphers();
this.messagingService.send("goHome");
return;
}
nextAccountStatus = await this.authService.getAuthStatus(userId);
const forcePasswordReset =
(await firstValueFrom(this.masterPasswordService.forceSetPasswordReason$(userId))) !=
ForceSetPasswordReason.None;
await this.systemService.clearPendingClipboard();
await this.notificationsService.updateConnection(false);
if (nextAccountStatus === AuthenticationStatus.LoggedOut) {
this.messagingService.send("goHome");
} else if (nextAccountStatus === AuthenticationStatus.Locked) {
this.messagingService.send("locked", { userId: userId });
} else if (forcePasswordReset) {
this.messagingService.send("update-temp-password", { userId: userId });
} else {
this.messagingService.send("unlocked", { userId: userId });
await this.refreshBadge();
await this.refreshMenu();
await this.updateOverlayCiphers();
await this.syncService.fullSync(false);
}
} finally {
this.messagingService.send("switchAccountFinish", {
userId: userId,
status: nextAccountStatus,
});
}
}
async logout(logoutReason: LogoutReason, userId?: UserId) {
const activeUserId = await firstValueFrom(
this.accountService.activeAccount$.pipe(
map((a) => a?.id),
timeout({
first: 2000,
with: () => {
throw new Error("No active account found to logout");
},
}),
),
);
const userBeingLoggedOut = userId ?? activeUserId;
await this.eventUploadService.uploadEvents(userBeingLoggedOut);
const newActiveUser =
userBeingLoggedOut === activeUserId
? await firstValueFrom(this.accountService.nextUpAccount$.pipe(map((a) => a?.id)))
: null;
await this.switchAccount(newActiveUser);
// HACK: We shouldn't wait for the authentication status to change but instead subscribe to the
// authentication status to do various actions.
const logoutPromise = firstValueFrom(
this.authService.authStatusFor$(userBeingLoggedOut).pipe(
filter((authenticationStatus) => authenticationStatus === AuthenticationStatus.LoggedOut),
timeout({
first: 5_000,
with: () => {
throw new Error("The logout process did not complete in a reasonable amount of time.");
},
}),
),
);
await Promise.all([
this.cryptoService.clearKeys(userBeingLoggedOut),
this.cipherService.clear(userBeingLoggedOut),
this.folderService.clear(userBeingLoggedOut),
this.collectionService.clear(userBeingLoggedOut),
this.vaultTimeoutSettingsService.clear(userBeingLoggedOut),
this.vaultFilterService.clear(),
this.biometricStateService.logout(userBeingLoggedOut),
this.popupViewCacheBackgroundService.clearState(),
/* We intentionally do not clear:
* - autofillSettingsService
* - badgeSettingsService
* - userNotificationSettingsService
*/
]);
//Needs to be checked before state is cleaned
const needStorageReseed = await this.needsStorageReseed(userBeingLoggedOut);
await this.stateService.clean({ userId: userBeingLoggedOut });
await this.accountService.clean(userBeingLoggedOut);
await this.stateEventRunnerService.handleEvent("logout", userBeingLoggedOut);
// HACK: Wait for the user logging outs authentication status to transition to LoggedOut
await logoutPromise;
this.messagingService.send("doneLoggingOut", {
logoutReason: logoutReason,
userId: userBeingLoggedOut,
});
if (needStorageReseed) {
await this.reseedStorage();
}
if (BrowserApi.isManifestVersion(3)) {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
BrowserApi.sendMessage("updateBadge");
}
await this.refreshBadge();
await this.mainContextMenuHandler?.noAccess();
await this.notificationsService.updateConnection(false);
await this.systemService.clearPendingClipboard();
await this.systemService.startProcessReload(this.authService);
}
private async needsStorageReseed(userId: UserId): Promise<boolean> {
const currentVaultTimeout = await firstValueFrom(
this.vaultTimeoutSettingsService.getVaultTimeoutByUserId$(userId),
);
return currentVaultTimeout == VaultTimeoutStringType.Never ? false : true;
}
async collectPageDetailsForContentScript(tab: any, sender: string, frameId: number = null) {
if (tab == null || !tab.id) {
return;
}
const options: any = {};
if (frameId != null) {
options.frameId = frameId;
}
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
BrowserApi.tabSendMessage(
tab,
{
command: "collectPageDetails",
tab: tab,
sender: sender,
},
options,
);
}
async openPopup() {
// Chrome APIs cannot open popup
// TODO: Do we need to open this popup?
if (!this.isSafari) {
return;
}
await SafariApp.sendMessageToApp("showPopover", null, true);
}
async reseedStorage() {
if (
!this.platformUtilsService.isChrome() &&
!this.platformUtilsService.isVivaldi() &&
!this.platformUtilsService.isOpera()
) {
return;
}
await this.storageService.reseed();
}
async clearClipboard(clipboardValue: string, clearMs: number) {
if (this.systemService != null) {
await this.systemService.clearClipboard(clipboardValue, clearMs);
}
}
async biometricUnlock(): Promise<boolean> {
if (this.nativeMessagingBackground == null) {
return false;
}
const responsePromise = this.nativeMessagingBackground.getResponse();
await this.nativeMessagingBackground.send({ command: "biometricUnlock" });
const response = await responsePromise;
return response.response === "unlocked";
}
private async fullSync(override = false) {
const syncInternal = 6 * 60 * 60 * 1000; // 6 hours
const lastSync = await this.syncService.getLastSync();
let lastSyncAgo = syncInternal + 1;
if (lastSync != null) {
lastSyncAgo = new Date().getTime() - lastSync.getTime();
}
if (override || lastSyncAgo >= syncInternal) {
await this.syncService.fullSync(override);
}
}
/**
* Temporary solution to handle initialization of the overlay background behind a feature flag.
* Will be reverted to instantiation within the constructor once the feature flag is removed.
*/
async initOverlayAndTabsBackground() {
if (
this.popupOnlyContext ||
this.overlayBackground ||
this.tabsBackground ||
(await firstValueFrom(this.authService.activeAccountStatus$)) ===
AuthenticationStatus.LoggedOut
) {
return;
}
const inlineMenuPositioningImprovementsEnabled = await this.configService.getFeatureFlag(
FeatureFlag.InlineMenuPositioningImprovements,
);
if (!inlineMenuPositioningImprovementsEnabled) {
this.overlayBackground = new LegacyOverlayBackground(
this.cipherService,
this.autofillService,
this.authService,
this.environmentService,
this.domainSettingsService,
this.autofillSettingsService,
this.i18nService,
this.platformUtilsService,
this.themeStateService,
);
} else {
this.overlayBackground = new OverlayBackground(
this.logService,
this.cipherService,
this.autofillService,
this.authService,
this.environmentService,
this.domainSettingsService,
this.autofillSettingsService,
this.i18nService,
this.platformUtilsService,
this.fido2ClientService,
this.themeStateService,
);
}
this.tabsBackground = new TabsBackground(
this,
this.notificationBackground,
this.overlayBackground,
);
await this.overlayBackground.init();
await this.tabsBackground.init();
}
}
``` | /content/code_sandbox/apps/browser/src/background/main.background.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 13,516 |
```xml
jest.mock('toolkit/extension/features/feature');
import { POSStyleCurrencyEntryMode } from '.';
import { createYnabGlobalStructureMock } from './__mocks__/currency-formatter';
import { POSStyleParser } from './pos-style-parser';
export interface YnabGlobalHasWebinstance {
YNABSharedLibWebInstance: YNABSharedLibWebInstance;
}
declare module globalThis {
let ynab: YnabGlobalHasWebinstance;
}
function setYnabGlobal(value: YnabGlobalHasWebinstance) {
Object.defineProperty(globalThis, 'ynab', {
value: value,
configurable: true,
writable: true,
});
}
describe('POSStyleParser', () => {
let extension: POSStyleParser;
const globalYnabBackup = globalThis.ynab;
beforeEach(() => {
setYnabGlobal(createYnabGlobalStructureMock());
const { currencyFormatter } =
ynab.YNABSharedLibWebInstance.firstInstanceCreated.formattingManager;
extension = new POSStyleParser(currencyFormatter);
});
afterAll(() => {
setYnabGlobal(globalYnabBackup);
});
describe('the mock', () => {
// todo remove when tests are finished
it('should provide the currency manager using the global ynab structure', () => {
expect(extension.formatter).toBeDefined();
expect(extension.formatter.getCurrency).toBeDefined();
const currency = extension.formatter.getCurrency();
expect(currency.decimal_separator).toBe(',');
});
it('should provide a possibility to configure e.g. decimal digits', () => {
const currency = extension.formatter.getCurrency();
expect(currency.decimal_digits).toBe(2);
extension.formatter._currencyObj!.decimal_digits = 3;
expect(currency.decimal_digits).toBe(3);
});
it('should always start with the same value for decimal digits', () => {
const currency = extension.formatter.getCurrency();
expect(currency.decimal_digits).toBe(2);
});
});
describe('determineValue()', () => {
it('should return decimal values with the right separator as is', () => {
const inputs = ['0,01', '0,999', '-2,0', '123456789123456789,5'];
expect(extension.determineValue('-2,0')).toBe('-2,0');
inputs.forEach((input) => {
expect(extension.determineValue(input)).toBe(input);
});
});
it('should ignore the wrong separator', () => {
expect(extension.determineValue('0.01')).toBe('0.01');
expect(extension.determineValue('12.3.4')).toBe('12.3.4');
});
it('should interpret numbers in POS style, e.g. 500 -> 5,00', () => {
expect(extension.determineValue('1')).toBe('0,01');
expect(extension.determineValue('99')).toBe('0,99');
expect(extension.determineValue('100')).toBe('1,00');
expect(extension.determineValue('1234')).toBe('12,34');
});
it('should allow the postfix - to be used for full monetary units', () => {
expect(extension.determineValue('1-')).toBe('1');
expect(extension.determineValue('1234-')).toBe('1234');
});
it('should not change numbers with decimal separator and postfix', () => {
expect(extension.determineValue('1,0-')).toBe('1,0-');
expect(extension.determineValue('1,1-')).toBe('1,1-');
});
it('should support math operations', () => {
expect(extension.determineValue('50*5')).toBe('2,50');
expect(extension.determineValue('11*9')).toBe('0,99');
expect(extension.determineValue('11*10')).toBe('1,10');
expect(extension.determineValue('5/3*100')).toBe('1,67');
expect(extension.determineValue('5%3*100')).toBe('2,00');
});
it('should round to a different number of digits, if specified', () => {
extension.formatter._currencyObj!.decimal_digits = 3;
expect(extension.determineValue('1')).toBe('0,001');
expect(extension.determineValue('999')).toBe('0,999');
expect(extension.determineValue('1000')).toBe('1,000');
expect(extension.determineValue('5/3*100')).toBe('0,167');
});
});
});
``` | /content/code_sandbox/src/extension/features/general/pos-style-currency-entry-mode/pos-style-parser.test.ts | xml | 2016-01-03T05:38:10 | 2024-08-13T16:08:09 | toolkit-for-ynab | toolkit-for-ynab/toolkit-for-ynab | 1,418 | 982 |
```xml
import { PrismaClient } from '@prisma/client';
import { JobTitleLabels } from '../src/components/shared/JobTitles';
const prisma = new PrismaClient();
type QuestionCreateData = Parameters<
typeof prisma.questionsQuestion.create
>[0]['data'];
function selectRandomRole() {
const roles = Object.keys(JobTitleLabels);
const randomIndex = Math.floor(Math.random() * roles.length);
return roles[randomIndex];
}
function generateRandomDate() {
// Return a date between 2020 and 2022.
const start = new Date(2020, 0, 1);
const end = new Date(2022, 0, 1);
return new Date(
start.getTime() + Math.random() * (end.getTime() - start.getTime()),
);
}
function generateRandomCodingAnswer() {
return CODING_ANSWER_CONTENT[
Math.floor(Math.random() * CODING_ANSWER_CONTENT.length)
];
}
function generateRandomBehavioralAnswer() {
return BEHAVIORAL_ANSWER_CONTENT[
Math.floor(Math.random() * BEHAVIORAL_ANSWER_CONTENT.length)
];
}
const CODING_QUESTION_CONTENT = [
'Given a string, find the length of the longest substring without repeating characters.',
'Given an array of integers, return indices of the two numbers such that they add up to a specific target.',
'Given a contiguous sequence of numbers in which each number repeats thrice, there is exactly one missing number. Find the missing number.',
'Find the contiguous subarray within an array (containing at least one number) which has the largest product.',
'Find a contiguous subarray which has the largest sum.',
];
const BEHAVIORAL_QUESTION_CONTENT = [
'Tell me about a time you had to work with a difficult person.',
'Rate your communication skills on a scale of 1 to 10.',
'Are you a team player?',
'What is your greatest weakness?',
'What is your greatest strength?',
'What is your biggest accomplishment?',
'What is your biggest failure?',
'Be honest, how would your friends describe you?',
'How do you handle stress?',
'Lets say you have a deadline to meet. How do you prioritize your work?',
];
const CODING_ANSWER_CONTENT = [
'This question is easy. Just use a hash map.',
'This question is hard. I have no idea how to solve it.',
'This question is medium. I can solve it in 30 minutes.',
'Can be done with a simple for loop.',
'Simple recursion can solve this.',
'Please explain the question again.',
'Question is not clear.',
'Brute force solution is the best.',
];
const BEHAVIORAL_ANSWER_CONTENT = [
'This is a very common question. I have a lot of experience with this.',
"I don't think this is a good question to ask. However, I can answer it.",
'Most companies ask this question. I think you should ask something else.',
'I try to take a step back and assess the situation. I figure out what is the most important thing to do and what can wait. I also try to delegate or ask for help when needed.',
'I try to have a discussion with my manager or the person who I feel is not valuing my work. I try to explain how I feel and what I would like to see change.',
'I try to have a discussion with the coworker. I try to understand their perspective and see if there is a way to resolve the issue.',
];
const CODING_QUESTIONS: Array<QuestionCreateData> = CODING_QUESTION_CONTENT.map(
(content) => ({
content,
questionType: 'CODING',
userId: null,
encounters: {
create: {
role: selectRandomRole(),
seenAt: generateRandomDate(),
},
},
}),
);
const BEHAVIORAL_QUESTIONS: Array<QuestionCreateData> =
BEHAVIORAL_QUESTION_CONTENT.map((content) => ({
content,
questionType: 'BEHAVIORAL',
userId: null,
encounters: {
create: {
role: selectRandomRole(),
seenAt: generateRandomDate(),
},
},
}));
const QUESTIONS: Array<QuestionCreateData> = [
...CODING_QUESTIONS,
...BEHAVIORAL_QUESTIONS,
];
async function main() {
console.log('Performing preliminary checks...');
const firstCompany = await prisma.company.findFirst();
if (!firstCompany) {
throw new Error(
'No company found. Please seed db with some companies first.',
);
}
const firstCity = await prisma.city.findFirst({
include: {
state: true,
},
});
if (!firstCity) {
throw new Error('No city found. Please seed db with some cities first.');
}
// Generate random answers to the questions
const users = await prisma.user.findMany();
if (users.length === 0) {
throw new Error('No users found. Please seed db with some users first.');
}
console.log('Seeding started...');
console.log('Creating coding and behavioral questions...');
await Promise.all([
QUESTIONS.map(async (question) => {
await prisma.questionsQuestion.create({
data: {
...question,
encounters: {
create: {
...question.encounters!.create,
companyId: firstCompany.id,
stateId: firstCity.stateId,
cityId: firstCity.id,
countryId: firstCity.state.countryId,
} as any,
},
},
});
}),
]);
console.log('Creating answers to coding questions...');
const codingQuestions = await prisma.questionsQuestion.findMany({
where: {
questionType: 'CODING',
},
});
await Promise.all(
codingQuestions.map(async (question) => {
const answers = Array.from(
{ length: Math.floor(Math.random() * 5) },
() => ({
content: generateRandomCodingAnswer(),
userId: users[Math.floor(Math.random() * users.length)].id,
questionId: question.id,
}),
);
await prisma.questionsAnswer.createMany({
data: answers,
});
}),
);
console.log('Creating answers to behavioral questions...');
const behavioralQuestions = await prisma.questionsQuestion.findMany({
where: {
questionType: 'BEHAVIORAL',
},
});
await Promise.all(
behavioralQuestions.map(async (question) => {
const answers = Array.from(
{ length: Math.floor(Math.random() * 5) },
() => ({
content: generateRandomBehavioralAnswer(),
userId: users[Math.floor(Math.random() * users.length)].id,
questionId: question.id,
}),
);
await prisma.questionsAnswer.createMany({
data: answers,
});
}),
);
console.log('Seeding completed.');
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
``` | /content/code_sandbox/apps/portal/prisma/seed-questions.ts | xml | 2016-07-05T05:00:48 | 2024-08-16T19:01:19 | tech-interview-handbook | yangshun/tech-interview-handbook | 115,302 | 1,527 |
```xml
export class AttachmentRequest {
fileName: string;
key: string;
fileSize: number;
adminRequest: boolean;
}
``` | /content/code_sandbox/libs/common/src/vault/models/request/attachment.request.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 28 |
```xml
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { authURL } from '~/data/api';
import { IAuthMethodList } from '~/types/Auth';
export const authProvidersApi = createApi({
reducerPath: 'providers',
baseQuery: fetchBaseQuery({
baseUrl: authURL
}),
tagTypes: ['Provider'],
endpoints: (builder) => ({
// get list of tokens
listAuthProviders: builder.query<IAuthMethodList, void>({
query: () => {
return { url: '/method' };
},
providesTags: (_result, _error, _args) => [{ type: 'Provider' }]
})
})
});
export const { useListAuthProvidersQuery } = authProvidersApi;
``` | /content/code_sandbox/ui/src/app/auth/authApi.ts | xml | 2016-11-05T00:09:07 | 2024-08-16T13:44:10 | flipt | flipt-io/flipt | 3,489 | 166 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<DefaultItemExcludes>$(DefaultItemExcludes);**\node_modules\**;node_modules\**</DefaultItemExcludes>
<TargetFramework>net6.0</TargetFramework>
<AssemblyName>Unosquare.PassCore.Web</AssemblyName>
<PackageId>Unosquare.PassCore.Web</PackageId>
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
<IsPackable>false</IsPackable>
<TypeScriptToolsVersion>4.2</TypeScriptToolsVersion>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<RootNamespace>Unosquare.PassCore.Web</RootNamespace>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<Nullable>enable</Nullable>
<NullableReferenceTypes>true</NullableReferenceTypes>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="4.6.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SimpleBase" Version="3.0.2" />
<PackageReference Include="zxcvbn-core" Version="7.0.92" />
<PackageReference Include="Unosquare.Swan" Version="3.0.0" />
</ItemGroup>
<ItemGroup>
<Content Remove="ClientApp\**" />
<Content Include="ClientApp\package.json" />
<Content Include="ClientApp\tsconfig.json" />
<Content Update="wwwroot/**/*.map" CopyToPublishDirectory="Never" />
<None Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PwnedPasswordsSearch\PwnedPasswordsSearch.csproj" />
<ProjectReference Include="..\Unosquare.PassCore.Common\Unosquare.PassCore.Common.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(PASSCORE_PROVIDER)' == ''">
<!-- Default Password Provider - Win32 -->
<ProjectReference Include="..\Unosquare.PassCore.PasswordProvider\Unosquare.PassCore.PasswordProvider.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(PASSCORE_PROVIDER)' == 'LDAP'">
<!-- Pure LDAP provider -->
<ProjectReference Include="..\Zyborg.PassCore.PasswordProvider.LDAP\Zyborg.PassCore.PasswordProvider.LDAP.csproj" />
</ItemGroup>
<PropertyGroup Condition="'$(PASSCORE_PROVIDER)' == 'LDAP'">
<DefineConstants>PASSCORE_LDAP_PROVIDER</DefineConstants>
</PropertyGroup>
<Target Name="NpmInstall" BeforeTargets="Build" Condition="!Exists('.\ClientApp\node_modules')">
<Exec Command="node --version" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Exec Command="npm install --force" WorkingDirectory=".\ClientApp" />
<Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from path_to_url and then restart your command prompt or IDE." />
<Message Importance="high" Text="Performing first-run npm install..." />
</Target>
<Target Name="Parcel" DependsOnTargets="NpmInstall" BeforeTargets="Build">
<Message Importance="high" Text="Performing run Parcel build..." />
<Exec Command="npm run build" WorkingDirectory=".\ClientApp" />
</Target>
</Project>
``` | /content/code_sandbox/src/Unosquare.PassCore.Web/Unosquare.PassCore.Web.csproj | xml | 2016-01-07T21:36:00 | 2024-08-16T09:03:42 | passcore | unosquare/passcore | 1,030 | 881 |
```xml
/**
* @license
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {MDCFoundation} from '@material/base/foundation';
import {MDCRippleAdapter} from './adapter';
import {cssClasses, numbers, strings} from './constants';
import {MDCRipplePoint} from './types';
import {getNormalizedEventCoords} from './util';
interface ActivationStateType {
isActivated?: boolean;
hasDeactivationUXRun?: boolean;
wasActivatedByPointer?: boolean;
wasElementMadeActive?: boolean;
activationEvent?: Event;
isProgrammatic?: boolean;
}
interface FgTranslationCoordinates {
startPoint: MDCRipplePoint;
endPoint: MDCRipplePoint;
}
interface Coordinates {
left: number;
top: number;
}
interface EventHandlerNonNull {
(event: Event): any;
}
type ActivationEventType = 'touchstart'|'pointerdown'|'mousedown'|'keydown';
type DeactivationEventType = 'touchend'|'pointerup'|'mouseup'|'contextmenu';
// Activation events registered on the root element of each instance for
// activation
const ACTIVATION_EVENT_TYPES: ActivationEventType[] = [
'touchstart',
'pointerdown',
'mousedown',
'keydown',
];
// Deactivation events registered on documentElement when a pointer-related down
// event occurs
const POINTER_DEACTIVATION_EVENT_TYPES: DeactivationEventType[] = [
'touchend',
'pointerup',
'mouseup',
'contextmenu',
];
// simultaneous nested activations
let activatedTargets: Array<EventTarget|null> = [];
/** MDC Ripple Foundation */
export class MDCRippleFoundation extends MDCFoundation<MDCRippleAdapter> {
static override get cssClasses() {
return cssClasses;
}
static override get strings() {
return strings;
}
static override get numbers() {
return numbers;
}
static override get defaultAdapter(): MDCRippleAdapter {
return {
addClass: () => undefined,
browserSupportsCssVars: () => true,
computeBoundingRect: () =>
({top: 0, right: 0, bottom: 0, left: 0, width: 0, height: 0} as any),
containsEventTarget: () => true,
deregisterDocumentInteractionHandler: () => undefined,
deregisterInteractionHandler: () => undefined,
deregisterResizeHandler: () => undefined,
getWindowPageOffset: () => ({x: 0, y: 0}),
isSurfaceActive: () => true,
isSurfaceDisabled: () => true,
isUnbounded: () => true,
registerDocumentInteractionHandler: () => undefined,
registerInteractionHandler: () => undefined,
registerResizeHandler: () => undefined,
removeClass: () => undefined,
updateCssVariable: () => undefined,
};
}
private activationAnimationHasEnded = false;
private activationState: ActivationStateType;
private activationTimer = 0;
private fgDeactivationRemovalTimer = 0;
private fgScale = '0';
private frame = {width: 0, height: 0};
private initialSize = 0;
private layoutFrame = 0;
private maxRadius = 0;
private unboundedCoords: Coordinates = {left: 0, top: 0};
private readonly activationTimerCallback: () => void;
private readonly activateHandler: EventHandlerNonNull;
private readonly deactivateHandler: EventHandlerNonNull;
private readonly focusHandler: EventHandlerNonNull;
private readonly blurHandler: EventHandlerNonNull;
private readonly resizeHandler: EventHandlerNonNull;
private previousActivationEvent?: Event;
constructor(adapter?: Partial<MDCRippleAdapter>) {
super({...MDCRippleFoundation.defaultAdapter, ...adapter});
this.activationState = this.defaultActivationState();
this.activationTimerCallback = () => {
this.activationAnimationHasEnded = true;
this.runDeactivationUXLogicIfReady();
};
this.activateHandler = (e) => {
this.activateImpl(e);
};
this.deactivateHandler = () => {
this.deactivateImpl();
};
this.focusHandler = () => {
this.handleFocus();
};
this.blurHandler = () => {
this.handleBlur();
};
this.resizeHandler = () => {
this.layout();
};
}
override init() {
const supportsPressRipple = this.supportsPressRipple();
this.registerRootHandlers(supportsPressRipple);
if (supportsPressRipple) {
const {ROOT, UNBOUNDED} = MDCRippleFoundation.cssClasses;
requestAnimationFrame(() => {
this.adapter.addClass(ROOT);
if (this.adapter.isUnbounded()) {
this.adapter.addClass(UNBOUNDED);
// Unbounded ripples need layout logic applied immediately to set
// coordinates for both shade and ripple
this.layoutInternal();
}
});
}
}
override destroy() {
if (this.supportsPressRipple()) {
if (this.activationTimer) {
clearTimeout(this.activationTimer);
this.activationTimer = 0;
this.adapter.removeClass(MDCRippleFoundation.cssClasses.FG_ACTIVATION);
}
if (this.fgDeactivationRemovalTimer) {
clearTimeout(this.fgDeactivationRemovalTimer);
this.fgDeactivationRemovalTimer = 0;
this.adapter.removeClass(
MDCRippleFoundation.cssClasses.FG_DEACTIVATION);
}
const {ROOT, UNBOUNDED} = MDCRippleFoundation.cssClasses;
requestAnimationFrame(() => {
this.adapter.removeClass(ROOT);
this.adapter.removeClass(UNBOUNDED);
this.removeCssVars();
});
}
this.deregisterRootHandlers();
this.deregisterDeactivationHandlers();
}
/**
* @param event Optional event containing position information.
*/
activate(event?: Event): void {
this.activateImpl(event);
}
deactivate(): void {
this.deactivateImpl();
}
layout(): void {
if (this.layoutFrame) {
cancelAnimationFrame(this.layoutFrame);
}
this.layoutFrame = requestAnimationFrame(() => {
this.layoutInternal();
this.layoutFrame = 0;
});
}
setUnbounded(unbounded: boolean): void {
const {UNBOUNDED} = MDCRippleFoundation.cssClasses;
if (unbounded) {
this.adapter.addClass(UNBOUNDED);
} else {
this.adapter.removeClass(UNBOUNDED);
}
}
handleFocus(): void {
requestAnimationFrame(() => {
this.adapter.addClass(MDCRippleFoundation.cssClasses.BG_FOCUSED);
});
}
handleBlur(): void {
requestAnimationFrame(() => {
this.adapter.removeClass(MDCRippleFoundation.cssClasses.BG_FOCUSED);
});
}
/**
* We compute this property so that we are not querying information about the
* client until the point in time where the foundation requests it. This
* prevents scenarios where client-side feature-detection may happen too
* early, such as when components are rendered on the server and then
* initialized at mount time on the client.
*/
private supportsPressRipple(): boolean {
return this.adapter.browserSupportsCssVars();
}
private defaultActivationState(): ActivationStateType {
return {
activationEvent: undefined,
hasDeactivationUXRun: false,
isActivated: false,
isProgrammatic: false,
wasActivatedByPointer: false,
wasElementMadeActive: false,
};
}
/**
* supportsPressRipple Passed from init to save a redundant function call
*/
private registerRootHandlers(supportsPressRipple: boolean) {
if (supportsPressRipple) {
for (const eventType of ACTIVATION_EVENT_TYPES) {
this.adapter.registerInteractionHandler(eventType, this.activateHandler);
}
if (this.adapter.isUnbounded()) {
this.adapter.registerResizeHandler(this.resizeHandler);
}
}
this.adapter.registerInteractionHandler('focus', this.focusHandler);
this.adapter.registerInteractionHandler('blur', this.blurHandler);
}
private registerDeactivationHandlers(event: Event) {
if (event.type === 'keydown') {
this.adapter.registerInteractionHandler('keyup', this.deactivateHandler);
} else {
for (const eventType of POINTER_DEACTIVATION_EVENT_TYPES) {
this.adapter.registerDocumentInteractionHandler(
eventType, this.deactivateHandler);
}
}
}
private deregisterRootHandlers() {
for (const eventType of ACTIVATION_EVENT_TYPES) {
this.adapter.deregisterInteractionHandler(eventType, this.activateHandler);
}
this.adapter.deregisterInteractionHandler('focus', this.focusHandler);
this.adapter.deregisterInteractionHandler('blur', this.blurHandler);
if (this.adapter.isUnbounded()) {
this.adapter.deregisterResizeHandler(this.resizeHandler);
}
}
private deregisterDeactivationHandlers() {
this.adapter.deregisterInteractionHandler('keyup', this.deactivateHandler);
for (const eventType of POINTER_DEACTIVATION_EVENT_TYPES) {
this.adapter.deregisterDocumentInteractionHandler(
eventType, this.deactivateHandler);
}
}
private removeCssVars() {
const rippleStrings = MDCRippleFoundation.strings;
const keys =
Object.keys(rippleStrings) as Array<keyof typeof rippleStrings>;
keys.forEach((key) => {
if (key.indexOf('VAR_') === 0) {
this.adapter.updateCssVariable(rippleStrings[key], null);
}
});
}
private activateImpl(event?: Event) {
if (this.adapter.isSurfaceDisabled()) {
return;
}
const activationState = this.activationState;
if (activationState.isActivated) {
return;
}
// Avoid reacting to follow-on events fired by touch device after an
// already-processed user interaction
const previousActivationEvent = this.previousActivationEvent;
const isSameInteraction = previousActivationEvent && event !== undefined &&
previousActivationEvent.type !== event.type;
if (isSameInteraction) {
return;
}
activationState.isActivated = true;
activationState.isProgrammatic = event === undefined;
activationState.activationEvent = event;
activationState.wasActivatedByPointer = activationState.isProgrammatic ?
false :
event !== undefined &&
(event.type === 'mousedown' || event.type === 'touchstart' ||
event.type === 'pointerdown');
const hasActivatedChild = event !== undefined &&
activatedTargets.length > 0 &&
activatedTargets.some(
(target) => this.adapter.containsEventTarget(target));
if (hasActivatedChild) {
// Immediately reset activation state, while preserving logic that
// prevents touch follow-on events
this.resetActivationState();
return;
}
if (event !== undefined) {
activatedTargets.push(event.target);
this.registerDeactivationHandlers(event);
}
activationState.wasElementMadeActive = this.checkElementMadeActive(event);
if (activationState.wasElementMadeActive) {
this.animateActivation();
}
requestAnimationFrame(() => {
// Reset array on next frame after the current event has had a chance to
// bubble to prevent ancestor ripples
activatedTargets = [];
if (!activationState.wasElementMadeActive && event !== undefined &&
((event as KeyboardEvent).key === ' ' ||
(event as KeyboardEvent).keyCode === 32)) {
// If space was pressed, try again within an rAF call to detect :active,
// because different UAs report active states inconsistently when
// they're called within event handling code:
// - path_to_url
// - path_to_url
// We try first outside rAF to support Edge, which does not exhibit this
// problem, but will crash if a CSS variable is set within a rAF
// callback for a submit button interaction (#2241).
activationState.wasElementMadeActive = this.checkElementMadeActive(event);
if (activationState.wasElementMadeActive) {
this.animateActivation();
}
}
if (!activationState.wasElementMadeActive) {
// Reset activation state immediately if element was not made active.
this.activationState = this.defaultActivationState();
}
});
}
private checkElementMadeActive(event?: Event) {
return (event !== undefined && event.type === 'keydown') ?
this.adapter.isSurfaceActive() :
true;
}
private animateActivation() {
const {VAR_FG_TRANSLATE_START, VAR_FG_TRANSLATE_END} =
MDCRippleFoundation.strings;
const {FG_DEACTIVATION, FG_ACTIVATION} = MDCRippleFoundation.cssClasses;
const {DEACTIVATION_TIMEOUT_MS} = MDCRippleFoundation.numbers;
this.layoutInternal();
let translateStart = '';
let translateEnd = '';
if (!this.adapter.isUnbounded()) {
const {startPoint, endPoint} = this.getFgTranslationCoordinates();
translateStart = `${startPoint.x}px, ${startPoint.y}px`;
translateEnd = `${endPoint.x}px, ${endPoint.y}px`;
}
this.adapter.updateCssVariable(VAR_FG_TRANSLATE_START, translateStart);
this.adapter.updateCssVariable(VAR_FG_TRANSLATE_END, translateEnd);
// Cancel any ongoing activation/deactivation animations
clearTimeout(this.activationTimer);
clearTimeout(this.fgDeactivationRemovalTimer);
this.rmBoundedActivationClasses();
this.adapter.removeClass(FG_DEACTIVATION);
// Force layout in order to re-trigger the animation.
this.adapter.computeBoundingRect();
this.adapter.addClass(FG_ACTIVATION);
this.activationTimer = setTimeout(() => {
this.activationTimerCallback();
}, DEACTIVATION_TIMEOUT_MS);
}
private getFgTranslationCoordinates(): FgTranslationCoordinates {
const {activationEvent, wasActivatedByPointer} = this.activationState;
let startPoint;
if (wasActivatedByPointer) {
startPoint = getNormalizedEventCoords(
activationEvent,
this.adapter.getWindowPageOffset(),
this.adapter.computeBoundingRect(),
);
} else {
startPoint = {
x: this.frame.width / 2,
y: this.frame.height / 2,
};
}
// Center the element around the start point.
startPoint = {
x: startPoint.x - (this.initialSize / 2),
y: startPoint.y - (this.initialSize / 2),
};
const endPoint = {
x: (this.frame.width / 2) - (this.initialSize / 2),
y: (this.frame.height / 2) - (this.initialSize / 2),
};
return {startPoint, endPoint};
}
private runDeactivationUXLogicIfReady() {
// This method is called both when a pointing device is released, and when
// the activation animation ends. The deactivation animation should only run
// after both of those occur.
const {FG_DEACTIVATION} = MDCRippleFoundation.cssClasses;
const {hasDeactivationUXRun, isActivated} = this.activationState;
const activationHasEnded = hasDeactivationUXRun || !isActivated;
if (activationHasEnded && this.activationAnimationHasEnded) {
this.rmBoundedActivationClasses();
this.adapter.addClass(FG_DEACTIVATION);
this.fgDeactivationRemovalTimer = setTimeout(() => {
this.adapter.removeClass(FG_DEACTIVATION);
}, numbers.FG_DEACTIVATION_MS);
}
}
private rmBoundedActivationClasses() {
const {FG_ACTIVATION} = MDCRippleFoundation.cssClasses;
this.adapter.removeClass(FG_ACTIVATION);
this.activationAnimationHasEnded = false;
this.adapter.computeBoundingRect();
}
private resetActivationState() {
this.previousActivationEvent = this.activationState.activationEvent;
this.activationState = this.defaultActivationState();
// Touch devices may fire additional events for the same interaction within
// a short time. Store the previous event until it's safe to assume that
// subsequent events are for new interactions.
setTimeout(
() => this.previousActivationEvent = undefined,
MDCRippleFoundation.numbers.TAP_DELAY_MS);
}
private deactivateImpl(): void {
const activationState = this.activationState;
// This can happen in scenarios such as when you have a keyup event that
// blurs the element.
if (!activationState.isActivated) {
return;
}
const state: ActivationStateType = {...activationState};
if (activationState.isProgrammatic) {
requestAnimationFrame(() => {
this.animateDeactivation(state);
});
this.resetActivationState();
} else {
this.deregisterDeactivationHandlers();
requestAnimationFrame(() => {
this.activationState.hasDeactivationUXRun = true;
this.animateDeactivation(state);
this.resetActivationState();
});
}
}
private animateDeactivation({wasActivatedByPointer, wasElementMadeActive}:
ActivationStateType) {
if (wasActivatedByPointer || wasElementMadeActive) {
this.runDeactivationUXLogicIfReady();
}
}
private layoutInternal() {
this.frame = this.adapter.computeBoundingRect();
const maxDim = Math.max(this.frame.height, this.frame.width);
// Surface diameter is treated differently for unbounded vs. bounded
// ripples. Unbounded ripple diameter is calculated smaller since the
// surface is expected to already be padded appropriately to extend the
// hitbox, and the ripple is expected to meet the edges of the padded hitbox
// (which is typically square). Bounded ripples, on the other hand, are
// fully expected to expand beyond the surface's longest diameter
// (calculated based on the diagonal plus a constant padding), and are
// clipped at the surface's border via `overflow: hidden`.
const getBoundedRadius = () => {
const hypotenuse = Math.sqrt(
Math.pow(this.frame.width, 2) + Math.pow(this.frame.height, 2));
return hypotenuse + MDCRippleFoundation.numbers.PADDING;
};
this.maxRadius = this.adapter.isUnbounded() ? maxDim : getBoundedRadius();
// Ripple is sized as a fraction of the largest dimension of the surface,
// then scales up using a CSS scale transform
const initialSize =
Math.floor(maxDim * MDCRippleFoundation.numbers.INITIAL_ORIGIN_SCALE);
// Unbounded ripple size should always be even number to equally center
// align.
if (this.adapter.isUnbounded() && initialSize % 2 !== 0) {
this.initialSize = initialSize - 1;
} else {
this.initialSize = initialSize;
}
this.fgScale = `${this.maxRadius / this.initialSize}`;
this.updateLayoutCssVars();
}
private updateLayoutCssVars() {
const {
VAR_FG_SIZE,
VAR_LEFT,
VAR_TOP,
VAR_FG_SCALE,
} = MDCRippleFoundation.strings;
this.adapter.updateCssVariable(VAR_FG_SIZE, `${this.initialSize}px`);
this.adapter.updateCssVariable(VAR_FG_SCALE, this.fgScale);
if (this.adapter.isUnbounded()) {
this.unboundedCoords = {
left: Math.round((this.frame.width / 2) - (this.initialSize / 2)),
top: Math.round((this.frame.height / 2) - (this.initialSize / 2)),
};
this.adapter.updateCssVariable(
VAR_LEFT, `${this.unboundedCoords.left}px`);
this.adapter.updateCssVariable(VAR_TOP, `${this.unboundedCoords.top}px`);
}
}
}
// tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier.
export default MDCRippleFoundation;
``` | /content/code_sandbox/packages/mdc-ripple/foundation.ts | xml | 2016-12-05T16:04:09 | 2024-08-16T15:42:22 | material-components-web | material-components/material-components-web | 17,119 | 4,485 |
```xml
import { ResponsiveRadar } from '@nivo/radar'
import { generateWinesTastes } from '@nivo/generators'
import { useChart } from '../hooks'
const props = {
indexBy: 'taste',
margin: { top: 60, right: 80, bottom: 20, left: 80 },
}
export function Radar() {
const [data] = useChart(generateWinesTastes)
return <ResponsiveRadar {...data} {...props} />
}
``` | /content/code_sandbox/examples/codesandbox/src/charts/Radar.tsx | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 110 |
```xml
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing,
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// specific language governing permissions and limitations
import { Data } from '../data.js';
import { DataType } from '../type.js';
/** @ignore */
export class ChunkedIterator<T extends DataType> implements IterableIterator<T['TValue'] | null> {
private chunkIndex = 0;
private chunkIterator: IterableIterator<T['TValue'] | null>;
constructor(
private numChunks: number = 0,
private getChunkIterator: (chunkIndex: number) => IterableIterator<T['TValue'] | null>
) {
this.chunkIterator = this.getChunkIterator(0);
}
next(): IteratorResult<T['TValue'] | null> {
while (this.chunkIndex < this.numChunks) {
const next = this.chunkIterator.next();
if (!next.done) {
return next;
}
if (++this.chunkIndex < this.numChunks) {
this.chunkIterator = this.getChunkIterator(this.chunkIndex);
}
}
return { done: true, value: null };
}
[Symbol.iterator]() {
return this;
}
}
/** @ignore */
export function computeChunkNullable<T extends DataType>(chunks: ReadonlyArray<Data<T>>) {
return chunks.some(chunk => chunk.nullable);
}
/** @ignore */
export function computeChunkNullCounts<T extends DataType>(chunks: ReadonlyArray<Data<T>>) {
return chunks.reduce((nullCount, chunk) => nullCount + chunk.nullCount, 0);
}
/** @ignore */
export function computeChunkOffsets<T extends DataType>(chunks: ReadonlyArray<Data<T>>) {
return chunks.reduce((offsets, chunk, index) => {
offsets[index + 1] = offsets[index] + chunk.length;
return offsets;
}, new Uint32Array(chunks.length + 1));
}
/** @ignore */
export function sliceChunks<T extends DataType>(chunks: ReadonlyArray<Data<T>>, offsets: Uint32Array | Array<number>, begin: number, end: number) {
const slices: Data<T>[] = [];
for (let i = -1, n = chunks.length; ++i < n;) {
const chunk = chunks[i];
const offset = offsets[i];
const { length } = chunk;
// Stop if the child is to the right of the slice boundary
if (offset >= end) { break; }
// Exclude children to the left of of the slice boundary
if (begin >= offset + length) { continue; }
// Include entire child if between both left and right boundaries
if (offset >= begin && (offset + length) <= end) {
slices.push(chunk);
continue;
}
// Include the child slice that overlaps one of the slice boundaries
const from = Math.max(0, begin - offset);
const to = Math.min(end - offset, length);
slices.push(chunk.slice(from, to - from));
}
if (slices.length === 0) {
slices.push(chunks[0].slice(0, 0));
}
return slices;
}
/** @ignore */
export function binarySearch<
T extends DataType,
F extends (chunks: ReadonlyArray<Data<T>>, _1: number, _2: number) => any
>(chunks: ReadonlyArray<Data<T>>, offsets: Uint32Array | number[], idx: number, fn: F) {
let lhs = 0, mid = 0, rhs = offsets.length - 1;
do {
if (lhs >= rhs - 1) {
return (idx < offsets[rhs]) ? fn(chunks, lhs, idx - offsets[lhs]) : null;
}
mid = lhs + (Math.trunc((rhs - lhs) * .5));
idx < offsets[mid] ? (rhs = mid) : (lhs = mid);
} while (lhs < rhs);
}
/** @ignore */
export function isChunkedValid<T extends DataType>(data: Data<T>, index: number): boolean {
return data.getValid(index);
}
/** @ignore */
export function wrapChunkedCall1<T extends DataType>(fn: (c: Data<T>, _1: number) => any) {
function chunkedFn(chunks: ReadonlyArray<Data<T>>, i: number, j: number) { return fn(chunks[i], j); }
return function (this: any, index: number) {
const data = this.data as ReadonlyArray<Data<T>>;
return binarySearch(data, this._offsets, index, chunkedFn);
};
}
/** @ignore */
export function wrapChunkedCall2<T extends DataType>(fn: (c: Data<T>, _1: number, _2: any) => any) {
let _2: any;
function chunkedFn(chunks: ReadonlyArray<Data<T>>, i: number, j: number) { return fn(chunks[i], j, _2); }
return function (this: any, index: number, value: any) {
const data = this.data as ReadonlyArray<Data<T>>;
_2 = value;
const result = binarySearch(data, this._offsets, index, chunkedFn);
_2 = undefined;
return result;
};
}
/** @ignore */
export function wrapChunkedIndexOf<T extends DataType>(indexOf: (c: Data<T>, e: T['TValue'], o?: number) => any) {
let _1: any;
function chunkedIndexOf(data: ReadonlyArray<Data<T>>, chunkIndex: number, fromIndex: number) {
let begin = fromIndex, index = 0, total = 0;
for (let i = chunkIndex - 1, n = data.length; ++i < n;) {
const chunk = data[i];
if (~(index = indexOf(chunk, _1, begin))) {
return total + index;
}
begin = 0;
total += chunk.length;
}
return -1;
}
return function (this: any, element: T['TValue'], offset?: number) {
_1 = element;
const data = this.data as ReadonlyArray<Data<T>>;
const result = typeof offset !== 'number'
? chunkedIndexOf(data, 0, 0)
: binarySearch(data, this._offsets, offset, chunkedIndexOf);
_1 = undefined;
return result;
};
}
``` | /content/code_sandbox/js/src/util/chunk.ts | xml | 2016-02-17T08:00:23 | 2024-08-16T19:00:48 | arrow | apache/arrow | 14,094 | 1,410 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="library_name">Xamarin.Forms.Platform.Android.AppLinks</string>
</resources>
``` | /content/code_sandbox/Xamarin.Forms.Platform.Android.AppLinks/Resources/values/Strings.xml | xml | 2016-03-18T15:52:03 | 2024-08-16T16:25:43 | Xamarin.Forms | xamarin/Xamarin.Forms | 5,637 | 39 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="path_to_url" xmlns:xsi="path_to_url" xmlns:activiti="path_to_url" xmlns:bpmndi="path_to_url" xmlns:omgdc="path_to_url" xmlns:omgdi="path_to_url" typeLanguage="path_to_url" expressionLanguage="path_to_url" targetNamespace="path_to_url">
<process id="simpleProcess" name="Simple process" isExecutable="true">
<startEvent id="start" name="Start JUnit"></startEvent>
<sequenceFlow id="flow1" name="" sourceRef="start" targetRef="waitTask"></sequenceFlow>
<userTask id="waitTask" name="WaitTask" activiti:assignee="kermit" />
<sequenceFlow id="flow2" sourceRef="waitTask" targetRef="end"></sequenceFlow>
<endEvent id="end" name="End JUnit"></endEvent>
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable-rest/src/test/resources/org/flowable/rest/service/api/legacy/StartProcessInstanceResourceTest.testStartInstanceWithVariables.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 222 |
```xml
import * as shiki from 'shiki';
import { JSDOM } from 'jsdom';
import { visit } from 'unist-util-visit';
import theme from './theme.json';
const dom = new JSDOM();
const document = dom.window.document;
/**
* Some langs are highlighted with different grammar rules but need to be displayed
*/
const LANG_REPLACEMENTS = {
'vue-html': 'vue',
};
const highlighterPromise = shiki.getHighlighter({
// Complete themes: path_to_url
theme: theme as any,
langs: ['js', 'ts', 'vue', 'graphql', 'jsx', 'css', 'sh', 'yaml', 'json', 'vue-html', 'html'],
});
export default function highlight() {
return async function (tree) {
const highlighter = await highlighterPromise;
visit(tree, 'code', visitor);
function visitor(node) {
const { lang, lines, fileName } = parseParts(node.lang || 'sh');
try {
const html = replaceColorsWithVariables(highlighter.codeToHtml(node.value, { lang: lang || 'sh' }));
const fragment = document.createDocumentFragment();
const wrapper = document.createElement('div');
wrapper.classList.add('shiki-snippet');
wrapper.innerHTML = html;
fragment.appendChild(wrapper);
const langSpan = createSpan(LANG_REPLACEMENTS[lang] || lang, 'shiki-language', {
'data-language': lang,
});
const shikiEl = fragment.querySelector('.shiki') as HTMLElement | null;
shikiEl?.prepend(langSpan);
if (lines.length) {
lines.forEach(line => {
const lineEl = fragment.querySelector(`.line:nth-child(${line})`) as HTMLElement | null;
lineEl?.classList.add('is-highlighted');
});
shikiEl?.classList.add('with-line-highlights');
}
fragment.querySelector('.line:last-child:empty')?.remove();
if ([...fragment.querySelectorAll('.line')].length === 1) {
shikiEl?.classList.add('single-line');
}
if (fileName) {
wrapper.prepend(createSpan(fileName, 'filename'));
shikiEl?.classList.add('with-filename');
}
node.value = fragment.querySelector('.shiki-snippet')?.outerHTML;
node.type = 'html';
} catch (err) {
console.error(err);
console.log(node.lang);
}
}
};
}
function createSpan(text: string, className: string, attrs?: Record<string, string>) {
const document = dom.window.document;
const span = document.createElement('span');
span.textContent = text;
span.classList.add(className);
if (attrs) {
Object.keys(attrs).forEach(attr => {
span.setAttribute(attr, attrs[attr]);
});
}
return span;
}
function replaceColorsWithVariables(html) {
const colors = [
{ variable: '--code-foreground', value: '#f8f8f2' },
{ variable: '--code-background', value: '#22212c' },
{ variable: '--code-token-constant', value: '#9580ff' },
{ variable: '--code-token-operator', value: '#ff80bf' },
{ variable: '--code-token-type', value: '#80ffea' },
{ variable: '--code-token-parameter', value: '#ffca80' },
{ variable: '--code-token-attribute', value: '#8aff80' },
{ variable: '--code-token-regex', value: '#ff9580' },
{ variable: '--code-token-string', value: '#ffff80' },
{ variable: '--code-token-comment', value: '#7970a9' },
];
let str = html;
colors.forEach(color => {
str = str.replace(new RegExp(`color:\\s*${color.value}`, 'ig'), `color: var(${color.variable})`);
});
return str;
}
function parseLines(lines) {
return lines.split(',').reduce((acc, line) => {
if (/-/.test(line)) {
const [start, end] = line.split('-').map(ln => Number(ln));
let current = start;
while (current <= end) {
acc.push(current);
current++;
}
return acc;
}
acc.push(Number(line));
return acc;
}, []);
}
const fileNameRE = /\[(.+)\]/;
const linesRE = /\{(.+)\}/;
function parseParts(lang) {
lang = lang.trim();
const [, fileName] = lang.match(fileNameRE) || [];
const [, lines] = lang.match(linesRE) || [];
const rawLang = lang.replace(fileNameRE, '').replace(linesRE, '');
return {
lang: rawLang,
lines: lines ? parseLines(lines.replace()) : [],
fileName,
};
}
``` | /content/code_sandbox/docs/highlight.ts | xml | 2016-07-30T01:10:44 | 2024-08-16T10:19:58 | vee-validate | logaretm/vee-validate | 10,699 | 1,030 |
```xml
import { Repository } from '../core/repository';
import {
DirectRepositoryCreateGroupThreadResponseRootObject,
DirectRepositoryGetPresenceResponseRootObject,
DirectRepositoryRankedRecipientsResponseRootObject,
} from '../responses';
export class DirectRepository extends Repository {
public async createGroupThread(
recipientUsers: string[],
threadTitle: string,
): Promise<DirectRepositoryCreateGroupThreadResponseRootObject> {
const { body } = await this.client.request.send({
url: '/api/v1/direct_v2/create_group_thread/',
method: 'POST',
form: this.client.request.sign({
_csrftoken: this.client.state.cookieCsrfToken,
_uuid: this.client.state.uuid,
_uid: this.client.state.cookieUserId,
recipient_users: JSON.stringify(recipientUsers),
thread_title: threadTitle,
}),
});
return body;
}
public async rankedRecipients(
mode: 'raven' | 'reshare' = 'raven',
query = '',
): Promise<DirectRepositoryRankedRecipientsResponseRootObject> {
const { body } = await this.client.request.send<DirectRepositoryRankedRecipientsResponseRootObject>({
url: '/api/v1/direct_v2/ranked_recipients/',
method: 'GET',
qs: {
mode,
query,
show_threads: true,
},
});
return body;
}
public async getPresence(): Promise<DirectRepositoryGetPresenceResponseRootObject> {
const { body } = await this.client.request.send<DirectRepositoryGetPresenceResponseRootObject>({
url: '/api/v1/direct_v2/get_presence/',
method: 'GET',
});
return body;
}
}
``` | /content/code_sandbox/src/repositories/direct.repository.ts | xml | 2016-06-09T12:14:48 | 2024-08-16T10:07:22 | instagram-private-api | dilame/instagram-private-api | 5,877 | 364 |
```xml
/*
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*
*/
import { P2P } from '../../src/index';
import { wait } from '../utils/helpers';
import { createNetwork, destroyNetwork, NETWORK_START_PORT } from '../utils/network_setup';
describe('Maximum transactions', () => {
let p2pNodeList: ReadonlyArray<P2P> = [];
let collectedMessages: Array<any> = [];
const disconnectReasons: Array<any> = [];
let dataLargerThanMaxPayload: Array<string>;
beforeEach(async () => {
dataLargerThanMaxPayload = [];
for (let i = 0; i < 1000; i += 1) {
dataLargerThanMaxPayload.push(`message${i}`);
}
const customConfig = (_index: number) => ({
wsMaxPayload: 5000,
});
p2pNodeList = await createNetwork({ customConfig });
collectedMessages = [];
p2pNodeList.forEach(p2p => {
p2p.on('EVENT_MESSAGE_RECEIVED', message => {
if (message.event === 'maxPayload') {
collectedMessages.push({
nodePort: p2p.config.port,
message,
});
}
});
p2p.on('EVENT_CLOSE_INBOUND', packet => {
disconnectReasons.push({
peerPort: packet.peerInfo.port,
code: packet.code,
reason: packet.reason,
});
});
p2p.on('EVENT_CLOSE_OUTBOUND', packet => {
disconnectReasons.push({
peerPort: packet.peerInfo.port,
code: packet.code,
reason: packet.reason,
});
});
});
});
afterEach(async () => {
await destroyNetwork(p2pNodeList);
});
it('should not send a package larger than the ws max transactions', async () => {
const firstP2PNode = p2pNodeList[0];
firstP2PNode.send({
event: 'maxPayload',
data: dataLargerThanMaxPayload,
});
await wait(100);
expect(Object.keys(collectedMessages)).toHaveLength(0);
});
it('should disconnect the peer which has sent the message', async () => {
const firstP2PNode = p2pNodeList[0];
firstP2PNode.send({
event: 'maxPayload',
data: dataLargerThanMaxPayload,
});
await wait(100);
const disconnectMaxPayload = disconnectReasons.filter(
packet =>
packet.reason === 'Message was too big to process' &&
packet.code === 1009 &&
packet.peerPort === NETWORK_START_PORT,
);
expect(disconnectMaxPayload.length).toBeGreaterThan(0);
expect(disconnectMaxPayload[0]).toMatchObject({
code: 1009,
reason: 'Message was too big to process',
});
});
});
``` | /content/code_sandbox/elements/lisk-p2p/test/functional/maximum_payload.spec.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 708 |
```xml
import { matches, mock } from "jest-mock-extended";
import { BehaviorSubject, of } from "rxjs";
import { UserDecryptionOptionsServiceAbstraction } from "@bitwarden/auth/common";
import { UserDecryptionOptions } from "../../../../auth/src/common/models/domain/user-decryption-options";
import { FakeAccountService, mockAccountServiceWith } from "../../../spec/fake-account-service";
import { FakeActiveUserState } from "../../../spec/fake-state";
import { FakeStateProvider } from "../../../spec/fake-state-provider";
import { DeviceType } from "../../enums";
import { AppIdService } from "../../platform/abstractions/app-id.service";
import { ConfigService } from "../../platform/abstractions/config/config.service";
import { CryptoFunctionService } from "../../platform/abstractions/crypto-function.service";
import { CryptoService } from "../../platform/abstractions/crypto.service";
import { EncryptService } from "../../platform/abstractions/encrypt.service";
import { I18nService } from "../../platform/abstractions/i18n.service";
import { KeyGenerationService } from "../../platform/abstractions/key-generation.service";
import { LogService } from "../../platform/abstractions/log.service";
import { PlatformUtilsService } from "../../platform/abstractions/platform-utils.service";
import { AbstractStorageService } from "../../platform/abstractions/storage.service";
import { StorageLocation } from "../../platform/enums";
import { EncryptionType } from "../../platform/enums/encryption-type.enum";
import { Utils } from "../../platform/misc/utils";
import { EncString } from "../../platform/models/domain/enc-string";
import { StorageOptions } from "../../platform/models/domain/storage-options";
import { SymmetricCryptoKey } from "../../platform/models/domain/symmetric-crypto-key";
import { CsprngArray } from "../../types/csprng";
import { UserId } from "../../types/guid";
import { DeviceKey, UserKey } from "../../types/key";
import { DeviceResponse } from "../abstractions/devices/responses/device.response";
import { DevicesApiServiceAbstraction } from "../abstractions/devices-api.service.abstraction";
import { UpdateDevicesTrustRequest } from "../models/request/update-devices-trust.request";
import { ProtectedDeviceResponse } from "../models/response/protected-device.response";
import {
SHOULD_TRUST_DEVICE,
DEVICE_KEY,
DeviceTrustService,
} from "./device-trust.service.implementation";
describe("deviceTrustService", () => {
let deviceTrustService: DeviceTrustService;
const keyGenerationService = mock<KeyGenerationService>();
const cryptoFunctionService = mock<CryptoFunctionService>();
const cryptoService = mock<CryptoService>();
const encryptService = mock<EncryptService>();
const appIdService = mock<AppIdService>();
const devicesApiService = mock<DevicesApiServiceAbstraction>();
const i18nService = mock<I18nService>();
const platformUtilsService = mock<PlatformUtilsService>();
const secureStorageService = mock<AbstractStorageService>();
const logService = mock<LogService>();
const configService = mock<ConfigService>();
const userDecryptionOptionsService = mock<UserDecryptionOptionsServiceAbstraction>();
const decryptionOptions = new BehaviorSubject<UserDecryptionOptions>(null);
let stateProvider: FakeStateProvider;
const mockUserId = Utils.newGuid() as UserId;
let accountService: FakeAccountService;
const deviceKeyPartialSecureStorageKey = "_deviceKey";
const deviceKeySecureStorageKey = `${mockUserId}${deviceKeyPartialSecureStorageKey}`;
const secureStorageOptions: StorageOptions = {
storageLocation: StorageLocation.Disk,
useSecureStorage: true,
userId: mockUserId,
};
beforeEach(() => {
jest.clearAllMocks();
const supportsSecureStorage = false; // default to false; tests will override as needed
// By default all the tests will have a mocked active user in state provider.
deviceTrustService = createDeviceTrustService(mockUserId, supportsSecureStorage);
});
it("instantiates", () => {
expect(deviceTrustService).not.toBeFalsy();
});
describe("User Trust Device Choice For Decryption", () => {
describe("getShouldTrustDevice", () => {
it("gets the user trust device choice for decryption", async () => {
const newValue = true;
await stateProvider.setUserState(SHOULD_TRUST_DEVICE, newValue, mockUserId);
const result = await deviceTrustService.getShouldTrustDevice(mockUserId);
expect(result).toEqual(newValue);
});
});
describe("setShouldTrustDevice", () => {
it("sets the user trust device choice for decryption ", async () => {
await stateProvider.setUserState(SHOULD_TRUST_DEVICE, false, mockUserId);
const newValue = true;
await deviceTrustService.setShouldTrustDevice(mockUserId, newValue);
const result = await deviceTrustService.getShouldTrustDevice(mockUserId);
expect(result).toEqual(newValue);
});
});
});
describe("trustDeviceIfRequired", () => {
it("should trust device and reset when getShouldTrustDevice returns true", async () => {
jest.spyOn(deviceTrustService, "getShouldTrustDevice").mockResolvedValue(true);
jest.spyOn(deviceTrustService, "trustDevice").mockResolvedValue({} as DeviceResponse);
jest.spyOn(deviceTrustService, "setShouldTrustDevice").mockResolvedValue();
await deviceTrustService.trustDeviceIfRequired(mockUserId);
expect(deviceTrustService.getShouldTrustDevice).toHaveBeenCalledTimes(1);
expect(deviceTrustService.trustDevice).toHaveBeenCalledTimes(1);
expect(deviceTrustService.setShouldTrustDevice).toHaveBeenCalledWith(mockUserId, null);
});
it("should not trust device nor reset when getShouldTrustDevice returns false", async () => {
const getShouldTrustDeviceSpy = jest
.spyOn(deviceTrustService, "getShouldTrustDevice")
.mockResolvedValue(false);
const trustDeviceSpy = jest.spyOn(deviceTrustService, "trustDevice");
const setShouldTrustDeviceSpy = jest.spyOn(deviceTrustService, "setShouldTrustDevice");
await deviceTrustService.trustDeviceIfRequired(mockUserId);
expect(getShouldTrustDeviceSpy).toHaveBeenCalledTimes(1);
expect(trustDeviceSpy).not.toHaveBeenCalled();
expect(setShouldTrustDeviceSpy).not.toHaveBeenCalled();
});
});
describe("Trusted Device Encryption core logic tests", () => {
const deviceKeyBytesLength = 64;
const userKeyBytesLength = 64;
describe("getDeviceKey", () => {
let existingDeviceKey: DeviceKey;
let existingDeviceKeyB64: { keyB64: string };
beforeEach(() => {
existingDeviceKey = new SymmetricCryptoKey(
new Uint8Array(deviceKeyBytesLength) as CsprngArray,
) as DeviceKey;
existingDeviceKeyB64 = existingDeviceKey.toJSON();
});
describe("Secure Storage not supported", () => {
it("returns null when there is not an existing device key", async () => {
await stateProvider.setUserState(DEVICE_KEY, null, mockUserId);
const deviceKey = await deviceTrustService.getDeviceKey(mockUserId);
expect(deviceKey).toBeNull();
expect(secureStorageService.get).not.toHaveBeenCalled();
});
it("returns the device key when there is an existing device key", async () => {
await stateProvider.setUserState(DEVICE_KEY, existingDeviceKey, mockUserId);
const deviceKey = await deviceTrustService.getDeviceKey(mockUserId);
expect(deviceKey).not.toBeNull();
expect(deviceKey).toBeInstanceOf(SymmetricCryptoKey);
expect(deviceKey).toEqual(existingDeviceKey);
expect(secureStorageService.get).not.toHaveBeenCalled();
});
});
describe("Secure Storage supported", () => {
beforeEach(() => {
const supportsSecureStorage = true;
deviceTrustService = createDeviceTrustService(mockUserId, supportsSecureStorage);
});
it("returns null when there is not an existing device key for the passed in user id", async () => {
secureStorageService.get.mockResolvedValue(null);
// Act
const deviceKey = await deviceTrustService.getDeviceKey(mockUserId);
// Assert
expect(deviceKey).toBeNull();
});
it("returns the device key when there is an existing device key for the passed in user id", async () => {
// Arrange
secureStorageService.get.mockResolvedValue(existingDeviceKeyB64);
// Act
const deviceKey = await deviceTrustService.getDeviceKey(mockUserId);
// Assert
expect(deviceKey).not.toBeNull();
expect(deviceKey).toBeInstanceOf(SymmetricCryptoKey);
expect(deviceKey).toEqual(existingDeviceKey);
});
});
it("throws an error when no user id is passed in", async () => {
await expect(deviceTrustService.getDeviceKey(null)).rejects.toThrow(
"UserId is required. Cannot get device key.",
);
});
});
describe("setDeviceKey", () => {
describe("Secure Storage not supported", () => {
it("successfully sets the device key in state provider", async () => {
await stateProvider.setUserState(DEVICE_KEY, null, mockUserId);
const newDeviceKey = new SymmetricCryptoKey(
new Uint8Array(deviceKeyBytesLength) as CsprngArray,
) as DeviceKey;
// TypeScript will allow calling private methods if the object is of type 'any'
// This is a hacky workaround, but it allows for cleaner tests
await (deviceTrustService as any).setDeviceKey(mockUserId, newDeviceKey);
expect(stateProvider.mock.setUserState).toHaveBeenLastCalledWith(
DEVICE_KEY,
newDeviceKey.toJSON(),
mockUserId,
);
});
});
describe("Secure Storage supported", () => {
beforeEach(() => {
const supportsSecureStorage = true;
deviceTrustService = createDeviceTrustService(mockUserId, supportsSecureStorage);
});
it("successfully sets the device key in secure storage", async () => {
// Arrange
await stateProvider.setUserState(DEVICE_KEY, null, mockUserId);
secureStorageService.get.mockResolvedValue(null);
const newDeviceKey = new SymmetricCryptoKey(
new Uint8Array(deviceKeyBytesLength) as CsprngArray,
) as DeviceKey;
// Act
// TypeScript will allow calling private methods if the object is of type 'any'
// This is a hacky workaround, but it allows for cleaner tests
await (deviceTrustService as any).setDeviceKey(mockUserId, newDeviceKey);
// Assert
expect(stateProvider.mock.setUserState).not.toHaveBeenCalledTimes(2);
expect(secureStorageService.save).toHaveBeenCalledWith(
deviceKeySecureStorageKey,
newDeviceKey,
secureStorageOptions,
);
});
});
it("throws an error when a null user id is passed in", async () => {
const newDeviceKey = new SymmetricCryptoKey(
new Uint8Array(deviceKeyBytesLength) as CsprngArray,
) as DeviceKey;
await expect((deviceTrustService as any).setDeviceKey(null, newDeviceKey)).rejects.toThrow(
"UserId is required. Cannot set device key.",
);
});
});
describe("makeDeviceKey", () => {
it("creates a new non-null 64 byte device key, securely stores it, and returns it", async () => {
const mockRandomBytes = new Uint8Array(deviceKeyBytesLength) as CsprngArray;
const mockDeviceKey = new SymmetricCryptoKey(mockRandomBytes) as DeviceKey;
const keyGenSvcGenerateKeySpy = jest
.spyOn(keyGenerationService, "createKey")
.mockResolvedValue(mockDeviceKey);
// TypeScript will allow calling private methods if the object is of type 'any'
// This is a hacky workaround, but it allows for cleaner tests
const deviceKey = await (deviceTrustService as any).makeDeviceKey();
expect(keyGenSvcGenerateKeySpy).toHaveBeenCalledTimes(1);
expect(keyGenSvcGenerateKeySpy).toHaveBeenCalledWith(deviceKeyBytesLength * 8);
expect(deviceKey).not.toBeNull();
expect(deviceKey).toBeInstanceOf(SymmetricCryptoKey);
});
});
describe("trustDevice", () => {
let mockDeviceKeyRandomBytes: CsprngArray;
let mockDeviceKey: DeviceKey;
let mockUserKeyRandomBytes: CsprngArray;
let mockUserKey: UserKey;
const deviceRsaKeyLength = 2048;
let mockDeviceRsaKeyPair: [Uint8Array, Uint8Array];
let mockDevicePrivateKey: Uint8Array;
let mockDevicePublicKey: Uint8Array;
let mockDevicePublicKeyEncryptedUserKey: EncString;
let mockUserKeyEncryptedDevicePublicKey: EncString;
let mockDeviceKeyEncryptedDevicePrivateKey: EncString;
const mockDeviceResponse: DeviceResponse = new DeviceResponse({
Id: "mockId",
Name: "mockName",
Identifier: "mockIdentifier",
Type: "mockType",
CreationDate: "mockCreationDate",
});
const mockDeviceId = "mockDeviceId";
let makeDeviceKeySpy: jest.SpyInstance;
let rsaGenerateKeyPairSpy: jest.SpyInstance;
let cryptoSvcGetUserKeySpy: jest.SpyInstance;
let cryptoSvcRsaEncryptSpy: jest.SpyInstance;
let encryptServiceEncryptSpy: jest.SpyInstance;
let appIdServiceGetAppIdSpy: jest.SpyInstance;
let devicesApiServiceUpdateTrustedDeviceKeysSpy: jest.SpyInstance;
beforeEach(() => {
// Setup all spies and default return values for the happy path
mockDeviceKeyRandomBytes = new Uint8Array(deviceKeyBytesLength) as CsprngArray;
mockDeviceKey = new SymmetricCryptoKey(mockDeviceKeyRandomBytes) as DeviceKey;
mockUserKeyRandomBytes = new Uint8Array(userKeyBytesLength) as CsprngArray;
mockUserKey = new SymmetricCryptoKey(mockUserKeyRandomBytes) as UserKey;
mockDeviceRsaKeyPair = [
new Uint8Array(deviceRsaKeyLength),
new Uint8Array(deviceRsaKeyLength),
];
mockDevicePublicKey = mockDeviceRsaKeyPair[0];
mockDevicePrivateKey = mockDeviceRsaKeyPair[1];
mockDevicePublicKeyEncryptedUserKey = new EncString(
EncryptionType.Rsa2048_OaepSha1_B64,
"mockDevicePublicKeyEncryptedUserKey",
);
mockUserKeyEncryptedDevicePublicKey = new EncString(
EncryptionType.AesCbc256_HmacSha256_B64,
"mockUserKeyEncryptedDevicePublicKey",
);
mockDeviceKeyEncryptedDevicePrivateKey = new EncString(
EncryptionType.AesCbc256_HmacSha256_B64,
"mockDeviceKeyEncryptedDevicePrivateKey",
);
// TypeScript will allow calling private methods if the object is of type 'any'
makeDeviceKeySpy = jest
.spyOn(deviceTrustService as any, "makeDeviceKey")
.mockResolvedValue(mockDeviceKey);
rsaGenerateKeyPairSpy = jest
.spyOn(cryptoFunctionService, "rsaGenerateKeyPair")
.mockResolvedValue(mockDeviceRsaKeyPair);
cryptoSvcGetUserKeySpy = jest
.spyOn(cryptoService, "getUserKey")
.mockResolvedValue(mockUserKey);
cryptoSvcRsaEncryptSpy = jest
.spyOn(cryptoService, "rsaEncrypt")
.mockResolvedValue(mockDevicePublicKeyEncryptedUserKey);
encryptServiceEncryptSpy = jest
.spyOn(encryptService, "encrypt")
.mockImplementation((plainValue, key) => {
if (plainValue === mockDevicePublicKey && key === mockUserKey) {
return Promise.resolve(mockUserKeyEncryptedDevicePublicKey);
}
if (plainValue === mockDevicePrivateKey && key === mockDeviceKey) {
return Promise.resolve(mockDeviceKeyEncryptedDevicePrivateKey);
}
});
appIdServiceGetAppIdSpy = jest
.spyOn(appIdService, "getAppId")
.mockResolvedValue(mockDeviceId);
devicesApiServiceUpdateTrustedDeviceKeysSpy = jest
.spyOn(devicesApiService, "updateTrustedDeviceKeys")
.mockResolvedValue(mockDeviceResponse);
});
it("calls the required methods with the correct arguments and returns a DeviceResponse", async () => {
const response = await deviceTrustService.trustDevice(mockUserId);
expect(makeDeviceKeySpy).toHaveBeenCalledTimes(1);
expect(rsaGenerateKeyPairSpy).toHaveBeenCalledTimes(1);
expect(cryptoSvcGetUserKeySpy).toHaveBeenCalledTimes(1);
expect(cryptoSvcRsaEncryptSpy).toHaveBeenCalledTimes(1);
// RsaEncrypt must be called w/ a user key array buffer of 64 bytes
const userKeyKey: Uint8Array = cryptoSvcRsaEncryptSpy.mock.calls[0][0];
expect(userKeyKey.byteLength).toBe(64);
expect(encryptServiceEncryptSpy).toHaveBeenCalledTimes(2);
expect(appIdServiceGetAppIdSpy).toHaveBeenCalledTimes(1);
expect(devicesApiServiceUpdateTrustedDeviceKeysSpy).toHaveBeenCalledTimes(1);
expect(devicesApiServiceUpdateTrustedDeviceKeysSpy).toHaveBeenCalledWith(
mockDeviceId,
mockDevicePublicKeyEncryptedUserKey.encryptedString,
mockUserKeyEncryptedDevicePublicKey.encryptedString,
mockDeviceKeyEncryptedDevicePrivateKey.encryptedString,
);
expect(response).toBeInstanceOf(DeviceResponse);
expect(response).toEqual(mockDeviceResponse);
});
it("throws specific error if user key is not found", async () => {
// setup the spy to return null
cryptoSvcGetUserKeySpy.mockResolvedValue(null);
// check if the expected error is thrown
await expect(deviceTrustService.trustDevice(mockUserId)).rejects.toThrow(
"User symmetric key not found",
);
// reset the spy
cryptoSvcGetUserKeySpy.mockReset();
// setup the spy to return undefined
cryptoSvcGetUserKeySpy.mockResolvedValue(undefined);
// check if the expected error is thrown
await expect(deviceTrustService.trustDevice(mockUserId)).rejects.toThrow(
"User symmetric key not found",
);
});
const methodsToTestForErrorsOrInvalidReturns: any = [
{
method: "makeDeviceKey",
spy: () => makeDeviceKeySpy,
errorText: "makeDeviceKey error",
},
{
method: "rsaGenerateKeyPair",
spy: () => rsaGenerateKeyPairSpy,
errorText: "rsaGenerateKeyPair error",
},
{
method: "getUserKey",
spy: () => cryptoSvcGetUserKeySpy,
errorText: "getUserKey error",
},
{
method: "rsaEncrypt",
spy: () => cryptoSvcRsaEncryptSpy,
errorText: "rsaEncrypt error",
},
{
method: "encryptService.encrypt",
spy: () => encryptServiceEncryptSpy,
errorText: "encryptService.encrypt error",
},
];
describe.each(methodsToTestForErrorsOrInvalidReturns)(
"trustDevice error handling and invalid return testing",
({ method, spy, errorText }) => {
// ensures that error propagation works correctly
it(`throws an error if ${method} fails`, async () => {
const methodSpy = spy();
methodSpy.mockRejectedValue(new Error(errorText));
await expect(deviceTrustService.trustDevice(mockUserId)).rejects.toThrow(errorText);
});
test.each([null, undefined])(
`throws an error if ${method} returns %s`,
async (invalidValue) => {
const methodSpy = spy();
methodSpy.mockResolvedValue(invalidValue);
await expect(deviceTrustService.trustDevice(mockUserId)).rejects.toThrow();
},
);
},
);
it("throws an error when a null user id is passed in", async () => {
await expect(deviceTrustService.trustDevice(null)).rejects.toThrow(
"UserId is required. Cannot trust device.",
);
});
});
describe("decryptUserKeyWithDeviceKey", () => {
let mockDeviceKey: DeviceKey;
let mockEncryptedDevicePrivateKey: EncString;
let mockEncryptedUserKey: EncString;
let mockUserKey: UserKey;
beforeEach(() => {
const mockDeviceKeyRandomBytes = new Uint8Array(deviceKeyBytesLength) as CsprngArray;
mockDeviceKey = new SymmetricCryptoKey(mockDeviceKeyRandomBytes) as DeviceKey;
const mockUserKeyRandomBytes = new Uint8Array(userKeyBytesLength) as CsprngArray;
mockUserKey = new SymmetricCryptoKey(mockUserKeyRandomBytes) as UserKey;
mockEncryptedDevicePrivateKey = new EncString(
EncryptionType.AesCbc256_HmacSha256_B64,
"mockEncryptedDevicePrivateKey",
);
mockEncryptedUserKey = new EncString(
EncryptionType.AesCbc256_HmacSha256_B64,
"mockEncryptedUserKey",
);
jest.clearAllMocks();
});
it("throws an error when a null user id is passed in", async () => {
await expect(
deviceTrustService.decryptUserKeyWithDeviceKey(
null,
mockEncryptedDevicePrivateKey,
mockEncryptedUserKey,
mockDeviceKey,
),
).rejects.toThrow("UserId is required. Cannot decrypt user key with device key.");
});
it("throws an error when a nullish encrypted device private key is passed in", async () => {
await expect(
deviceTrustService.decryptUserKeyWithDeviceKey(
mockUserId,
null,
mockEncryptedUserKey,
mockDeviceKey,
),
).rejects.toThrow(
"Encrypted device private key is required. Cannot decrypt user key with device key.",
);
});
it("throws an error when a nullish encrypted user key is passed in", async () => {
await expect(
deviceTrustService.decryptUserKeyWithDeviceKey(
mockUserId,
mockEncryptedDevicePrivateKey,
null,
mockDeviceKey,
),
).rejects.toThrow(
"Encrypted user key is required. Cannot decrypt user key with device key.",
);
});
it("returns null when device key isn't provided", async () => {
const result = await deviceTrustService.decryptUserKeyWithDeviceKey(
mockUserId,
mockEncryptedDevicePrivateKey,
mockEncryptedUserKey,
mockDeviceKey,
);
expect(result).toBeNull();
});
it("successfully returns the user key when provided keys (including device key) can decrypt it", async () => {
const decryptToBytesSpy = jest
.spyOn(encryptService, "decryptToBytes")
.mockResolvedValue(new Uint8Array(userKeyBytesLength));
const rsaDecryptSpy = jest
.spyOn(cryptoService, "rsaDecrypt")
.mockResolvedValue(new Uint8Array(userKeyBytesLength));
const result = await deviceTrustService.decryptUserKeyWithDeviceKey(
mockUserId,
mockEncryptedDevicePrivateKey,
mockEncryptedUserKey,
mockDeviceKey,
);
expect(result).toEqual(mockUserKey);
expect(decryptToBytesSpy).toHaveBeenCalledTimes(1);
expect(rsaDecryptSpy).toHaveBeenCalledTimes(1);
});
it("returns null and removes device key when the decryption fails", async () => {
const decryptToBytesSpy = jest
.spyOn(encryptService, "decryptToBytes")
.mockRejectedValue(new Error("Decryption error"));
const setDeviceKeySpy = jest.spyOn(deviceTrustService as any, "setDeviceKey");
const result = await deviceTrustService.decryptUserKeyWithDeviceKey(
mockUserId,
mockEncryptedDevicePrivateKey,
mockEncryptedUserKey,
mockDeviceKey,
);
expect(result).toBeNull();
expect(decryptToBytesSpy).toHaveBeenCalledTimes(1);
expect(setDeviceKeySpy).toHaveBeenCalledTimes(1);
expect(setDeviceKeySpy).toHaveBeenCalledWith(mockUserId, null);
});
});
describe("rotateDevicesTrust", () => {
let fakeNewUserKey: UserKey = null;
const FakeNewUserKeyMarker = 1;
const FakeOldUserKeyMarker = 5;
const FakeDecryptedPublicKeyMarker = 17;
beforeEach(() => {
const fakeNewUserKeyData = new Uint8Array(64);
fakeNewUserKeyData.fill(FakeNewUserKeyMarker, 0, 1);
fakeNewUserKey = new SymmetricCryptoKey(fakeNewUserKeyData) as UserKey;
cryptoService.userKey$.mockReturnValue(of(fakeNewUserKey));
});
it("throws an error when a null user id is passed in", async () => {
await expect(
deviceTrustService.rotateDevicesTrust(null, fakeNewUserKey, ""),
).rejects.toThrow("UserId is required. Cannot rotate device's trust.");
});
it("does an early exit when the current device is not a trusted device", async () => {
const deviceKeyState: FakeActiveUserState<DeviceKey> =
stateProvider.activeUser.getFake(DEVICE_KEY);
deviceKeyState.nextState(null);
await deviceTrustService.rotateDevicesTrust(mockUserId, fakeNewUserKey, "");
expect(devicesApiService.updateTrust).not.toHaveBeenCalled();
});
describe("is on a trusted device", () => {
beforeEach(async () => {
const mockDeviceKey = new SymmetricCryptoKey(
new Uint8Array(deviceKeyBytesLength),
) as DeviceKey;
await stateProvider.setUserState(DEVICE_KEY, mockDeviceKey, mockUserId);
});
it("rotates current device keys and calls api service when the current device is trusted", async () => {
const currentEncryptedPublicKey = new EncString("2.cHVibGlj|cHVibGlj|cHVibGlj");
const currentEncryptedUserKey = new EncString("4.dXNlcg==");
const fakeOldUserKeyData = new Uint8Array(new Uint8Array(64));
// Fill the first byte with something identifiable
fakeOldUserKeyData.fill(FakeOldUserKeyMarker, 0, 1);
// Mock the retrieval of a user key that differs from the new one passed into the method
cryptoService.userKey$.mockReturnValue(
of(new SymmetricCryptoKey(fakeOldUserKeyData) as UserKey),
);
appIdService.getAppId.mockResolvedValue("test_device_identifier");
devicesApiService.getDeviceKeys.mockImplementation((deviceIdentifier, secretRequest) => {
if (
deviceIdentifier !== "test_device_identifier" ||
secretRequest.masterPasswordHash !== "my_password_hash"
) {
return Promise.resolve(null);
}
return Promise.resolve(
new ProtectedDeviceResponse({
id: "",
creationDate: "",
identifier: "test_device_identifier",
name: "Firefox",
type: DeviceType.FirefoxBrowser,
encryptedPublicKey: currentEncryptedPublicKey.encryptedString,
encryptedUserKey: currentEncryptedUserKey.encryptedString,
}),
);
});
// Mock the decryption of the public key with the old user key
encryptService.decryptToBytes.mockImplementationOnce((_encValue, privateKeyValue) => {
expect(privateKeyValue.key.byteLength).toBe(64);
expect(new Uint8Array(privateKeyValue.key)[0]).toBe(FakeOldUserKeyMarker);
const data = new Uint8Array(250);
data.fill(FakeDecryptedPublicKeyMarker, 0, 1);
return Promise.resolve(data);
});
// Mock the encryption of the new user key with the decrypted public key
cryptoService.rsaEncrypt.mockImplementationOnce((data, publicKey) => {
expect(data.byteLength).toBe(64); // New key should also be 64 bytes
expect(new Uint8Array(data)[0]).toBe(FakeNewUserKeyMarker); // New key should have the first byte be '1';
expect(new Uint8Array(publicKey)[0]).toBe(FakeDecryptedPublicKeyMarker);
return Promise.resolve(new EncString("4.ZW5jcnlwdGVkdXNlcg=="));
});
// Mock the reencryption of the device public key with the new user key
encryptService.encrypt.mockImplementationOnce((plainValue, key) => {
expect(plainValue).toBeInstanceOf(Uint8Array);
expect(new Uint8Array(plainValue as Uint8Array)[0]).toBe(FakeDecryptedPublicKeyMarker);
expect(new Uint8Array(key.key)[0]).toBe(FakeNewUserKeyMarker);
return Promise.resolve(
new EncString("2.ZW5jcnlwdGVkcHVibGlj|ZW5jcnlwdGVkcHVibGlj|ZW5jcnlwdGVkcHVibGlj"),
);
});
await deviceTrustService.rotateDevicesTrust(
mockUserId,
fakeNewUserKey,
"my_password_hash",
);
expect(devicesApiService.updateTrust).toHaveBeenCalledWith(
matches((updateTrustModel: UpdateDevicesTrustRequest) => {
return (
updateTrustModel.currentDevice.encryptedPublicKey ===
"2.ZW5jcnlwdGVkcHVibGlj|ZW5jcnlwdGVkcHVibGlj|ZW5jcnlwdGVkcHVibGlj" &&
updateTrustModel.currentDevice.encryptedUserKey === "4.ZW5jcnlwdGVkdXNlcg=="
);
}),
expect.stringMatching("test_device_identifier"),
);
});
});
});
});
// Helpers
function createDeviceTrustService(mockUserId: UserId | null, supportsSecureStorage: boolean) {
accountService = mockAccountServiceWith(mockUserId);
stateProvider = new FakeStateProvider(accountService);
platformUtilsService.supportsSecureStorage.mockReturnValue(supportsSecureStorage);
decryptionOptions.next({} as any);
userDecryptionOptionsService.userDecryptionOptions$ = decryptionOptions;
return new DeviceTrustService(
keyGenerationService,
cryptoFunctionService,
cryptoService,
encryptService,
appIdService,
devicesApiService,
i18nService,
platformUtilsService,
stateProvider,
secureStorageService,
userDecryptionOptionsService,
logService,
configService,
);
}
});
``` | /content/code_sandbox/libs/common/src/auth/services/device-trust.service.spec.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 6,518 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<selector xmlns:android="path_to_url">
<item android:color="?attr/colorOnSurface"/>
</selector>
``` | /content/code_sandbox/lib/java/com/google/android/material/timepicker/res/color-night/material_timepicker_modebutton_tint.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 76 |
```xml
import {css, html, LitElement, PropertyValues} from "lit";
import {customElement, property, state} from "lit/decorators.js";
import {ErrorObject} from "ajv";
import {
Actions,
configReducer,
CoreActions,
coreReducer,
createAjv,
Dispatch,
generateDefaultUISchema,
generateJsonSchema,
JsonFormsCellRendererRegistryEntry,
JsonFormsCore,
JsonFormsProps,
JsonFormsRendererRegistryEntry,
JsonFormsSubStates,
JsonFormsUISchemaRegistryEntry,
JsonSchema,
mapStateToJsonFormsRendererProps,
OwnPropsOfJsonFormsRenderer,
setConfig,
UISchemaElement
} from "@jsonforms/core";
import {getTemplateWrapper, StandardRenderers} from "./standard-renderers";
import {getLabel, getTemplateFromProps} from "./util";
import {baseStyle} from "./styles";
import {Util} from "@openremote/core";
import {AdditionalProps} from "./base-element";
declare global {
interface SymbolConstructor {
readonly observable: symbol;
}
}
export {
ErrorObject,
StandardRenderers,
getTemplateWrapper,
JsonFormsRendererRegistryEntry,
UISchemaElement
};
export interface JsonFormsStateContext extends JsonFormsSubStates {
dispatch: Dispatch<CoreActions>;
}
// language=CSS
const styles = css`
.delete-container {
width: 0;
}
.item-container {
margin: 0; /* Remove inherited margin */
}
`;
@customElement("or-json-forms")
export class OrJSONForms extends LitElement implements OwnPropsOfJsonFormsRenderer, AdditionalProps {
@property({type: Object})
public uischema?: UISchemaElement;
@property({type: Object})
public schema?: JsonSchema;
@property({type: Object, attribute: false})
public data: any;
@property({type: Array})
public renderers?: JsonFormsRendererRegistryEntry[] = StandardRenderers;
@property({type: Array})
public cells?: JsonFormsCellRendererRegistryEntry[];
@property({type: String, attribute: false})
public onChange?: (dataAndErrors: {errors: ErrorObject[] | undefined, data: any}) => void;
@property({type: String, attribute: false})
public config: any;
@property({type: Array})
public uischemas?: JsonFormsUISchemaRegistryEntry[];
@property({type: Boolean})
public readonly: boolean = false;
@property({type: String})
public label!: string;
@property({type: Boolean})
public required: boolean = false;
public static get styles() {
return [
baseStyle,
styles
];
}
@state()
protected core?: JsonFormsCore;
@state()
protected contextValue?: JsonFormsSubStates;
protected previousData: any;
protected previousErrors: ErrorObject[] = [];
public checkValidity() {
return this.previousErrors.length === 0;
}
shouldUpdate(_changedProperties: PropertyValues) {
super.shouldUpdate(_changedProperties);
if (!this.schema) {
this.schema = this.data !== undefined ? generateJsonSchema(this.data) : {};
}
if (!this.uischema) {
this.uischema = generateDefaultUISchema(this.schema!);
}
if (!this.core) {
this.core = {
ajv: createAjv({useDefaults: true, validateFormats: false}),
data: {},
schema: this.schema!,
uischema: this.uischema!
};
this.updateCore(Actions.init(this.data, this.schema, this.uischema));
this.config = configReducer(undefined, setConfig(this.config));
}
if (_changedProperties.has("data") || _changedProperties.has("schema") || _changedProperties.has("uischema")) {
this.updateCore(
Actions.updateCore(this.data, this.schema, this.uischema)
);
}
if (!this.contextValue || _changedProperties.has("core") || _changedProperties.has("renderers") || _changedProperties.has("cells") || _changedProperties.has("config") || _changedProperties.has("readonly")) {
this.contextValue = {
core: this.core,
renderers: this.renderers,
cells: this.cells,
config: this.config,
uischemas: this.uischemas,
readonly: this.readonly,
dispatch: (action: CoreActions) => this.updateCore(action)
}
}
if (_changedProperties.has("core")) {
const data = this.core!.data;
const errors = this.core!.errors;
if (this.onChange && (!Util.objectsEqual(data, this.previousData, true) || (errors && !Util.objectsEqual(errors, this.previousErrors, true)))) {
this.previousErrors = errors || [];
this.previousData = data;
this.onChange({data: data, errors: errors});
}
}
return true;
}
updateCore<T extends CoreActions>(coreAction: T): T {
const coreState = coreReducer(this.core, coreAction);
if(coreState !== this.core) {
this.core = coreState;
}
return coreAction;
}
render() {
if (!this.contextValue) {
return html``;
}
const props: JsonFormsProps & AdditionalProps = {
...mapStateToJsonFormsRendererProps({jsonforms: {...this.contextValue}}, this),
label: getLabel(this.schema!, this.uischema!, this.label, undefined) || "",
required: this.required
};
return getTemplateFromProps(this.contextValue, props) || html``;
}
}
``` | /content/code_sandbox/ui/component/or-json-forms/src/index.ts | xml | 2016-02-03T11:14:02 | 2024-08-16T12:45:50 | openremote | openremote/openremote | 1,184 | 1,221 |
```xml
import {PluginInputHandler} from "./index";
import Msg from "../../models/msg";
import Chan from "../../models/chan";
import {MessageType} from "../../../shared/types/msg";
import {ChanType} from "../../../shared/types/chan";
const commands = ["query", "msg", "say"];
function getTarget(cmd: string, args: string[], chan: Chan) {
switch (cmd) {
case "msg":
case "query":
return args.shift();
default:
return chan.name;
}
}
const input: PluginInputHandler = function (network, chan, cmd, args) {
let targetName = getTarget(cmd, args, chan);
if (cmd === "query") {
if (!targetName) {
chan.pushMessage(
this,
new Msg({
type: MessageType.ERROR,
text: "You cannot open a query window without an argument.",
})
);
return;
}
const target = network.getChannel(targetName);
if (typeof target === "undefined") {
const char = targetName[0];
if (
network.irc.network.options.CHANTYPES &&
network.irc.network.options.CHANTYPES.includes(char)
) {
chan.pushMessage(
this,
new Msg({
type: MessageType.ERROR,
text: "You can not open query windows for channels, use /join instead.",
})
);
return;
}
for (let i = 0; i < network.irc.network.options.PREFIX.length; i++) {
if (network.irc.network.options.PREFIX[i].symbol === char) {
chan.pushMessage(
this,
new Msg({
type: MessageType.ERROR,
text: "You can not open query windows for names starting with a user prefix.",
})
);
return;
}
}
const newChan = this.createChannel({
type: ChanType.QUERY,
name: targetName,
});
this.emit("join", {
network: network.uuid,
chan: newChan.getFilteredClone(true),
shouldOpen: true,
index: network.addChannel(newChan),
});
this.save();
newChan.loadMessages(this, network);
}
}
if (args.length === 0) {
return true;
}
if (!targetName) {
return true;
}
const msg = args.join(" ");
if (msg.length === 0) {
return true;
}
network.irc.say(targetName, msg);
// If the IRCd does not support echo-message, simulate the message
// being sent back to us.
if (!network.irc.network.cap.isEnabled("echo-message")) {
const parsedTarget = network.irc.network.extractTargetGroup(targetName);
let targetGroup: string | undefined = undefined;
if (parsedTarget) {
targetName = parsedTarget.target;
targetGroup = parsedTarget.target_group;
}
const channel = network.getChannel(targetName);
if (typeof channel !== "undefined") {
network.irc.emit("privmsg", {
nick: network.irc.user.nick,
ident: network.irc.user.username,
hostname: network.irc.user.host,
target: targetName,
group: targetGroup,
message: msg,
});
}
}
return true;
};
export default {
commands,
input,
};
``` | /content/code_sandbox/server/plugins/inputs/msg.ts | xml | 2016-02-09T03:16:03 | 2024-08-16T10:52:38 | thelounge | thelounge/thelounge | 5,518 | 732 |
```xml
import Koa from "koa";
import {PlatformKoaSettings} from "./PlatformKoaSettings.js";
export * from "./PlatformKoaSettings.js";
declare global {
namespace TsED {
export interface Configuration {
/**
* Configuration related to Koa platform application.
*/
koa: PlatformKoaSettings;
}
export interface NextFunction extends Koa.Next {}
}
}
``` | /content/code_sandbox/packages/platform/platform-koa/src/interfaces/interfaces.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 84 |
```xml
import { beforeEach, describe, expect, it } from 'bun:test';
import { getDefaultConfig } from '../../generator/config/defaultConfig';
import { loadFileIconDefinitions } from '../../generator/fileGenerator';
import type { Config } from '../../models/icons/config';
import type { FileIcons } from '../../models/icons/files/fileTypes';
import { IconPack } from '../../models/icons/iconPack';
import { type Manifest, createEmptyManifest } from '../../models/manifest';
describe('file icons', () => {
let expectedManifest: Manifest;
let config: Config;
beforeEach(() => {
config = getDefaultConfig();
expectedManifest = createEmptyManifest();
});
it('should configure icon definitions', () => {
const fileIcons: FileIcons = {
defaultIcon: { name: 'file' },
icons: [
{
name: 'angular',
fileNames: ['.angular-cli.json', 'angular-cli.json'],
enabledFor: [IconPack.Angular, IconPack.Ngrx],
},
{
name: 'javascript',
fileNames: ['filename.js'],
fileExtensions: ['js'],
},
],
};
const manifest = createEmptyManifest();
const iconDefinitions = loadFileIconDefinitions(
fileIcons,
config,
manifest
);
expectedManifest.iconDefinitions = {
angular: {
iconPath: './../icons/angular.svg',
},
javascript: {
iconPath: './../icons/javascript.svg',
},
file: {
iconPath: './../icons/file.svg',
},
};
expectedManifest.file = 'file';
expectedManifest.fileExtensions = {
js: 'javascript',
};
expectedManifest.fileNames = {
'.angular-cli.json': 'angular',
'angular-cli.json': 'angular',
'filename.js': 'javascript',
};
expect(iconDefinitions).toStrictEqual(expectedManifest);
});
it('should disable icon packs', () => {
const fileIcons: FileIcons = {
defaultIcon: { name: 'file' },
icons: [
{
name: 'angular',
fileNames: ['.angular-cli.json', 'angular-cli.json'],
enabledFor: [IconPack.Ngrx],
},
{
name: 'javascript',
fileNames: ['filename.js'],
fileExtensions: ['js'],
},
],
};
const manifest = createEmptyManifest();
config.activeIconPack = '';
const iconDefinitions = loadFileIconDefinitions(
fileIcons,
config,
manifest
);
expectedManifest.iconDefinitions = {
file: {
iconPath: './../icons/file.svg',
},
javascript: {
iconPath: './../icons/javascript.svg',
},
};
expectedManifest.file = 'file';
expectedManifest.fileExtensions = {
js: 'javascript',
};
expectedManifest.fileNames = {
'filename.js': 'javascript',
};
expect(iconDefinitions).toStrictEqual(expectedManifest);
});
it('should configure custom icon associations', () => {
const fileIcons: FileIcons = {
defaultIcon: { name: 'file' },
icons: [
{
name: 'angular',
fileNames: ['.angular-cli.json', 'angular-cli.json'],
},
{
name: 'javascript',
fileNames: ['filename.js'],
fileExtensions: ['js'],
},
],
};
const config = getDefaultConfig();
config.files.associations = {
'*.sample.ts': 'angular',
'sample.js': 'javascript',
};
const manifest = createEmptyManifest();
const iconDefinitions = loadFileIconDefinitions(
fileIcons,
config,
manifest
);
expectedManifest.iconDefinitions = {
file: {
iconPath: './../icons/file.svg',
},
javascript: {
iconPath: './../icons/javascript.svg',
},
angular: {
iconPath: './../icons/angular.svg',
},
};
expectedManifest.file = 'file';
expectedManifest.fileExtensions = {
js: 'javascript',
'sample.ts': 'angular',
};
expectedManifest.fileNames = {
'.angular-cli.json': 'angular',
'angular-cli.json': 'angular',
'sample.js': 'javascript',
'filename.js': 'javascript',
};
config.files.associations = {
'*.sample.ts': 'angular',
'sample.js': 'javascript',
};
expect(iconDefinitions).toStrictEqual(expectedManifest);
});
it('should configure language icons for light and high contrast', () => {
const fileIcons: FileIcons = {
defaultIcon: { name: 'file', light: true, highContrast: true },
icons: [
{
name: 'angular',
fileNames: ['.angular-cli.json', 'angular-cli.json'],
enabledFor: [IconPack.Angular, IconPack.Ngrx],
},
{
name: 'javascript',
fileNames: ['filename.js'],
fileExtensions: ['js'],
light: true,
highContrast: true,
},
],
};
const manifest = createEmptyManifest();
const iconDefinitions = loadFileIconDefinitions(
fileIcons,
config,
manifest
);
expectedManifest.iconDefinitions = {
file: {
iconPath: './../icons/file.svg',
},
// biome-ignore lint/style/useNamingConvention:
file_light: {
iconPath: './../icons/file_light.svg',
},
// biome-ignore lint/style/useNamingConvention:
file_highContrast: {
iconPath: './../icons/file_highContrast.svg',
},
javascript: {
iconPath: './../icons/javascript.svg',
},
// biome-ignore lint/style/useNamingConvention:
javascript_light: {
iconPath: './../icons/javascript_light.svg',
},
// biome-ignore lint/style/useNamingConvention:
javascript_highContrast: {
iconPath: './../icons/javascript_highContrast.svg',
},
angular: {
iconPath: './../icons/angular.svg',
},
};
expectedManifest.file = 'file';
expectedManifest.fileExtensions = {
js: 'javascript',
};
expectedManifest.light = {
file: 'file_light',
fileExtensions: {
js: 'javascript_light',
},
fileNames: {
'filename.js': 'javascript_light',
},
};
expectedManifest.highContrast = {
file: 'file_highContrast',
fileExtensions: {
js: 'javascript_highContrast',
},
fileNames: {
'filename.js': 'javascript_highContrast',
},
};
expectedManifest.fileNames = {
'.angular-cli.json': 'angular',
'angular-cli.json': 'angular',
'filename.js': 'javascript',
};
expect(iconDefinitions).toStrictEqual(expectedManifest);
});
it('should generate cloned file icons config', () => {
const fileIcons: FileIcons = {
defaultIcon: { name: 'file' },
icons: [
{
name: 'foo',
fileNames: ['foo.bar'],
},
{
name: 'foo-clone',
fileNames: ['bar.foo'],
fileExtensions: ['baz'],
light: true,
clone: {
base: 'foo',
color: 'green-500',
lightColor: 'green-100',
},
},
],
};
const manifest = createEmptyManifest();
const iconDefinitions = loadFileIconDefinitions(
fileIcons,
config,
manifest
);
expectedManifest.iconDefinitions = {
foo: {
iconPath: './../icons/foo.svg',
},
'foo-clone': {
iconPath: './../icons/foo-clone.clone.svg',
},
'foo-clone_light': {
iconPath: './../icons/foo-clone_light.clone.svg',
},
file: {
iconPath: './../icons/file.svg',
},
};
expectedManifest.light = {
fileExtensions: {
baz: 'foo-clone_light',
},
fileNames: {
'bar.foo': 'foo-clone_light',
},
};
expectedManifest.fileNames = {
'foo.bar': 'foo',
'bar.foo': 'foo-clone',
};
expectedManifest.fileExtensions = {
baz: 'foo-clone',
};
expectedManifest.file = 'file';
expect(iconDefinitions).toStrictEqual(expectedManifest);
});
it('should allow interoperability between cloned and user custom associations', () => {
const fileIcons: FileIcons = {
defaultIcon: { name: 'file' },
icons: [
{
name: 'foo',
fileExtensions: ['foo'],
},
{
name: 'bar',
fileExtensions: ['bar'],
clone: {
base: 'foo',
color: 'green-500',
lightColor: 'green-100',
},
},
],
};
config.files.associations = {
'*.baz': 'bar', // assigned to the clone
};
const manifest = createEmptyManifest();
const iconDefinitions = loadFileIconDefinitions(
fileIcons,
config,
manifest
);
expectedManifest.iconDefinitions = {
foo: {
iconPath: './../icons/foo.svg',
},
bar: {
iconPath: './../icons/bar.clone.svg',
},
file: {
iconPath: './../icons/file.svg',
},
};
expectedManifest.fileNames = {};
expectedManifest.fileExtensions = {
foo: 'foo',
bar: 'bar',
baz: 'bar',
};
expectedManifest.file = 'file';
expect(iconDefinitions).toStrictEqual(expectedManifest);
});
});
``` | /content/code_sandbox/src/core/tests/icons/fileIcons.test.ts | xml | 2016-09-09T20:41:42 | 2024-08-16T07:38:46 | vscode-material-icon-theme | material-extensions/vscode-material-icon-theme | 2,007 | 2,049 |
```xml
import cn from "classnames";
import React, { FunctionComponent, HTMLAttributes } from "react";
import { withStyles } from "coral-ui/hocs";
import styles from "./Navigation.css";
interface Props extends HTMLAttributes<any> {
className?: string;
classes: typeof styles;
children?: React.ReactNode;
}
const Navigation: FunctionComponent<Props> = ({
children,
className,
classes,
...rest
}) => (
<nav {...rest} className={cn(classes.root, className)}>
<ul className={classes.ul}>{children}</ul>
</nav>
);
export default withStyles(styles)(Navigation);
``` | /content/code_sandbox/client/src/core/client/ui/components/v2/SubBar/Navigation.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 129 |
```xml
<manifest xmlns:android="path_to_url"
package="com.vincent.filepicker">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:supportsRtl="true">
<activity
android:name=".activity.ImagePickActivity"
android:screenOrientation="portrait"
android:theme="@style/vw_FilePickerTheme" />
<activity android:name=".activity.ImageBrowserActivity"
android:screenOrientation="portrait"
android:theme="@style/vw_FilePickerTheme"
android:hardwareAccelerated="false" />
<activity android:name=".activity.VideoPickActivity"
android:screenOrientation="portrait"
android:theme="@style/vw_FilePickerTheme" />
<activity android:name=".activity.AudioPickActivity"
android:screenOrientation="portrait"
android:theme="@style/vw_FilePickerTheme" />
<activity android:name=".activity.NormalFilePickActivity"
android:screenOrientation="portrait"
android:theme="@style/vw_FilePickerTheme" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
``` | /content/code_sandbox/filepicker/src/main/AndroidManifest.xml | xml | 2016-10-26T08:46:20 | 2024-08-02T07:35:09 | MultiType-FilePicker | fishwjy/MultiType-FilePicker | 1,398 | 326 |
```xml
<vector xmlns:android="path_to_url" android:height="34.0dp" android:tint="?attr/colorControlNormal" android:viewportHeight="15" android:viewportWidth="15" android:width="34.0dp">
<path android:fillColor="@android:color/white" android:pathData="M12 0C13 0 13 0 13 1L13 14C13 15 13 15 12 15L3 15C2 15 2 15 2 14L2 1C2 0 2 0 3 0L12 0zM10 12L4 12L4 13L10 13L10 12zM12 9L11 9L11 9.75L12 9.75L12 9zM10 2L4 2L4 10L10 10L10 2zM12 7.5L11 7.5L11 8.25L12 8.25L12 7.5zM12 6L11 6L11 6.75L12 6.75L12 6zM12 4.5L11 4.5L11 5.25L12 5.25L12 4.5z"/>
<path android:fillColor="@android:color/white" android:pathData="M7 2.5C8.25 2.5 9.25 3.5 9.25 4.75C9.25 6 8.5 6.75 7.5 7L7.5 8C7.5 8 8.5 8 8.5 8C8.75 8 8.75 8.75 8.5 8.75C8.5 8.75 7.5 8.75 7.5 8.75L7.5 9.5C7.5 9.75 6.5 9.75 6.5 9.5L6.5 8.75C6.5 8.75 5.5 8.75 5.5 8.75C5.25 8.75 5.25 8 5.5 8C5.5 8 6.5 8 6.5 8L6.5 7C5.5 6.75 4.75 5.75 4.75 4.75C4.75 3.5 5.75 2.5 7 2.5zM7 3.25L7 3.25C6.25 3.25 5.5 4 5.5 4.75C5.5 5.5 6.25 6.25 7 6.25C7.75 6.25 8.5 5.5 8.5 4.75C8.5 4 7.75 3.25 7 3.25z"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_preset_temaki_vending_venus.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 684 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/// <reference types="@stdlib/types"/>
import { Collection } from '@stdlib/types/array';
/**
* Returns an accessed value.
*
* @returns accessed value
*/
type Nullary<V> = ( this: V ) => number | void;
/**
* Returns an accessed value.
*
* @param value - array element
* @returns accessed value
*/
type Unary<T, V> = ( this: V, value: T ) => number | void;
/**
* Returns an accessed value.
*
* @param value - array element
* @param idx - iteration index
* @returns accessed value
*/
type Binary<T, V> = ( this: V, value: T, idx: number ) => number | void;
/**
* Returns an accessed value.
*
* @param value - array element
* @param idx - iteration index
* @param xi - strided index (offsetX + idx*strideX)
* @returns accessed value
*/
type Ternary<T, V> = ( this: V, value: T, idx: number, xi: number ) => number | void;
/**
* Returns an accessed value.
*
* @param value - array element
* @param idx - iteration index
* @param xi - strided index (offsetX + idx*strideX)
* @param yi - strided index (offsetY + idx*strideY)
* @returns accessed value
*/
type Quaternary<T, V> = ( this: V, value: T, idx: number, xi: number, yi: number ) => number | void;
/**
* Returns an accessed value.
*
* @param value - array element
* @param idx - iteration index
* @param xi - strided index (offsetX + idx*strideX)
* @param yi - strided index (offsetY + idx*strideY)
* @param x - input array
* @returns accessed value
*/
type Quinary<T, V> = ( this: V, value: T, idx: number, xi: number, yi: number, x: Collection<T> ) => number | void;
/**
* Returns an accessed value.
*
* @param value - array element
* @param idx - iteration index
* @param xi - strided index (offsetX + idx*strideX)
* @param yi - strided index (offsetY + idx*strideY)
* @param x - input array
* @param y - output array
* @returns accessed value
*/
type Senary<T, U, V> = ( this: V, value: T, idx: number, xi: number, yi: number, x: Collection<T>, y: Collection<U> ) => number | void;
/**
* Returns an accessed value.
*
* @param value - array element
* @param idx - iteration index
* @param xi - strided index (offsetX + idx*strideX)
* @param yi - strided index (offsetY + idx*strideY)
* @param x - input array
* @param y - output array
* @returns accessed value
*/
type Callback<T, U, V> = Nullary<V> | Unary<T, V> | Binary<T, V> | Ternary<T, V> | Quaternary<T, V> | Quinary<T, V> | Senary<T, U, V>;
/**
* Interface describing `cbrtBy`.
*/
interface Routine {
/**
* Computes the cube root of each element retrieved from an input strided array `x` via a callback function and assigns each result to an element in an output strided array `y`.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param y - destination array
* @param strideY - `y` stride length
* @param clbk - callback function
* @param thisArg - callback execution context
* @returns `y`
*
* @example
* function accessor( v ) {
* return v;
* }
*
* var x = [ 1.0, 9.0, -27.0, 81.0, -125.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* cbrtBy( x.length, x, 1, y, 1, accessor );
* // y => [ 1.0, ~2.08, -3.0, ~4.327, -5.0 ]
*/
<T = unknown, U = unknown, V = unknown>( N: number, x: Collection<T>, strideX: number, y: Collection<U>, strideY: number, clbk: Callback<T, U, V>, thisArg?: ThisParameterType<Callback<T, U, V>> ): Collection<U | number>;
/**
* Computes the cube root of each element retrieved from an input strided array `x` via a callback function and assigns each result to an element in an output strided array `y` using alternative indexing semantics.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param offsetX - starting index for `x`
* @param y - destination array
* @param strideY - `y` stride length
* @param offsetY - starting index for `y`
* @param clbk - callback function
* @param thisArg - callback execution context
* @returns `y`
*
* @example
* function accessor( v ) {
* return v;
* }
*
* var x = [ 1.0, 9.0, -27.0, 81.0, -125.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* cbrtBy.ndarray( x.length, x, 1, 0, y, 1, 0, accessor );
* // y => [ 1.0, ~2.08, -3.0, ~4.327, -5.0 ]
*/
ndarray<T = unknown, U = unknown, V = unknown>( N: number, x: Collection<T>, strideX: number, offsetX: number, y: Collection<U>, strideY: number, offsetY: number, clbk: Callback<T, U, V>, thisArg?: ThisParameterType<Callback<T, U, V>> ): Collection<U | number>;
}
/**
* Computes the cube root of each element retrieved from an input strided array `x` via a callback function and assigns each result to an element in an output strided array `y`.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param y - destination array
* @param strideY - `y` stride length
* @param clbk - callback function
* @param thisArg - callback execution context
* @returns `y`
*
* @example
* function accessor( v ) {
* return v;
* }
*
* var x = [ 1.0, 9.0, -27.0, 81.0, -125.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* cbrtBy( x.length, x, 1, y, 1, accessor );
* // y => [ 1.0, ~2.08, -3.0, ~4.327, -5.0 ]
*
* @example
* function accessor( v ) {
* return v;
* }
*
* var x = [ 1.0, 9.0, -27.0, 81.0, -125.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* cbrtBy.ndarray( x.length, x, 1, 0, y, 1, 0, accessor );
* // y => [ 1.0, ~2.08, -3.0, ~4.327, -5.0 ]
*/
declare var cbrtBy: Routine;
// EXPORTS //
export = cbrtBy;
``` | /content/code_sandbox/lib/node_modules/@stdlib/math/strided/special/cbrt-by/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 1,910 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/border"
android:padding="10dp"
android:textColor="#000"
android:textSize="20sp" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@mipmap/ic_launcher" />
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/item.xml | xml | 2016-11-30T10:14:50 | 2024-08-12T19:26:20 | SwissArmyKnife | android-notes/SwissArmyKnife | 1,346 | 166 |
```xml
import {Component} from '@angular/core';
import {MatRadioModule} from '@angular/material/radio';
/**
* @title Basic radios
*/
@Component({
selector: 'radio-overview-example',
templateUrl: 'radio-overview-example.html',
styleUrl: 'radio-overview-example.css',
standalone: true,
imports: [MatRadioModule],
})
export class RadioOverviewExample {}
``` | /content/code_sandbox/src/components-examples/material/radio/radio-overview/radio-overview-example.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 83 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
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
-->
<!DOCTYPE suite SYSTEM "path_to_url" >
<suite name="testerina-intg-test-suite">
<!-- ballerina.test Related Test Cases. -->
<test name="testerina-intg-tests">
<parameter name="enableTesterinaTests" value="true" />
<groups>
<run>
<exclude name="brokenOnJBallerina"/>
</run>
</groups>
<classes>
<class name="org.ballerinalang.testerina.test.BasicCasesTest" />
<class name="org.ballerinalang.testerina.test.negative.MissingFunctionsTestCase"/>
<class name="org.ballerinalang.testerina.test.negative.InvalidFunctionMockingTestCase"/>
<class name="org.ballerinalang.testerina.test.GroupingTest" />
<class name="org.ballerinalang.testerina.test.SelectedFunctionTest" />
<class name="org.ballerinalang.testerina.test.negative.SkipTestsTestCase" />
<class name="org.ballerinalang.testerina.test.negative.InvalidDataProviderTestCase" />
<class name="org.ballerinalang.testerina.test.negative.UnusedVarWithErrorTestCase" />
<class name="org.ballerinalang.testerina.test.negative.InvalidTestDefinitionsTestCase" />
<class name="org.ballerinalang.testerina.test.DisableTestsTestCase" />
<class name="org.ballerinalang.testerina.test.MockTest" />
<class name="org.ballerinalang.testerina.test.TestReportTest" />
<class name="org.ballerinalang.testerina.test.PathVerificationTest" />
<class name="org.ballerinalang.testerina.test.RerunFailedTest"/>
<class name="org.ballerinalang.testerina.test.FunctionNameValidationTest" />
<class name="org.ballerinalang.testerina.test.ImportTest" />
<class name="org.ballerinalang.testerina.test.ModuleExecutionTest" />
<class name="org.ballerinalang.testerina.test.ModuleExecutionFlowTest" />
<class name="org.ballerinalang.testerina.test.ModuleGracefulStopTest" />
<class name="org.ballerinalang.testerina.test.ModuleExecutionWithInitStartFailuresTest" />
<class name="org.ballerinalang.testerina.test.CodeCoverageReportTest" />
<class name="org.ballerinalang.testerina.test.SourcelessTestExecutionTests"/>
<class name="org.ballerinalang.testerina.test.DataProviderTest"/>
<class name="org.ballerinalang.testerina.test.CodegenCodeCoverageTest"/>
<class name="org.ballerinalang.testerina.test.ExcludeFromCodeCoverageTest"/>
<class name="org.ballerinalang.testerina.test.ConfigurableCliArgsTest"/>
<class name="org.ballerinalang.testerina.test.negative.InvalidConfigurableCliArgsTestCase"/>
<class name="org.ballerinalang.testerina.test.TestparallelizationTest"/>
<class name="org.ballerinalang.testerina.test.SingleTestExecutionWithInitFailuresTest"/>
<class name="org.ballerinalang.testerina.test.TestExecutionWithInitFailuresTest"/>
<class name="org.ballerinalang.testerina.test.EscapedIdentifiersValidationTest"/>
</classes>
</test>
</suite>
``` | /content/code_sandbox/tests/testerina-integration-test/src/test/resources/testng.xml | xml | 2016-11-16T14:58:44 | 2024-08-15T15:15:21 | ballerina-lang | ballerina-platform/ballerina-lang | 3,561 | 786 |
```xml
import {
exists,
isArray,
isNode,
isNullOrUndefined,
isObject,
isObjectAndNotArrayNotNode,
} from './common-utils';
import { DeepPartial } from '../models';
export function deepMerge<T>(
target: DeepPartial<T> | T,
source: DeepPartial<T> | T,
): DeepPartial<T> | T {
if (isObjectAndNotArrayNotNode(target) && isObjectAndNotArrayNotNode(source)) {
return deepMergeRecursively(target, source);
} else if (isNullOrUndefined(target) && isNullOrUndefined(source)) {
return {} as T;
} else {
return exists(source) ? (source as T) : target;
}
}
function deepMergeRecursively<T>(
target: DeepPartial<T> | T,
source: DeepPartial<T> | T,
): DeepPartial<T> | T {
const shouldNotRecurse =
isNullOrUndefined(target) ||
isNullOrUndefined(source) || // at least one not defined
isArray(target) ||
isArray(source) || // at least one array
!isObject(target) ||
!isObject(source) || // at least one not an object
isNode(target) ||
isNode(source); // at least one node
/**
* if we will not recurse any further,
* we will prioritize source if it is a defined value.
*/
if (shouldNotRecurse) {
return exists(source) ? (source as T) : target;
}
const keysOfTarget = Object.keys(target as { [key: string]: any });
const keysOfSource = Object.keys(source as { [key: string]: any });
const uniqueKeys = new Set(keysOfTarget.concat(keysOfSource));
return [...uniqueKeys].reduce((retVal, key) => {
(retVal as any)[key] = deepMergeRecursively(
(target as { [key: string]: any })[key],
(source as { [key: string]: any })[key],
);
return retVal;
}, {} as T);
}
``` | /content/code_sandbox/npm/ng-packs/packages/core/src/lib/utils/object-utils.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 450 |
```xml
export interface BeforeInit {
$beforeInit(): void | Promise<any>;
}
``` | /content/code_sandbox/packages/platform/common/src/interfaces/BeforeInit.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 17 |
```xml
export interface CacheEntry<T> {
status: number;
value: T;
}
export interface Filter {
[key: string]: number;
}
export interface Sort {
sort: 'Time' | 'Size' | 'SnoozeTime';
desc: boolean;
}
export interface SearchParameters {
address?: string;
from?: string;
to?: string;
keyword?: string;
begin?: number;
end?: number;
wildcard?: number;
}
``` | /content/code_sandbox/applications/mail/src/app/models/tools.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 100 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.oushangfeng.pinneddemo.StockActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.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"/>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_stock"/>
</android.support.design.widget.CoordinatorLayout>
``` | /content/code_sandbox/app/src/main/res/layout/activity_stock.xml | xml | 2016-07-22T19:30:16 | 2024-08-15T11:03:14 | PinnedSectionItemDecoration | oubowu/PinnedSectionItemDecoration | 2,083 | 223 |
```xml
import { TestBed } from '@angular/core/testing';
import { Component } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { bubble } from '../../../../../../src/app/data';
import { APP_BASE_HREF } from '@angular/common';
import { BubbleChartModule } from './bubble-chart.module';
jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
@Component({
selector: 'test-component',
template: ''
})
class TestComponent {
results: any[] = bubble;
colorScheme = {
domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
};
}
describe('<ngx-charts-bubble-chart>', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [NoopAnimationsModule, BubbleChartModule],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }]
});
});
describe('basic setup', () => {
beforeEach(() => {
TestBed.overrideComponent(TestComponent, {
set: {
template: `
<ngx-charts-bubble-chart
[animations]="false"
[view]="[400,800]"
[scheme]="colorScheme"
[results]="results">
</ngx-charts-bubble-chart>`
}
}).compileComponents();
});
it('should set the svg width and height', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const svg = fixture.debugElement.nativeElement.querySelector('svg');
expect(svg.getAttribute('width')).toBe('400');
expect(svg.getAttribute('height')).toBe('800');
});
it('should render 12 circle elements', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const circleElements = fixture.debugElement.nativeElement.querySelectorAll('g.circle');
expect(circleElements.length).toEqual(12);
});
});
});
``` | /content/code_sandbox/projects/swimlane/ngx-charts/src/lib/bubble-chart/bubble-chart.component.spec.ts | xml | 2016-07-22T15:58:41 | 2024-08-02T15:56:24 | ngx-charts | swimlane/ngx-charts | 4,284 | 399 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="path_to_url">
<item
android:title="@string/menu_1"
android:icon="@drawable/ic_apps_black_24dp" />
<item
android:title="@string/menu_2"
android:icon="@drawable/ic_maps_local_bar" />
<item
android:title="@string/menu_3"
android:icon="@drawable/ic_maps_local_restaurant" />
<item
android:title="@string/menu_4"
android:icon="@drawable/ic_maps_local_bar" />
<item
android:title="@string/menu_5"
android:icon="@drawable/ic_maps_place" />
</menu>
``` | /content/code_sandbox/demo/src/main/res/menu/bottom_navigation_menu_5.xml | xml | 2016-03-17T12:17:56 | 2024-08-16T05:12:20 | ahbottomnavigation | aurelhubert/ahbottomnavigation | 3,836 | 155 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import FLOAT64_NINF = require( './index' );
// TESTS //
// The export is a number...
{
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
FLOAT64_NINF; // $ExpectType number
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/constants/float64/ninf/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 101 |
```xml
export * from './element.js';
export * from './event.js';
export * from './event-target.js';
export * from './hydrate.js';
export * from './node.js';
export * from './options.js';
export * from './utils.js';
``` | /content/code_sandbox/packages/miniapp-runtime/src/interface/index.ts | xml | 2016-11-03T06:59:15 | 2024-08-16T10:11:29 | ice | alibaba/ice | 17,815 | 51 |
```xml
import {test, expect} from 'vitest';
import toLines from './index.js';
test('should return an array for empty input', () => {
expect((toLines as () => string[])()).toStrictEqual([]);
});
test('should return an array for null input', () => {
expect((toLines as (input: any) => string[])(null)).toStrictEqual([]);
});
test('should return an array for empty string input', () => {
expect(toLines('')).toStrictEqual(['']);
});
test('should split LF newlines', () => {
expect(toLines('some\nweird\ntext')).toStrictEqual(['some', 'weird', 'text']);
});
test('should split CR+LF newlines', () => {
expect(toLines('some\r\nweird\r\ntext')).toStrictEqual([
'some',
'weird',
'text',
]);
});
``` | /content/code_sandbox/@commitlint/to-lines/src/index.test.ts | xml | 2016-02-12T08:37:56 | 2024-08-16T13:28:33 | commitlint | conventional-changelog/commitlint | 16,499 | 189 |
```xml
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<command>
<update>
<domain:update
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>example.tld</domain:name>
<domain:add>
<domain:ns>
<domain:hostObj>ns2.example.foo</domain:hostObj>
</domain:ns>
</domain:add>
<domain:rem/>
<domain:chg/>
</domain:update>
</update>
<extension>
<metadata:metadata xmlns:metadata="urn:google:params:xml:ns:metadata-1.0">
<metadata:reason>domain-update-test</metadata:reason>
<metadata:requestedByRegistrar>true</metadata:requestedByRegistrar>
</metadata:metadata>
</extension>
<clTRID>ABC-12345</clTRID>
</command>
</epp>
``` | /content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_update_metadata.xml | xml | 2016-02-29T20:16:48 | 2024-08-15T19:49:29 | nomulus | google/nomulus | 1,685 | 214 |
```xml
// path_to_url
import { XmlComponent } from "@file/xml-components";
// <xsd:group name="EG_RunInnerContent">
// ...
// <xsd:element name="br" type="CT_Br"/>
// <xsd:complexType name="CT_Br">
// <xsd:attribute name="type" type="ST_BrType" use="optional"/>
// <xsd:attribute name="clear" type="ST_BrClear" use="optional"/>
// </xsd:complexType>
// <xsd:simpleType name="ST_BrType">
// <xsd:restriction base="xsd:string">
// <xsd:enumeration value="page"/>
// <xsd:enumeration value="column"/>
// <xsd:enumeration value="textWrapping"/>
// </xsd:restriction>
// </xsd:simpleType>
// <xsd:simpleType name="ST_BrClear">
// <xsd:restriction base="xsd:string">
// <xsd:enumeration value="none"/>
// <xsd:enumeration value="left"/>
// <xsd:enumeration value="right"/>
// <xsd:enumeration value="all"/>
// </xsd:restriction>
// </xsd:simpleType>
export class Break extends XmlComponent {
public constructor() {
super("w:br");
}
}
``` | /content/code_sandbox/src/file/paragraph/run/break.ts | xml | 2016-03-26T23:43:56 | 2024-08-16T13:02:47 | docx | dolanmiu/docx | 4,139 | 280 |
```xml
import { GameObject } from '../serialize/GameObject.js';
import { PhysicsEngine, PhysicsEngineOptions } from './PhysicsEngine.js';
import P2, { BodyOptions, CircleOptions } from 'p2';
interface P2PhysicsEngineOptions extends PhysicsEngineOptions {
dt?: number
}
/**
* P2PhysicsEngine is a three-dimensional lightweight physics engine
*/
class P2PhysicsEngine extends PhysicsEngine {
private p2PhysicsEngineOptions: P2PhysicsEngineOptions;
constructor(options: P2PhysicsEngineOptions) {
super(options);
this.p2PhysicsEngineOptions = options;
this.p2PhysicsEngineOptions.dt = this.p2PhysicsEngineOptions.dt || (1 / 60);
this.world = new P2.World({ gravity: [0, 0] });
}
// entry point for a single step of the P2 Physics
step(dt: number, objectFilter: (o: GameObject) => boolean): void {
this.world.step(dt || this.p2PhysicsEngineOptions.dt);
}
// add a circle
addCircle(circleOptions: CircleOptions, bodyOptions: BodyOptions): P2.Body {
// create a body, add shape, add to world
let body = new P2.Body(bodyOptions);
body.addShape(new P2.Circle(circleOptions));
this.world.addBody(body);
return body;
}
addBox(width: number, height: number, mass: number) {
// create a body, add shape, add to world
let body = new P2.Body({ mass, position: [0, 0] });
body.addShape(new P2.Box({ width, height }));
this.world.addBody(body);
return body;
}
removeObject(obj: P2.Body) {
this.world.removeBody(obj);
}
}
export { P2PhysicsEngine, P2PhysicsEngineOptions }
``` | /content/code_sandbox/src/physics/P2PhysicsEngine.ts | xml | 2016-06-10T12:58:57 | 2024-08-15T07:16:18 | lance | lance-gg/lance | 1,570 | 395 |
```xml
import type { BaseAnnotations } from 'storybook/internal/types';
import { type ReactRenderer, type StoryContext } from './public-types';
export const mount: BaseAnnotations<ReactRenderer>['mount'] =
(context: StoryContext) => async (ui) => {
if (ui != null) {
context.originalStoryFn = () => ui;
}
await context.renderToCanvas();
return context.canvas;
};
``` | /content/code_sandbox/code/renderers/react/src/mount.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 90 |
```xml
// The Apollo Client source that is published to npm is prepared via
// config/prepareDist.js.
//
// If a release is being manually published, npm run build (which in turn runs
// prepareDist.js via postbuild script) performs all of the necessary processing
// to prepare the release. However, if a release is being automatically
// published via Changesets, there are some additional required
// steps:
//
// - Copy the .changeset folder into "dist" so Changesets can pick up the
// markdown changesets when generating the release.
// - Copy CHANGELOG.md into "dist" so Changesets can use it to generate release
// notes.
// - Add both .changeset and CHANGELOG.md to an .npmignore so they are not
// included in the published package.
const fs = require("fs");
const path = require("path");
const distRoot = `${__dirname}/../dist`;
const srcDir = `${__dirname}/..`;
const destDir = `${srcDir}/dist`;
// recursive copy function
function copyDir(src: string, dest: string) {
fs.mkdirSync(dest, { recursive: true });
let entries = fs.readdirSync(src, { withFileTypes: true });
for (let entry of entries) {
let srcPath = path.join(src, entry.name);
let destPath = path.join(dest, entry.name);
entry.isDirectory() ?
copyDir(srcPath, destPath)
: fs.copyFileSync(srcPath, destPath);
}
}
fs.copyFileSync(`${srcDir}/CHANGELOG.md`, `${destDir}/CHANGELOG.md`);
copyDir(`${srcDir}/.changeset`, `${destDir}/.changeset`);
fs.writeFileSync(`${destDir}/.npmignore`, `.changeset\nCHANGELOG.md`);
``` | /content/code_sandbox/config/prepareChangesetsRelease.ts | xml | 2016-02-26T20:25:00 | 2024-08-16T10:56:57 | apollo-client | apollographql/apollo-client | 19,304 | 376 |
```xml
import { ICommandBarStyleProps, ICommandBarStyles } from '@fluentui/react/lib/CommandBar';
import * as StyleConstants from '../Constants';
import { IExtendedSemanticColors } from '../IExtendedSemanticColors';
export const CommandBarStyles = (props: ICommandBarStyleProps): Partial<ICommandBarStyles> => {
const { theme } = props;
const { semanticColors } = theme;
const extendedSemanticColors = semanticColors as IExtendedSemanticColors;
return {
root: [
{
backgroundColor: semanticColors.bodyBackground,
height: '36px',
borderBottomWidth: StyleConstants.borderWidth,
borderBottomStyle: StyleConstants.borderSolid,
borderBottomColor: extendedSemanticColors.commandBarBorder,
padding: 0,
},
],
};
};
``` | /content/code_sandbox/packages/azure-themes/src/azure/styles/CommandBar.styles.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 164 |
```xml
import { Flex, Heading } from "@chakra-ui/react";
export const Hero = ({ title }: { title: string }) => (
<Flex
justifyContent="center"
alignItems="center"
height="100vh"
bgGradient="linear(to-l, heroGradientStart, heroGradientEnd)"
bgClip="text"
>
<Heading fontSize="6vw">{title}</Heading>
</Flex>
);
Hero.defaultProps = {
title: "with-chakra-ui-typescript",
};
``` | /content/code_sandbox/examples/with-chakra-ui/src/components/Hero.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.