text
stringlengths 27
775k
|
---|
#nullable enable
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Shared.Roles
{
/// <summary>
/// Describes information for a single antag.
/// </summary>
[Prototype("antag")]
public class AntagPrototype : IPrototype
{
[ViewVariables]
[DataField("id", required: true)]
public string ID { get; } = default!;
/// <summary>
/// The name of this antag as displayed to players.
/// </summary>
[DataField("name")]
public string Name { get; } = string.Empty;
/// <summary>
/// The antag's objective, displayed at round-start to the player.
/// </summary>
[DataField("objective")]
public string Objective { get; private set; } = string.Empty;
/// <summary>
/// Whether or not the antag role is one of the bad guys.
/// </summary>
[DataField("antagonist")]
public bool Antagonist { get; private set; }
/// <summary>
/// Whether or not the player can set the antag role in antag preferences.
/// </summary>
[DataField("setPreference")]
public bool SetPreference { get; private set; }
}
}
|
#! /usr/bin/env bats
#
# This file provides negative test cases for when the user does not execute
# upgrade steps in the correct order after starting the hub.
load helpers
setup() {
STATE_DIR=`mktemp -d`
export GPUPGRADE_HOME="${STATE_DIR}/gpupgrade"
gpupgrade prepare init --old-bindir /dummy --new-bindir /dummy
kill_hub
gpupgrade prepare start-hub
}
teardown() {
kill_hub
rm -r "${STATE_DIR}"
}
@test "seginstall requires segments to have been loaded into the configuration" {
gpupgrade check seginstall
run gpupgrade status upgrade
[[ "$output" = *"FAILED - Install binaries on segments"* ]]
}
@test "start-agents requires segments to have been loaded into the configuration" {
gpupgrade prepare start-agents
run gpupgrade status upgrade
[[ "$output" = *"FAILED - Agents Started on Cluster"* ]]
}
|
<?php
namespace App\Deposito;
use App\Deposito\Empregado;
use Illuminate\Database\Eloquent\Model;
class Setor extends Model
{
// Referência à tabela 'sectors'.
protected $table = 'sectors';
// Define 'name' como chave primária.
protected $primaryKey = 'name';
// Determina que a chave primária não é incremental.
public $incrementing = false;
// Determina o tipo da chave primária como string.
protected $keyType = 'string';
// Determina que não há timestamps.
public $timestamps = false;
// Lista de colunas liberadas para mass assignment.
protected $fillable = ['name', 'boss'];
// Oculta a relação empregados.
protected $hidden = ['name'];
//Lista todos os empregados que trabalham no setor.
public function empregados() {
return $this->belongsToMany('Empregado', 'employer_sector', 'sector_name', 'employer_register');
}
// Alocar empregado para o setor.
public static function alocar_empregado($setor, $empregado) {
// Procura o setor.
$setor = static::find($setor);
// Relaciona o empregado com o setor.
$setor->empregados()->attach($empregado);
}
// Desalocar empregado do setor.
public static function desalocar_empregado($setor, $empregado) {
// Procura o empregado.
$setor = static::find($setor);
//Procura o empregado.
$setor->empregados()->detach($empregado);
}
}
|
import {NavigationContainer} from '@react-navigation/native';
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/lib/integration/react';
import App from 'src/App';
import {persistor, store} from 'src/store';
import NavigationService, {navigationRef} from './lib/NavigationService';
import './i18n';
import {enableScreens} from 'react-native-screens';
/**
* Optimize memory usage and performance: https://reactnavigation.org/docs/react-native-screens/
*/
enableScreens();
export default function Root() {
useEffect(() => {
NavigationService.isReady = false;
}, []);
return (
<Provider store={store}>
<PersistGate loading={<View />} persistor={persistor}>
<NavigationContainer
ref={navigationRef}
onReady={() => {
NavigationService.isReady = true;
}}>
<App />
</NavigationContainer>
</PersistGate>
</Provider>
);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Arcus.Templates.AzureFunctions.Http.Model;
using Arcus.Templates.Tests.Integration.Fixture;
using Bogus;
using Xunit;
using Xunit.Abstractions;
namespace Arcus.Templates.Tests.Integration.AzureFunctions.Http.Api
{
[Collection(TestCollections.Integration)]
[Trait("Category", TestTraits.Integration)]
public class HttpTriggerOrderTests
{
private readonly TestConfig _config;
private readonly ITestOutputHelper _outputWriter;
private static readonly Faker BogusGenerator = new Faker();
/// <summary>
/// Initializes a new instance of the <see cref="HttpTriggerOrderTests"/> class.
/// </summary>
public HttpTriggerOrderTests(ITestOutputHelper outputWriter)
{
_outputWriter = outputWriter;
_config = TestConfig.Create();
}
[Fact]
public async Task AzureFunctionsHttpProject_WithoutOptions_ResponseToCorrectOrder()
{
// Arrange
var order = new Order
{
Id = Guid.NewGuid().ToString(),
ArticleNumber = BogusGenerator.Random.String(1, 100),
Scheduled = BogusGenerator.Date.RecentOffset()
};
using (var project = await AzureFunctionsHttpProject.StartNewAsync(_config, _outputWriter))
{
// Act
using (HttpResponseMessage response = await project.Order.PostAsync(order))
{
// Assert
string responseContent = await response.Content.ReadAsStringAsync();
Assert.True(HttpStatusCode.OK == response.StatusCode, responseContent);
Assert.NotNull(JsonSerializer.Deserialize<Order>(responseContent));
IEnumerable<string> responseHeaderNames = response.Headers.Select(header => header.Key).ToArray();
Assert.Contains("X-Transaction-ID", responseHeaderNames);
Assert.Contains("RequestId", responseHeaderNames);
}
}
}
}
}
|
cask 'hackhands' do
version '1.4.11'
sha256 '638d4726d721592b4147403402b4b51bcdc848621f83d665320c03d44457c616'
# desktop.hackhands.com.s3-website-us-west-1.amazonaws.com was verified as official when first introduced to the cask
url "http://desktop.hackhands.com.s3-website-us-west-1.amazonaws.com/osx/#{version}/HackHands.zip"
name 'HackHands'
homepage 'https://hackhands.com/desktop/'
app 'HackHands.app'
end
|
// @flow
import * as React from "react";
import styled, { css } from "styled-components";
import { ModalContext } from "./ModalContext";
import { MobileHeader, StyledModalHeader, ModalHeading } from "./ModalHeader";
import { StyledModalFooter } from "./ModalFooter";
import { StyledModalSection } from "./ModalSection";
import ModalCloseButton from "./ModalCloseButton";
import { SIZES, CLOSE_BUTTON_DATA_TEST } from "./consts";
import KEY_CODE_MAP from "../common/keyMaps";
import defaultTheme from "../defaultTheme";
import { StyledButtonPrimitive } from "../primitives/ButtonPrimitive";
import media, { getBreakpointWidth } from "../utils/mediaQuery";
import { QUERIES } from "../utils/mediaQuery/consts";
import { right } from "../utils/rtl";
import transition from "../utils/transition";
import randomID from "../utils/randomID";
import onlyIE from "../utils/onlyIE";
import useMediaQuery from "../hooks/useMediaQuery";
import FOCUSABLE_ELEMENT_SELECTORS from "../hooks/useFocusTrap/consts";
import usePrevious from "../hooks/usePrevious";
import type { Instance, Props } from "./index";
const getSizeToken = () => ({ size, theme }) => {
const tokens = {
[SIZES.EXTRASMALL]: "360px",
[SIZES.SMALL]: theme.orbit.widthModalSmall,
[SIZES.NORMAL]: theme.orbit.widthModalNormal,
[SIZES.LARGE]: theme.orbit.widthModalLarge,
[SIZES.EXTRALARGE]: theme.orbit.widthModalExtraLarge,
};
return tokens[size];
};
const ModalBody = styled.div`
width: 100%;
height: 100%;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: ${({ theme }) => theme.orbit.zIndexModalOverlay};
box-sizing: border-box;
outline: none;
overflow-x: hidden;
background-color: rgba(0, 0, 0, 0.5);
font-family: ${({ theme }) => theme.orbit.fontfamily};
-webkit-overflow-scrolling: auto;
${media.largeMobile(css`
overflow-y: auto;
padding: ${({ theme }) => theme.orbit.spaceXXLarge};
`)};
${onlyIE(css`
position: -ms-page;
`)};
`;
ModalBody.defaultProps = {
theme: defaultTheme,
};
const ModalWrapper = styled.div`
box-sizing: border-box;
min-height: 100%;
display: flex;
align-items: flex-start;
margin: 0 auto;
position: fixed;
width: 100%;
border-top-left-radius: ${({ isMobileFullPage }) =>
!isMobileFullPage && "12px"}; // TODO: create token
border-top-right-radius: ${({ isMobileFullPage }) =>
!isMobileFullPage && "12px"}; // TODO: create token
transition: ${transition(["top"], "normal", "ease-in-out")};
top: ${({ loaded, isMobileFullPage }) => (loaded ? !isMobileFullPage && "32px" : "100%")};
${onlyIE(css`
/* IE flex bug, the content won't be centered if there is not 'height' property
https://github.com/philipwalton/flexbugs/issues/231 */
height: 1px;
`)};
${media.largeMobile(css`
position: relative;
top: 0;
max-width: ${getSizeToken};
align-items: center;
`)};
`;
ModalWrapper.defaultProps = {
theme: defaultTheme,
};
const CloseContainer = styled.div`
display: flex;
// -ms-page needs to set up for IE on max largeMobile
${({ scrolled, fixedClose, theme }) =>
fixedClose || scrolled
? css`
position: fixed;
${onlyIE(
css`
position: -ms-page;
`,
`(max-width:${+getBreakpointWidth(QUERIES.LARGEMOBILE, theme, true) - 1}px)`,
)};
`
: css`
position: absolute;
`};
position: ${({ scrolled, fixedClose }) => (fixedClose || scrolled ? "fixed" : "absolute")};
top: ${({ scrolled, fixedClose, isMobileFullPage }) =>
!isMobileFullPage && (fixedClose || scrolled) ? "32px" : "0"};
right: 0;
z-index: 800;
justify-content: flex-end;
align-items: center;
box-sizing: border-box;
// TODO create tokens
height: 52px;
width: 100%;
max-width: ${({ modalWidth }) => (modalWidth ? `${modalWidth}px` : getSizeToken)};
box-shadow: ${({ scrolled, theme }) => scrolled && theme.orbit.boxShadowFixed};
background-color: ${({ theme, scrolled }) => scrolled && theme.orbit.paletteWhite};
border-top-left-radius: ${({ isMobileFullPage }) =>
!isMobileFullPage && "12px"}; // TODO: create token
border-top-right-radius: ${({ isMobileFullPage }) =>
!isMobileFullPage && "12px"}; // TODO: create token
transition: ${transition(["box-shadow", "background-color"], "fast", "ease-in-out")};
pointer-events: none;
${media.largeMobile(css`
top: ${({ scrolled, fixedClose }) => (fixedClose || scrolled) && "0"};
right: ${({ scrolled, fixedClose }) => (fixedClose || scrolled) && "auto"};
border-radius: 0;
`)};
& + ${StyledModalSection}:first-of-type {
padding-top: 52px;
border-top: 0;
margin: 0;
}
${StyledButtonPrimitive} {
pointer-events: auto;
margin-${right}: ${({ theme }) => theme.orbit.spaceXXSmall};
& svg {
transition: ${transition(["color"], "fast", "ease-in-out")};
color: ${({ theme }) => theme.orbit.paletteInkLight};
}
&:hover svg {
color: ${({ theme }) => theme.orbit.paletteInkLightHover};
}
&:active svg {
color: ${({ theme }) => theme.orbit.paletteInkLightActive};
}
}
`;
CloseContainer.defaultProps = {
theme: defaultTheme,
};
const ModalWrapperContent = styled.div`
position: absolute;
box-sizing: border-box;
border-top-left-radius: ${({ isMobileFullPage }) =>
!isMobileFullPage && "12px"}; // TODO: create token
border-top-right-radius: ${({ isMobileFullPage }) =>
!isMobileFullPage && "12px"}; // TODO: create token
background-color: ${({ theme }) => theme.orbit.backgroundModal};
font-family: ${({ theme }) => theme.orbit.fontFamily};
width: 100%;
${({ theme, fixedFooter, footerHeight, isMobileFullPage }) =>
isMobileFullPage
? css`
max-height: 100%;
top: 0;
`
: css`
max-height: calc(
100% - ${theme.orbit.spaceXLarge} -
${`${fixedFooter && Boolean(footerHeight) ? footerHeight : 0}px`}
);
`};
bottom: ${({ fixedFooter, footerHeight, isMobileFullPage, theme }) =>
`${
(!isMobileFullPage ? parseInt(theme.orbit.spaceXLarge, 10) : 0) +
(fixedFooter && Boolean(footerHeight) ? footerHeight : 0)
}px`};
box-shadow: ${({ theme }) => theme.orbit.boxShadowOverlay};
overflow-y: auto;
overflow-x: hidden;
${({ fixedFooter, theme, footerHeight, fullyScrolled }) =>
fixedFooter &&
footerHeight &&
css`
${StyledModalFooter} {
bottom: 0;
padding: ${theme.orbit.spaceMedium};
box-shadow: ${fullyScrolled
? `inset 0 1px 0 ${theme.orbit.paletteCloudNormal}, ${theme.orbit.boxShadowFixedReverse}`
: `inset 0 0 0 transparent, ${theme.orbit.boxShadowFixedReverse}`};
position: fixed;
transition: ${transition(["box-shadow"], "fast", "ease-in-out")};
}
${StyledModalSection}:last-of-type {
padding-bottom: ${theme.orbit.spaceLarge};
margin-bottom: 0;
}
`};
${MobileHeader} {
top: ${({ scrolled, theme, isMobileFullPage }) =>
!isMobileFullPage && scrolled && theme.orbit.spaceXLarge};
opacity: ${({ scrolled }) => scrolled && "1"};
visibility: ${({ scrolled }) => scrolled && "visible"};
transition: ${({ scrolled }) =>
scrolled &&
css`
${transition(["top"], "normal", "ease-in-out")},
${transition(["opacity", "visibility"], "fast", "ease-in-out")}
`};
${({ scrolled }) =>
scrolled &&
onlyIE(css`
${MobileHeader} {
position: -ms-page;
}
`)}
}
${StyledModalHeader} {
margin-bottom: ${({ hasModalSection, theme }) => !hasModalSection && theme.orbit.spaceXLarge};
}
${media.largeMobile(css`
position: relative;
bottom: auto;
border-radius: ${({ isMobileFullPage }) => !isMobileFullPage && "9px"};
padding-bottom: 0;
height: auto;
overflow: visible;
max-height: 100%;
${StyledModalSection}:last-of-type {
padding-bottom: ${({ theme }) => theme.orbit.spaceXXLarge};
margin-bottom: ${({ fixedFooter, footerHeight }) =>
fixedFooter ? `${footerHeight}px` : "0"};
&::after {
content: none;
}
}
${StyledModalHeader} {
margin-bottom: ${({ hasModalSection, fixedFooter, footerHeight }) =>
!hasModalSection && fixedFooter ? `${footerHeight}px` : "0"};
}
${StyledModalFooter} {
padding: ${({ theme, fixedFooter }) =>
fixedFooter
? `${theme.orbit.spaceXLarge} ${theme.orbit.spaceXXLarge}!important`
: theme.orbit.spaceXXLarge};
max-width: ${({ modalWidth }) => (modalWidth ? `${modalWidth}px` : getSizeToken)};
position: ${({ fullyScrolled, fixedFooter }) => fixedFooter && fullyScrolled && "absolute"};
box-shadow: ${({ fullyScrolled }) => fullyScrolled && "none"};
}
${MobileHeader} {
top: ${({ scrolled, theme }) => (scrolled ? "0" : `-${theme.orbit.spaceXXLarge}`)};
width: ${({ modalWidth, theme }) =>
`calc(${modalWidth}px - 48px - ${theme.orbit.spaceXXLarge})`};
}
`)};
${onlyIE(
css`
${StyledModalFooter} {
// -ms-page must be used for mobile devices
position: ${({ fixedFooter }) => fixedFooter && "-ms-page"};
}
`,
)};
${({ theme }) =>
onlyIE(
css`
${StyledModalFooter} {
// we need to apply static position for IE only when fullyScrolled and fixedFooter
// or fixed when fixedFooter (overwrite -ms-page)
position: ${({ fullyScrolled, fixedFooter }) =>
(fullyScrolled && fixedFooter && "static") || (fixedFooter && "fixed")};
// for IE there's need to be added inset box-shadow with same background as footer has
box-shadow: ${({ fixedFooter }) =>
!fixedFooter && `inset 0 0 0 1px ${theme.orbit.paletteWhite}`};
}
// also we need to clear not wanted margins
${({ fullyScrolled, fixedFooter }) =>
fullyScrolled &&
fixedFooter &&
css`
${StyledModalSection}:last-of-type {
margin-bottom: 0;
}
${StyledModalHeader} {
margin-bottom: ${({ hasModalSection }) => !hasModalSection && "0"};
}
`};
`,
getBreakpointWidth(QUERIES.LARGEMOBILE, theme),
)};
`;
ModalWrapperContent.defaultProps = {
theme: defaultTheme,
};
const OFFSET = 40;
const Modal = React.forwardRef<Props, Instance>(
(
{
size = SIZES.NORMAL,
scrollingElementRef,
children,
onClose,
fixedFooter = false,
isMobileFullPage = false,
preventOverlayClose = false,
hasCloseButton = true,
dataTest,
}: Props,
ref,
) => {
const [loaded, setLoaded] = React.useState<boolean>(false);
const [scrolled, setScrolled] = React.useState<boolean>(false);
const [fullyScrolled, setFullyScrolled] = React.useState<boolean>(false);
const [hasModalTitle, setHasModalTitle] = React.useState<boolean>(false);
const [hasModalSection, setHasModalSection] = React.useState<boolean>(false);
const [clickedModalBody, setClickedModalBody] = React.useState<boolean>(false);
const [fixedClose, setFixedClose] = React.useState<boolean>(false);
const [focusTriggered, setFocusTriggered] = React.useState<boolean>(false);
const [modalWidth, setModalWidth] = React.useState<number>(0);
const [footerHeight, setFooterHeight] = React.useState<number>(0);
const [firstFocusableEl, setFirstFocusableEl] = React.useState<HTMLElement | null>(null);
const [lastFocusableEl, setLastFocusableEl] = React.useState<HTMLElement | null>(null);
const modalContent = React.useRef<HTMLElement | null>(null);
const modalBody = React.useRef<HTMLElement | null>(null);
const modalID = React.useMemo(() => randomID("modalID"), []);
const { isLargeMobile } = useMediaQuery();
const scrollingElement = React.useRef<HTMLElement | null>(null);
const setScrollingElementRefs = React.useCallback(
node => {
scrollingElement.current = node;
if (scrollingElementRef) {
if (typeof scrollingElementRef === "function") {
scrollingElementRef(node);
} else {
// eslint-disable-next-line no-param-reassign
scrollingElementRef.current = node;
}
}
},
[scrollingElementRef],
);
const modalContentRef = React.useCallback(
node => {
modalContent.current = node;
if (!isLargeMobile) setScrollingElementRefs(node);
},
[isLargeMobile, setScrollingElementRefs],
);
const modalBodyRef = React.useCallback(
node => {
modalBody.current = node;
if (isLargeMobile) setScrollingElementRefs(node);
},
[isLargeMobile, setScrollingElementRefs],
);
const prevChildren = usePrevious(children);
const setDimensions = () => {
const content = modalContent.current;
if (!content) return;
// added in 4.0.3, interpolation of styled component return static className
const footerEl = content.querySelector(`${StyledModalFooter}`);
const contentDimensions = content.getBoundingClientRect();
setModalWidth(contentDimensions.width);
if (footerEl?.clientHeight) {
setFooterHeight(footerEl.clientHeight);
}
};
const setFirstFocus = () => {
if (modalBody.current) {
modalBody.current.focus();
}
};
const decideFixedFooter = () => {
if (!modalContent.current || !modalBody.current) return;
// if the content height is smaller than window height, we need to explicitly set fullyScrolled to true
const content = modalContent.current;
const body = modalBody.current;
const contentHeight =
content.scrollHeight > content.offsetHeight + OFFSET
? content.offsetHeight
: content.scrollHeight;
// when scrollHeight + topPadding - scrollingElementHeight is smaller than or equal to window height
setFullyScrolled(contentHeight + OFFSET - body.scrollTop <= window.innerHeight);
};
const manageFocus = () => {
if (!focusTriggered || !modalContent.current) return;
const focusableElements = modalContent.current.querySelectorAll(FOCUSABLE_ELEMENT_SELECTORS);
if (focusableElements.length > 0) {
setFirstFocusableEl(focusableElements[0]);
setLastFocusableEl(focusableElements[focusableElements.length - 1]);
}
};
const keyboardHandler = (event: SyntheticKeyboardEvent<HTMLElement>) => {
if (event.keyCode !== KEY_CODE_MAP.TAB) return;
if (!focusTriggered) {
setFocusTriggered(true);
manageFocus();
}
if (
event.shiftKey &&
(document.activeElement === firstFocusableEl ||
document.activeElement === modalBody.current)
) {
event.preventDefault();
lastFocusableEl?.focus();
} else if (!event.shiftKey && document.activeElement === lastFocusableEl) {
event.preventDefault();
firstFocusableEl?.focus();
}
};
const handleKeyDown = (event: SyntheticKeyboardEvent<HTMLDivElement>) => {
if (onClose && event.key === "Escape") {
event.stopPropagation();
onClose(event);
}
keyboardHandler(event);
};
const handleResize = React.useCallback(() => {
setDimensions();
decideFixedFooter();
}, []);
const handleClickOutside = (event: MouseEvent) => {
const clickedOutside =
onClose &&
preventOverlayClose === false &&
!clickedModalBody &&
modalContent.current &&
event.target instanceof Element &&
!modalContent.current.contains(event.target) &&
/ModalBody|ModalWrapper/.test(event.target.className);
if (clickedOutside && onClose) {
onClose(event);
}
setClickedModalBody(false);
};
const setScrollStates = (
target: HTMLElement,
fullScrollOffset: number,
fixCloseOffset: number,
scrollBegin: ?number,
mobile?: boolean,
) => {
const content = modalContent.current;
if (!content) return;
const { height: contentHeight } = content.getBoundingClientRect();
/*
Only for desktop, we need to check if the scrollHeight of content is bigger than actual height
if so, we need to you use the contentHeight + padding as bottom scroll point,
otherwise actual scrollHeight of the target is enough.
*/
const scrollHeight =
!mobile && target.scrollHeight > contentHeight + 80
? contentHeight + 80
: target.scrollHeight;
setScrolled(target.scrollTop >= scrollBegin + (!mobile ? target.scrollTop : 0));
setFixedClose(target.scrollTop >= fixCloseOffset);
// set fullyScrolled state sooner than the exact end of the scroll (with fullScrollOffset value)
setFullyScrolled(
fixedFooter && target.scrollTop >= scrollHeight - target.clientHeight - fullScrollOffset,
);
};
const getScrollTopPoint = (mobile?: boolean) => {
const content = modalContent.current;
if (!content) return null;
const headingEl = content.querySelector(`${ModalHeading}`);
if (headingEl) {
const { top } = headingEl.getBoundingClientRect();
return top;
}
if (mobile) return OFFSET;
const { top } = content.getBoundingClientRect();
return top;
};
const handleScroll = (event: Event) => {
if (event.target instanceof HTMLDivElement && event.target === modalBody.current) {
setScrollStates(event.target, OFFSET, OFFSET, getScrollTopPoint());
}
};
const handleMobileScroll = (event: Event) => {
if (event.target instanceof HTMLDivElement && event.target === modalContent.current) {
setScrollStates(event.target, 10, 1, getScrollTopPoint(true), true);
}
};
const handleMouseDown = () => {
/*
This is due to issue where it was possible to close Modal,
even though click started (onMouseDown) in ModalWrapper.
*/
setClickedModalBody(true);
};
const callContextFunctions = () => {
setDimensions();
decideFixedFooter();
manageFocus();
};
const getScrollPosition = () => {
if (scrollingElement.current) {
return scrollingElement.current.scrollTop;
}
return null;
};
const setScrollPosition = value => {
if (scrollingElement.current) {
scrollingElement.current.scrollTop = value;
}
};
React.useImperativeHandle(ref, () => ({
getScrollPosition,
setScrollPosition,
modalBody,
modalContent,
}));
React.useEffect(() => {
const timer: TimeoutID = setTimeout(() => {
setLoaded(true);
decideFixedFooter();
setDimensions();
setFirstFocus();
}, 15);
window.addEventListener("resize", handleResize);
return () => {
clearTimeout(timer);
window.removeEventListener("resize", handleResize);
};
}, [handleResize]);
React.useEffect(() => {
if (children !== prevChildren) {
decideFixedFooter();
setDimensions();
}
}, [children, prevChildren]);
const hasCloseContainer = hasModalTitle || (onClose && hasCloseButton);
return (
<ModalBody
tabIndex="0"
onKeyDown={handleKeyDown}
onScroll={handleScroll}
onClick={handleClickOutside}
data-test={dataTest}
ref={modalBodyRef}
role="dialog"
aria-modal="true"
aria-labelledby={modalID}
>
<ModalWrapper
size={size}
loaded={loaded}
onScroll={handleMobileScroll}
fixedFooter={fixedFooter}
id={modalID}
isMobileFullPage={isMobileFullPage}
>
<ModalWrapperContent
size={size}
fixedFooter={fixedFooter}
scrolled={scrolled}
ref={modalContentRef}
fixedClose={fixedClose}
fullyScrolled={fullyScrolled}
modalWidth={modalWidth}
footerHeight={footerHeight}
hasModalSection={hasModalSection}
isMobileFullPage={isMobileFullPage}
onMouseDown={handleMouseDown}
>
{hasCloseContainer && (
<CloseContainer
data-test="CloseContainer"
modalWidth={modalWidth}
size={size}
scrolled={scrolled}
fixedClose={fixedClose}
isMobileFullPage={isMobileFullPage}
>
{onClose && hasCloseButton && (
<ModalCloseButton onClick={onClose} dataTest={CLOSE_BUTTON_DATA_TEST} />
)}
</CloseContainer>
)}
<ModalContext.Provider
value={{
setHasModalTitle,
setHasModalSection: () => setHasModalSection(true),
removeHasModalSection: () => setHasModalSection(false),
callContextFunctions,
hasModalSection,
isMobileFullPage,
closable: Boolean(onClose),
isInsideModal: true,
}}
>
{children}
</ModalContext.Provider>
</ModalWrapperContent>
</ModalWrapper>
</ModalBody>
);
},
);
Modal.displayName = "Modal";
export default Modal;
export { default as ModalHeader } from "./ModalHeader";
export { default as ModalSection } from "./ModalSection";
export { default as ModalFooter } from "./ModalFooter";
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk.internal.v8native;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.chromium.sdk.CallFrame;
import org.chromium.sdk.DebugContext;
import org.chromium.sdk.InvalidContextException;
import org.chromium.sdk.JsEvaluateContext;
import org.chromium.sdk.JsScope;
import org.chromium.sdk.JsVariable;
import org.chromium.sdk.RelayOk;
import org.chromium.sdk.RestartFrameExtension;
import org.chromium.sdk.Script;
import org.chromium.sdk.SyncCallback;
import org.chromium.sdk.TextStreamPosition;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.v8native.InternalContext.ContextDismissedCheckedException;
import org.chromium.sdk.internal.v8native.processor.BacktraceProcessor;
import org.chromium.sdk.internal.v8native.protocol.V8ProtocolUtil;
import org.chromium.sdk.internal.v8native.protocol.input.FailedCommandResponse.ErrorDetails;
import org.chromium.sdk.internal.v8native.protocol.input.FrameObject;
import org.chromium.sdk.internal.v8native.protocol.input.RestartFrameBody;
import org.chromium.sdk.internal.v8native.protocol.input.ScopeRef;
import org.chromium.sdk.internal.v8native.protocol.input.SuccessCommandResponse;
import org.chromium.sdk.internal.v8native.protocol.output.DebuggerMessage;
import org.chromium.sdk.internal.v8native.protocol.output.DebuggerMessageFactory;
import org.chromium.sdk.internal.v8native.protocol.output.RestartFrameMessage;
import org.chromium.sdk.internal.v8native.value.JsScopeImpl;
import org.chromium.sdk.internal.v8native.value.JsVariableBase;
import org.chromium.sdk.internal.v8native.value.PropertyReference;
import org.chromium.sdk.internal.v8native.value.ValueLoader;
import org.chromium.sdk.internal.v8native.value.ValueMirror;
import org.chromium.sdk.util.GenericCallback;
import org.chromium.sdk.util.MethodIsBlockingException;
import org.chromium.sdk.util.RelaySyncCallback;
import org.json.simple.JSONObject;
/**
* A generic implementation of the CallFrame interface.
*/
public class CallFrameImpl implements CallFrame {
/** The frame ID as reported by the JavaScript VM. */
private final int frameId;
/** The debug context this call frame belongs in. */
private final InternalContext context;
/** The underlying frame data from the JavaScript VM. */
private final FrameObject frameObject;
/**
* 0-based line number in the entire script resource.
*/
private final int lineNumber;
/**
* Function name associated with the frame.
*/
private final String frameFunction;
/**
* The associated script id value.
*/
private final long scriptId;
/** The scopes known in this call frame. */
private final AtomicReference<List<? extends JsScope>> scopesRef =
new AtomicReference<List<? extends JsScope>>(null);
/** The receiver variable known in this call frame. May be null. Null is not cached. */
private final AtomicReference<JsVariable> receiverVariableRef =
new AtomicReference<JsVariable>(null);
/**
* A script associated with the frame.
*/
private Script script;
/**
* Constructs a call frame for the given handler using the FrameMirror data
* from the remote JavaScript VM.
*
* @param mirror frame in the VM
* @param index call frame id (0 is the stack top)
* @param context in which the call frame is created
*/
public CallFrameImpl(FrameObject frameObject, InternalContext context) {
this.frameObject = frameObject;
this.context = context;
int index = (int) frameObject.index();
JSONObject func = frameObject.func();
int currentLine = (int) frameObject.line();
// If we stopped because of the debuggerword then we're on the next
// line.
// TODO(apavlov): Terry says: we need to use the [e.g. Rhino] AST to
// decide if line is debuggerword. If so, find the next sequential line.
// The below works for simple scripts but doesn't take into account
// comments, etc.
// TODO(peter.rybin): do we really need this thing? (advancing to the next line?)
// stopping on "debugger;" seems to be a quite natural thing.
String srcLine = frameObject.sourceLineText();
if (srcLine.trim().startsWith(DEBUGGER_RESERVED)) {
currentLine++;
}
Long scriptRef = V8ProtocolUtil.getObjectRef(frameObject.script());
long scriptId =
ScriptImpl.getScriptId(context.getValueLoader().getSpecialHandleManager(), scriptRef);
this.scriptId = scriptId;
this.lineNumber = currentLine;
this.frameFunction = V8ProtocolUtil.getFunctionName(func);
this.frameId = index;
}
public InternalContext getInternalContext() {
return context;
}
@Override
public List<? extends JsScope> getVariableScopes() {
ensureScopes();
return scopesRef.get();
}
@Override
public JsVariable getReceiverVariable() throws MethodIsBlockingException {
ensureReceiver();
return receiverVariableRef.get();
}
@Override
public JsEvaluateContext getEvaluateContext() {
return evaluateContextImpl;
}
private void ensureScopes() {
if (scopesRef.get() != null) {
return;
}
List<? extends JsScope> result = Collections.unmodifiableList(createScopes());
scopesRef.compareAndSet(null, result);
}
private void ensureReceiver() throws MethodIsBlockingException {
if (receiverVariableRef.get() != null) {
return;
}
JsVariable result;
PropertyReference ref = V8Helper.computeReceiverRef(frameObject);
if (ref == null) {
result = null;
} else {
ValueLoader valueLoader = context.getValueLoader();
ValueMirror mirror =
valueLoader.getOrLoadValueFromRefs(Collections.singletonList(ref)).get(0);
// This name should be string. We are making it string as a fall-back strategy.
String varNameStr = ref.getName().toString();
// 'this' variable is not mutable. Consider making it mutable.
result = new JsVariableBase.Impl(valueLoader, mirror, varNameStr);
}
if (result != null) {
receiverVariableRef.compareAndSet(null, result);
}
}
@Override
public TextStreamPosition getStatementStartPosition() {
return textStreamPosition;
}
@Override
public String getFunctionName() {
return frameFunction;
}
@Override
public Script getScript() {
return script;
}
/**
* @return this call frame's unique identifier within the V8 VM (0 is the top
* frame)
*/
public int getIdentifier() {
return frameId;
}
void hookUpScript(ScriptManager scriptManager) {
Script script = scriptManager.findById(scriptId);
if (script != null) {
this.script = script;
}
}
private List<JsScopeImpl<?>> createScopes() {
List<ScopeRef> scopes = frameObject.scopes();
List<JsScopeImpl<?>> result = new ArrayList<JsScopeImpl<?>>(scopes.size());
for (ScopeRef scopeRef : scopes) {
result.add(JsScopeImpl.create(JsScopeImpl.Host.create(this), scopeRef));
}
return result;
}
private final JsEvaluateContextImpl evaluateContextImpl = new JsEvaluateContextImpl() {
@Override
protected Integer getFrameIdentifier() {
return getIdentifier();
}
@Override
public InternalContext getInternalContext() {
return context;
}
};
private final TextStreamPosition textStreamPosition = new TextStreamPosition() {
@Override public int getOffset() {
return frameObject.position().intValue();
}
@Override public int getLine() {
return lineNumber;
}
@Override public int getColumn() {
Long columnObj = frameObject.column();
if (columnObj == null) {
return -1;
}
return columnObj.intValue();
}
};
/**
* Implements restart frame operation as chain of VM calls. After the main 'restart' command
* it either calls 'step in' request or reloads backtrace. {@link RelaySyncCallback} is used
* to ensure final sync callback call guarantee.
*/
public static final RestartFrameExtension RESTART_FRAME_EXTENSION = new RestartFrameExtension() {
@Override
public RelayOk restartFrame(CallFrame callFrame,
final GenericCallback<Boolean> callback, SyncCallback syncCallback) {
final CallFrameImpl frameImpl = (CallFrameImpl) callFrame;
final DebugSession debugSession = frameImpl.context.getDebugSession();
RelaySyncCallback relaySyncCallback = new RelaySyncCallback(syncCallback);
final RelaySyncCallback.Guard guard = relaySyncCallback.newGuard();
RestartFrameMessage message = new RestartFrameMessage(frameImpl.frameId);
V8CommandCallbackBase v8Callback = new V8CommandCallbackBase() {
@Override
public void success(SuccessCommandResponse successResponse) {
RelayOk relayOk =
handleRestartResponse(successResponse, debugSession, callback, guard.getRelay());
guard.discharge(relayOk);
}
@Override
public void failure(String message, ErrorDetails errorDetails) {
if (callback != null) {
callback.failure(new Exception(message));
}
}
};
try {
return frameImpl.context.sendV8CommandAsync(message, false, v8Callback,
guard.asSyncCallback());
} catch (ContextDismissedCheckedException e) {
throw new InvalidContextException(e);
}
}
private RelayOk handleRestartResponse(SuccessCommandResponse successResponse,
DebugSession debugSession,
final GenericCallback<Boolean> callback, final RelaySyncCallback relaySyncCallback) {
RestartFrameBody body;
try {
body = successResponse.body().asRestartFrameBody();
} catch (JsonProtocolParseException e) {
throw new RuntimeException(e);
}
InternalContext.UserContext debugContext =
debugSession.getContextBuilder().getCurrentDebugContext();
if (debugContext == null) {
// We may have already issued 'continue' since the moment that change live command
// was sent so the context was dropped. Ignore this case.
return finishRestartSuccessfully(false, callback, relaySyncCallback);
}
RestartFrameBody.ResultDescription resultDescription = body.getResultDescription();
if (body.getResultDescription().stack_update_needs_step_in() == Boolean.TRUE) {
return stepIn(debugContext, callback, relaySyncCallback);
} else {
return reloadStack(debugContext, callback, relaySyncCallback);
}
}
private RelayOk stepIn(InternalContext.UserContext debugContext,
final GenericCallback<Boolean> callback, final RelaySyncCallback relaySyncCallback) {
final RelaySyncCallback.Guard guard = relaySyncCallback.newGuard();
DebugContext.ContinueCallback continueCallback = new DebugContext.ContinueCallback() {
@Override
public void success() {
RelayOk relayOk = finishRestartSuccessfully(true, callback, relaySyncCallback);
guard.discharge(relayOk);
}
@Override
public void failure(String errorMessage) {
if (callback != null) {
callback.failure(new Exception(errorMessage));
}
}
};
return debugContext.continueVm(DebugContext.StepAction.IN, 0,
continueCallback, guard.asSyncCallback());
}
private RelayOk reloadStack(InternalContext.UserContext debugContext,
final GenericCallback<Boolean> callback, final RelaySyncCallback relaySyncCallback) {
final RelaySyncCallback.Guard guard = relaySyncCallback.newGuard();
final ContextBuilder.ExpectingBacktraceStep backtraceStep =
debugContext.createReloadBacktraceStep();
V8CommandCallbackBase v8Callback = new V8CommandCallbackBase() {
@Override
public void success(SuccessCommandResponse successResponse) {
BacktraceProcessor.setFrames(successResponse, backtraceStep);
RelayOk relayOk = finishRestartSuccessfully(false, callback, relaySyncCallback);
guard.discharge(relayOk);
}
@Override
public void failure(String message, ErrorDetails errorDetails) {
if (callback != null) {
callback.failure(new Exception(message));
}
}
};
DebuggerMessage message = DebuggerMessageFactory.backtrace(null, null, true);
try {
// Command is not immediate because we are supposed to be suspended.
return debugContext.getInternalContext().sendV8CommandAsync(message, false,
v8Callback, guard.asSyncCallback());
} catch (ContextDismissedCheckedException e) {
throw new InvalidContextException(e);
}
}
private RelayOk finishRestartSuccessfully(boolean vmResumed,
GenericCallback<Boolean> callback, RelaySyncCallback relaySyncCallback) {
if (callback != null) {
callback.success(vmResumed);
}
return relaySyncCallback.finish();
}
@Override
public boolean canRestartFrame(CallFrame callFrame) {
return callFrame.getScript() != null;
}
};
private static final String DEBUGGER_RESERVED = "debugger";
}
|
#!/bin/bash
#
# This script will install Ansible and then deploy a simple Ceph cluster.
# The script relies on the auto osd discovery feature, so we at least expect 2 raw devices
# to work properly.
set -e
if [[ -z $1 ]]; then
CEPH_BRANCH_DEFAULT=master
else
CEPH_BRANCH_DEFAULT=$1
fi
CEPH_BRANCH=${CEPH_BRANCH:-$CEPH_BRANCH_DEFAULT}
SUBNET=$(ip r | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/[0-9]\{1,2\}' | head -1)
MON_IP=$(ip -4 -o a | awk '/eth/ { sub ("/..", "", $4); print $4 }')
if [[ $EUID -ne 0 ]]; then
echo "You are NOT running this script as root."
echo "You should."
echo "Really."
echo "PLEASE RUN IT WITH SUDO ONLY :)"
exit 1
fi
sudo bash install-ansible.sh
ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
cp group_vars/all.sample group_vars/all
cp group_vars/osds.sample group_vars/osds
sed -i "s/#osd_auto_discovery: false/osd_auto_discovery: true/" group_vars/osds
sed -i "s/#journal_collocation: false/journal_collocation: true/" group_vars/osds
sed -i "s/#ceph_dev: false/ceph_dev: true/" group_vars/all
sed -i "s/#pool_default_size: 3/pool_default_size: 2/" group_vars/all
sed -i "s/#monitor_address: 0.0.0.0/monitor_address: ${MON_IP}/" group_vars/all
sed -i "s/#journal_size: 0/journal_size: 100/" group_vars/all
sed -i "s|#public_network: 0.0.0.0\/0|public_network: ${SUBNET}|" group_vars/all
sed -i "s/#common_single_host_mode: true/common_single_host_mode: true/" group_vars/all
sed -i "s|#ceph_dev_branch: master|ceph_dev_branch: ${CEPH_BRANCH}|" group_vars/all
cat > /etc/ansible/hosts <<EOF
[mons]
localhost
[osds]
localhost
[mdss]
localhost
[rgws]
localhost
EOF
cp site.yml.sample site.yml
ansible all -m ping
ansible-playbook site.yml
|
import os
from uuid import UUID
from allure_commons.utils import md5
from allure_commons.model2 import StatusDetails
from allure_commons.model2 import Status
from allure_commons.model2 import Parameter
from allure_commons.utils import format_exception
def get_step_name(node, step):
name = "{step_keyword} {step_name}".format(step_keyword=step.keyword, step_name=step.name)
if hasattr(node, 'callspec'):
for key, value in node.callspec.params.items():
name = name.replace("<{key}>".format(key=key), "<{{{key}}}>".format(key=key))
name = name.format(**node.callspec.params)
return name
def get_name(node, scenario):
if hasattr(node, 'callspec'):
parts = node.nodeid.rsplit("[")
return "{name} [{params}".format(name=scenario.name, params=parts[-1])
return scenario.name
def get_full_name(feature, scenario):
feature_path = os.path.normpath(feature.rel_filename)
return "{feature}:{scenario}".format(feature=feature_path, scenario=scenario.name)
def get_uuid(*args):
return str(UUID(md5(*args)))
def get_status_details(exception):
message = str(exception)
trace = format_exception(type(exception), exception)
return StatusDetails(message=message, trace=trace) if message or trace else None
def get_pytest_report_status(pytest_report):
pytest_statuses = ('failed', 'passed', 'skipped')
statuses = (Status.FAILED, Status.PASSED, Status.SKIPPED)
for pytest_status, status in zip(pytest_statuses, statuses):
if getattr(pytest_report, pytest_status):
return status
def get_params(node):
if hasattr(node, 'callspec'):
params = node.callspec.params
return [Parameter(name=name, value=str(value)) for name, value in params.items()]
|
<img src="{{ asset('demyhealth/images/logo.png') }}" alt="Logo" class="h-10">
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model("user_model");
$this->load->library('form_validation');
$this->load->library('session');
}
public function index()
{
$this->cek_login_lib->sudah_login();
$data["title"] = 'Login Page';
$this->load->view('v_login', $data);
}
public function logout()
{
$ms = $this->session->userdata('masuk');
if ($ms == 'arsip_bjb') {
$this->session->sess_destroy();
redirect(base_url());
} else {
redirect(base_url());
}
}
public function cek()
{
$post = $this->input->post();
$u = $post['username'];
$p = $post['password'];
$username = $this->security->xss_clean(trim(htmlspecialchars($u, ENT_QUOTES)));
$password = $this->security->xss_clean(trim(htmlspecialchars($p, ENT_QUOTES)));
$user = $this->user_model;
$isiUser = $user->cari_username($username);
$hasil = $isiUser->row_array();
// mengecek username
if ($isiUser->num_rows() != 0 ) {
// cek password
if (password_verify($password, $hasil['password'])) {
// set session
$array = array(
'masuk' => 'arsip_bjb',
'level' => $hasil['id_data_level'],
'username' => $hasil['username'],
'id_data_user' => $hasil['id_data_user'],
'id_data_pegawai' => $hasil['id_data_pegawai'],
'add_time' => $hasil['add_time_user'],
'unit_kerja' => $hasil['unit_kerja'],
'id_unit_kerja' => $hasil['id_unit_kerja']
);
$this->session->set_userdata( $array );
// berhasil masuk
echo json_encode(['hasil' => 'silahkan masuk']);
}else{
// password salah
echo json_encode(['hasil' => 'password salah']);
}
}else{
// username tidak ditemukan
echo json_encode(['hasil' => 'username tidak ditemukan']);
}
}
// public function sign_in()
// {
// $post = $this->input->post();
// $id_data_user = $post['id_data_user'];
// $username = $post['username'];
// $id_data_pegawai = $post['id_data_pegawai'];
// $add_time = $post['add_time'];
// $this->session->set_userdata('id_data_user',$id_data_user);
// $this->session->set_userdata('username',$username);
// $this->session->set_userdata('id_data_pegawai',$id_data_pegawai);
// $this->session->set_userdata('add_time',$add_time);
// echo "dashboard";
// }
public function tes()
{
$hash = password_hash('pusat', PASSWORD_DEFAULT);
echo $hash;
// if (password_verify('t', $hash2)){
// echo "benar";
// }else{
// echo "salah";
// }
}
public function r()
{
$user = $this->user_model;
$isiUser = $user->joinUser1('q','1');
echo $isiUser;
}
}
/* End of file Login.php */
/* Location: ./application/controllers/Login.php */ |
@using Blogifier.Core.Data.Models
@using Blogifier.Core.Common
@model BlogPostsModel
@{
var term = ViewBag.Term;
var search = "search";
Model.Pager.RouteValue = search + "/" + term + "/";
}
<main class="page-search">
<header class="page-cover" style="background-image: url('@Model.CoverImg')">
<h2 class="page-cover-title">@term</h2>
<p class="page-cover-desc">Search Results:</p>
</header>
<div class="page-content">
<div class="container">
@Html.Partial($"~/{ApplicationSettings.BlogThemesFolder}/OneFour/_Shared/_Post.cshtml", Model.Posts)
@Html.Partial($"~/{ApplicationSettings.BlogThemesFolder}/OneFour/_Shared/_Pager.cshtml", Model.Pager)
</div>
</div>
</main> |
<ul class="nav" id="side-menu">
<li>
<a href="index.php"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a>
</li>
<li>
<a href="data_kategori_barang.php"><i class="fa fa-briefcase fa-fw"></i> Data Kategori Barang</a>
</li>
<li>
<a href="data_barang.php"><i class="fa fa-briefcase fa-fw"></i> Data Barang</a>
</li>
<li>
<a href="data_hutang.php"><i class="fa fa-briefcase fa-fw"></i> Data Hutang</a>
</li>
<li>
<a href="data_supplier.php"><i class="fa fa-briefcase fa-fw"></i> Data Supplier</a>
</li>
<li>
<a href=" data_pembelian.php"><i class="fa fa-cart-plus fa-fw"></i> Data Pembelian</a>
</li>
<li>
<a href="data_penjualan.php"><i class="fa fa-cart-plus fa-fw"></i> Data Penjualan</a>
</li>
<li>
<a href=" detail_penjualann.php"><i class="fa fa-cart-plus fa-fw"></i> Data Detail Penjualan</a>
</li>
<li>
<a href="logout.php"><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul> |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.bumptech.glide.load.model;
// Referenced classes of package com.bumptech.glide.load.model:
// LazyHeaderFactory, LazyHeaders
static final class LazyHeaders$StringHeaderFactory
implements LazyHeaderFactory
{
public String buildHeader()
{
return value;
// 0 0:aload_0
// 1 1:getfield #19 <Field String value>
// 2 4:areturn
}
public boolean equals(Object obj)
{
if(obj instanceof LazyHeaders$StringHeaderFactory)
//* 0 0:aload_1
//* 1 1:instanceof #2 <Class LazyHeaders$StringHeaderFactory>
//* 2 4:ifeq 24
{
obj = ((Object) ((LazyHeaders$StringHeaderFactory)obj));
// 3 7:aload_1
// 4 8:checkcast #2 <Class LazyHeaders$StringHeaderFactory>
// 5 11:astore_1
return value.equals(((Object) (((LazyHeaders$StringHeaderFactory) (obj)).value)));
// 6 12:aload_0
// 7 13:getfield #19 <Field String value>
// 8 16:aload_1
// 9 17:getfield #19 <Field String value>
// 10 20:invokevirtual #29 <Method boolean String.equals(Object)>
// 11 23:ireturn
} else
{
return false;
// 12 24:iconst_0
// 13 25:ireturn
}
}
public int hashCode()
{
return value.hashCode();
// 0 0:aload_0
// 1 1:getfield #19 <Field String value>
// 2 4:invokevirtual #33 <Method int String.hashCode()>
// 3 7:ireturn
}
public String toString()
{
StringBuilder stringbuilder = new StringBuilder();
// 0 0:new #36 <Class StringBuilder>
// 1 3:dup
// 2 4:invokespecial #37 <Method void StringBuilder()>
// 3 7:astore_1
stringbuilder.append("StringHeaderFactory{value='");
// 4 8:aload_1
// 5 9:ldc1 #39 <String "StringHeaderFactory{value='">
// 6 11:invokevirtual #43 <Method StringBuilder StringBuilder.append(String)>
// 7 14:pop
stringbuilder.append(value);
// 8 15:aload_1
// 9 16:aload_0
// 10 17:getfield #19 <Field String value>
// 11 20:invokevirtual #43 <Method StringBuilder StringBuilder.append(String)>
// 12 23:pop
stringbuilder.append('\'');
// 13 24:aload_1
// 14 25:bipush 39
// 15 27:invokevirtual #46 <Method StringBuilder StringBuilder.append(char)>
// 16 30:pop
stringbuilder.append('}');
// 17 31:aload_1
// 18 32:bipush 125
// 19 34:invokevirtual #46 <Method StringBuilder StringBuilder.append(char)>
// 20 37:pop
return stringbuilder.toString();
// 21 38:aload_1
// 22 39:invokevirtual #48 <Method String StringBuilder.toString()>
// 23 42:areturn
}
private final String value;
LazyHeaders$StringHeaderFactory(String s)
{
// 0 0:aload_0
// 1 1:invokespecial #17 <Method void Object()>
value = s;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #19 <Field String value>
// 5 9:return
}
}
|
# Foundation Assets [![Bower License][badge_license]](LICENSE.md)
[![Bower Package][badge_bower]](https://github.com/ARCANESOFT/foundation-assets)
[![Bower Release][badge_release]](https://github.com/ARCANESOFT/foundation-assets)
[badge_license]: https://img.shields.io/bower/l/foundation-assets.svg?style=flat-square
[badge_bower]: https://img.shields.io/badge/bower-foundation--assets-blue.svg?style=flat-square
[badge_release]: https://img.shields.io/bower/v/foundation-assets.svg?style=flat-square
### Available Packages/Frameworks/Widgets
| Name | Description |
| ---- | ----------- |
| | |
|
package es.unizar.eina.notepadv3;
import android.database.Cursor;
import androidx.test.espresso.action.ViewActions;
import androidx.test.rule.ActivityTestRule;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import es.unizar.eina.catlist.CatList;
import static androidx.test.espresso.Espresso.onData;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.longClick;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.isRoot;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withSpinnerText;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.core.AllOf.allOf;
public class Notepadv3EspressoTest {
private static final String TEST_NAME="Espresso";
private static List<String> notas = new ArrayList<>();
private static List<String> categorias = new ArrayList<>();
@Rule
public ActivityTestRule<Notepadv3> mActivityRule = new ActivityTestRule<>(Notepadv3.class);
private void crearNota(String title, String body) {
openActionBarOverflowOrOptionsMenu(mActivityRule.getActivity());
//onView(withText(R.string.menu_insert)).check(matches(notNullValue()));
onView(withText(R.string.menu_insert)).perform(click());
// Se asegura de que la actividad actual es NoteEdit
onView(withId(R.id.title)).check(matches(notNullValue()));
// En el título inserta "Espresso Note Title <i>"
onView(withId(R.id.title)).perform(typeText(title), closeSoftKeyboard());
// En el cuerpo inserta "Espresso Note Body <i>"
onView(withId(R.id.body)).perform(typeText(body), closeSoftKeyboard());
// Confirma y vuelve a la actividad anterior
onView(withId(R.id.confirm)).perform(click());
notas.add(title);
// Aserción: comprobación de que la nota está en la base de datos
Cursor noteCursor = mActivityRule.getActivity().getmDbHelper().fetchNote(title);
assertNoteEquals(title, body, noteCursor);
}
private void editarNota(String title, String body) {
onView(withText(title)).perform(longClick());
onView(withText(R.string.menu_edit)).perform(click());
// Se asegura de que la actividad actual es NoteEdit
// En el cuerpo inserta "Espresso Note Body <i>"
onView(withId(R.id.body)).perform(replaceText(body), closeSoftKeyboard());
// Confirma y vuelve a la actividad anterior
onView(withId(R.id.confirm)).perform(click());
// Aserción: comprobación de que la nota está en la base de datos
Cursor noteCursor = mActivityRule.getActivity().getmDbHelper().fetchNote(title);
assertNoteEquals(title, body, noteCursor);
}
private void editarCategoria(String name, String new_name) {
boolean goBack = false;
try {
onView(withId(R.id.title)).check(matches(isDisplayed()));
} catch (Exception e) {
onView(withId(R.id.notepad_buttonCat)).perform(click());
goBack = true;
}
onView(withText(name)).perform(longClick());
onView(withText(R.string.menu_cat_edit)).perform(click());
// Se asegura de que la actividad actual es NoteEdit
onView(withId(R.id.cat_name)).check(matches(notNullValue()));
// En el título inserta "Espresso Note Title <i>"
onView(withId(R.id.cat_name)).perform(replaceText(new_name), closeSoftKeyboard());
// Confirma y vuelve a la actividad anterior
onView(withId(R.id.cat_confirm)).perform(click());
categorias.remove(name);
categorias.add(new_name);
// Aserción: comprobación de que la nota se visualiza en el listado
onView(withText(new_name)).check(matches(isDisplayed()));
if(goBack) {
goBack();
}
}
private void crearCategoria(String name) {
boolean goBack = false;
try {
onView(withId(R.id.title)).check(matches(isDisplayed()));
} catch (Exception e) {
onView(withId(R.id.notepad_buttonCat)).perform(click());
goBack = true;
}
openActionBarOverflowOrOptionsMenu(mActivityRule.getActivity());
onView(withText(R.string.menu_insert)).check(matches(notNullValue()));
onView(withText(R.string.menu_insert)).perform(click());
// Se asegura de que la actividad actual es NoteEdit
onView(withId(R.id.cat_name)).check(matches(notNullValue()));
// En el título inserta "Espresso Note Title <i>"
onView(withId(R.id.cat_name)).perform(typeText(name), closeSoftKeyboard());
// Confirma y vuelve a la actividad anterior
onView(withId(R.id.cat_confirm)).perform(click());
categorias.add(name);
// Aserción: comprobación de que la nota se visualiza en el listado
onView(withText(name)).check(matches(isDisplayed()));
if(goBack) {
goBack();
}
}
private void crearNotaANDback(String title, String body) {
openActionBarOverflowOrOptionsMenu(mActivityRule.getActivity());
//onView(withText(R.string.menu_insert)).check(matches(notNullValue()));
onView(withText(R.string.menu_insert)).perform(click());
// Se asegura de que la actividad actual es NoteEdit
onView(withId(R.id.title)).check(matches(notNullValue()));
// En el título inserta "Espresso Note Title <i>"
onView(withId(R.id.title)).perform(typeText(title), closeSoftKeyboard());
// En el cuerpo inserta "Espresso Note Body <i>"
onView(withId(R.id.body)).perform(typeText(body), closeSoftKeyboard());
notas.add(title);
goBack();
}
@After
public void clear(){
boolean goBack = false;
try {
onView(withId(R.id.title)).check(matches(isDisplayed()));
} catch (Exception e) {
onView(withId(R.id.notepad_buttonCat)).perform(click());
goBack = true;
}
for(String title : categorias) {
borrarCat(title, false);
}
if(goBack) {
goBack();
}
listarCatReset();
listarTodas();
List<String> notas_n= new ArrayList<>(notas);
for(String title : notas_n) {
borrarNota(title);
}
}
/*public void limpiarNotas() {
listarCatReset();
listarTodas();
for(String title : notas) {
borrarNota(title);
}
}
@After
public void limpiarCategorias() {
boolean goBack = false;
try {
onView(withId(R.id.title)).check(matches(isDisplayed()));
} catch (Exception e) {
onView(withId(R.id.notepad_buttonCat)).perform(click());
goBack = true;
}
for(String title : categorias) {
borrarCat(title, false);
}
if(goBack) {
goBack();
}
}*/
private void borrarNota(String title) {
onView(withText(title)).perform(longClick());
onView(withText(R.string.menu_delete)).perform(click());
notas.remove(title);
}
private void borrarCat(String title, boolean from_note_list) {
boolean goBack = false;
if(from_note_list) {
try {
onView(withId(R.id.cat_id)).check(matches(isDisplayed()));
} catch (Exception e) {
onView(withId(R.id.notepad_buttonCat)).perform(click());
goBack = true;
}
}
onView(withText(title)).perform(longClick());
onView(withText(R.string.menu_cat_delete)).perform(click());
categorias.remove(title);
if(goBack) {
goBack();
}
}
private void listarPorTitulo() {
onView(withId(R.id.notepad_button)).perform(click());
onView(withId(R.id.notepad_order)).check(matches(withText("Title")));
}
private void listarPorCategoria() {
onView(withId(R.id.notepad_button)).perform(click());
onView(withId(R.id.notepad_order)).check(matches(withText("Category")));
}
private void listarTodas() {
onView(withId(R.id.spinner)).perform(click());
onData(allOf(is(instanceOf(String.class)), is("All"))).perform(click());
onView(withId(R.id.spinner)).check(matches(withSpinnerText("All")));
}
private void listarVigentes() {
onView(withId(R.id.spinner)).perform(click());
onData(allOf(is(instanceOf(String.class)), is("Planned Notes"))).perform(click());
onView(withId(R.id.spinner)).check(matches(withSpinnerText("Planned Notes")));
}
private void listarActivas() {
onView(withId(R.id.spinner)).perform(click());
onData(allOf(is(instanceOf(String.class)), is("Active Notes"))).perform(click());
onView(withId(R.id.spinner)).check(matches(withSpinnerText("Active Notes")));
}
private void listarCaducadas() {
onView(withId(R.id.spinner)).perform(click());
onData(allOf(is(instanceOf(String.class)), is("Expired Notes"))).perform(click());
onView(withId(R.id.spinner)).check(matches(withSpinnerText("Expired Notes")));
}
private void goBack() {
onView(isRoot()).perform(ViewActions.pressBack());
}
private void assertNoteEquals(String title, String body, Cursor noteCursor) {
assertThat(noteCursor.getCount(), is(greaterThanOrEqualTo(1)));
assertThat(noteCursor.getString(noteCursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)),
is(equalTo(title)));
assertThat(noteCursor.getString(noteCursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)),
is(equalTo(body)));
}
private void listarCategorias(String categoria) {
onView(withId(R.id.notepad_buttonCat)).perform(click());
onView(withText(categoria)).perform(longClick());
onView(withText(R.string.menu_cat_select)).perform(click());
onView(withId(R.id.notepad_category)).check(matches(withText(categoria)));
}
private void listarCategoriaAndBack() {
onView(withId(R.id.notepad_buttonCat)).perform(click());
goBack();
}
private void listarCatReset() {
onView(withId(R.id.notepad_buttonReset)).perform(click());
}
@Test
public void camino1() {
crearCategoria(UUID.randomUUID().toString());
listarPorCategoria();
listarPorTitulo();
listarVigentes();
listarPorCategoria();
listarActivas();
listarPorTitulo();
listarCaducadas();
listarCategorias(categorias.get(0));
crearNota(UUID.randomUUID().toString(), UUID.randomUUID().toString());
listarCatReset();
listarPorCategoria();
listarVigentes();
listarPorTitulo();
listarActivas();
listarPorCategoria();
listarCaducadas();
listarPorTitulo();
listarTodas();
listarCategoriaAndBack();
listarPorCategoria();
editarNota(notas.get(0), UUID.randomUUID().toString());
listarVigentes();
listarVigentes();
listarActivas();
listarVigentes();
listarCaducadas();
listarVigentes();
listarCategorias(categorias.get(0));
crearCategoria(UUID.randomUUID().toString());
listarActivas();
listarActivas();
listarCaducadas();
listarActivas();
listarCategorias(categorias.get(0));
editarCategoria(categorias.get(1), UUID.randomUUID().toString());
listarCaducadas();
listarCaducadas();
listarCategorias(categorias.get(1));
borrarCat(categorias.get(1), true);
listarCategorias(categorias.get(0));
}
@Test
public void camino2() {
crearNota(UUID.randomUUID().toString(), UUID.randomUUID().toString());
listarPorCategoria();
borrarNota(notas.get(0));
listarPorTitulo();
listarCatReset();
}
@Test
public void camino3() {
crearNota(UUID.randomUUID().toString(), UUID.randomUUID().toString());
listarPorCategoria();
crearNotaANDback(UUID.randomUUID().toString(), UUID.randomUUID().toString());
listarPorTitulo();
editarNota(notas.get(0), UUID.randomUUID().toString());
listarVigentes();
crearNotaANDback(UUID.randomUUID().toString(), UUID.randomUUID().toString());
listarCatReset();
}
@Test
public void camino4() {
crearNota(UUID.randomUUID().toString(), UUID.randomUUID().toString());
listarPorCategoria();
borrarNota(notas.get(0));
listarPorTitulo();
listarCatReset();
}
}
|
#include <complex>
#include <stdio.h>
extern "C" unsigned int
mandel_double(double re, double im, unsigned int max_iterations)
{
std::complex<double> c (re, im);
std::complex<double> z (0.0, 0.0);
for (unsigned int i = 0; i < max_iterations; i++)
{
if (std::abs(z) > 2) {
return i + 1;
}
z = z * z + c;
}
return 0;
}
unsigned char color_map [] = {
0, 0, 252,
64, 0, 252,
124, 0, 252,
188, 0, 252,
252, 0, 252,
252, 0, 188,
252, 0, 124,
252, 0, 64,
252, 0, 0,
252, 64, 0,
252, 124, 0,
252, 188, 0,
252, 252, 0,
188, 252, 0,
124, 252, 0,
64, 252, 0,
0, 252, 0,
0, 252, 64,
0, 252, 124,
0, 252, 188,
0, 252, 252,
0, 188, 252,
0, 124, 252,
0, 64, 252,
124, 124, 252,
156, 124, 252,
188, 124, 252,
220, 124, 252,
252, 124, 252,
252, 124, 220,
252, 124, 188,
252, 124, 156,
252, 124, 124,
252, 156, 124,
252, 188, 124,
252, 220, 124,
252, 252, 124,
220, 252, 124,
188, 252, 124,
156, 252, 124,
124, 252, 124,
124, 252, 156,
124, 252, 188,
124, 252, 220,
124, 252, 252,
124, 220, 252,
124, 188, 252,
124, 156, 252,
180, 180, 252,
196, 180, 252,
216, 180, 252,
232, 180, 252,
252, 180, 252,
252, 180, 232,
252, 180, 216,
252, 180, 196,
252, 180, 180,
252, 196, 180,
252, 216, 180,
252, 232, 180,
252, 252, 180,
232, 252, 180,
216, 252, 180,
196, 252, 180,
180, 252, 180,
180, 252, 196,
180, 252, 216,
180, 252, 232,
180, 252, 252,
180, 232, 252,
180, 216, 252,
180, 196, 252,
0, 0, 112,
28, 0, 112,
56, 0, 112,
84, 0, 112,
112, 0, 112,
112, 0, 84,
112, 0, 56,
112, 0, 28,
112, 0, 0,
112, 28, 0,
112, 56, 0,
112, 84, 0,
112, 112, 0,
84, 112, 0,
56, 112, 0,
28, 112, 0,
0, 112, 0,
0, 112, 28,
0, 112, 56,
0, 112, 84,
0, 112, 112,
0, 84, 112,
0, 56, 112,
0, 28, 112,
56, 56, 112,
68, 56, 112,
84, 56, 112,
96, 56, 112,
112, 56, 112,
112, 56, 96,
112, 56, 84,
112, 56, 68,
112, 56, 56,
112, 68, 56,
112, 84, 56,
112, 96, 56,
112, 112, 56,
96, 112, 56,
84, 112, 56,
68, 112, 56,
56, 112, 56,
56, 112, 68,
56, 112, 84,
56, 112, 96,
56, 112, 112,
56, 96, 112,
56, 84, 112,
56, 68, 112,
80, 80, 112,
88, 80, 112,
96, 80, 112,
104, 80, 112,
112, 80, 112,
112, 80, 104,
112, 80, 96,
112, 80, 88,
112, 80, 80,
112, 88, 80,
112, 96, 80,
112, 104, 80,
112, 112, 80,
104, 112, 80,
96, 112, 80,
88, 112, 80,
80, 112, 80,
80, 112, 88,
80, 112, 96,
80, 112, 104,
80, 112, 112,
80, 104, 112,
80, 96, 112,
80, 88, 112,
0, 0, 64,
16, 0, 64,
32, 0, 64,
48, 0, 64,
64, 0, 64,
64, 0, 48,
64, 0, 32,
64, 0, 16,
64, 0, 0,
64, 16, 0,
64, 32, 0,
64, 48, 0,
64, 64, 0,
48, 64, 0,
32, 64, 0,
16, 64, 0,
0, 64, 0,
0, 64, 16,
0, 64, 32,
0, 64, 48,
0, 64, 64,
0, 48, 64,
0, 32, 64,
0, 16, 64,
32, 32, 64,
40, 32, 64,
48, 32, 64,
56, 32, 64,
64, 32, 64,
64, 32, 56,
64, 32, 48,
64, 32, 40,
64, 32, 32,
64, 40, 32,
64, 48, 32,
64, 56, 32,
64, 64, 32,
56, 64, 32,
48, 64, 32,
40, 64, 32,
32, 64, 32,
32, 64, 40,
32, 64, 48,
32, 64, 56,
32, 64, 64,
32, 56, 64,
32, 48, 64,
32, 40, 64,
44, 44, 64,
48, 44, 64,
52, 44, 64,
60, 44, 64,
64, 44, 64,
64, 44, 60,
64, 44, 52,
64, 44, 48,
64, 44, 44,
64, 48, 44,
64, 52, 44,
64, 60, 44,
64, 64, 44,
60, 64, 44,
52, 64, 44,
48, 64, 44,
44, 64, 44,
44, 64, 48,
44, 64, 52,
44, 64, 60,
44, 64, 64,
44, 60, 64,
44, 52, 64,
44, 48, 64
};
struct Color
{
unsigned short red;
unsigned short green;
unsigned short blue;
};
extern "C" unsigned int
get_color_part (unsigned int color, unsigned int part)
{
return color_map [color * 3 + part];
}
extern "C" struct Color
get_color (unsigned int index)
{
struct Color value;
value.red = color_map [index * 3 + 0];
value.green = color_map [index * 3 + 1];
value.blue = color_map [index * 3 + 2];
return value;
}
extern "C" struct Color
linear_blend_color (unsigned int color1, unsigned int color2, double t)
{
struct Color low = get_color (color1);
struct Color high = get_color (color2);
struct Color value;
value.red = low.red + t * (high.red - low.red);
value.green = low.green + t * (high.green - low.green);
value.blue = low.blue + t * (high.blue - low.blue);
return value;
}
extern "C" struct Color
log_color(unsigned int pixel)
{
double log_pixel = log(pixel) / log(2);
double low = floor(log_pixel);
unsigned int high = low + 1;
double fraction = log_pixel - low;
return linear_blend_color (low, high, fraction);
}
extern "C" void
modified_log_color_c (unsigned int pixel, unsigned int *red, unsigned int *green, unsigned int *blue)
{
struct Color color;
if (pixel < 64)
{
unsigned int remainder = pixel % 16;
unsigned int low = pixel / 16;
unsigned int high = low + 1;
double fraction = (1.0 / 16.0) * (double) remainder;
color = linear_blend_color (low, high, fraction);
}
else
{
double log_pixel = log(pixel) / log(sqrt(2)) - 8;
// printf ("pixel = %d log_pixel = %g\n", pixel, log_pixel);
double low = floor(log_pixel);
unsigned int high = low + 1;
double fraction = log_pixel - low;
color = linear_blend_color (low, high, fraction);
}
*red = color.red;
*green = color.green;
*blue = color.blue;
// printf ("red = %d green = %d blue = %d\n", *red, *green, *blue);
}
|
package us.ihmc.euclid.tuple2D;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static us.ihmc.euclid.EuclidTestConstants.ITERATIONS;
import java.util.Random;
import org.junit.jupiter.api.Test;
import us.ihmc.euclid.exceptions.NotAMatrix2DException;
import us.ihmc.euclid.exceptions.NotAnOrientation2DException;
import us.ihmc.euclid.tools.EuclidCoreRandomTools;
import us.ihmc.euclid.tools.EuclidCoreTestTools;
import us.ihmc.euclid.tools.EuclidCoreTools;
import us.ihmc.euclid.transform.RigidBodyTransform;
import us.ihmc.euclid.tuple2D.interfaces.Point2DBasics;
import us.ihmc.euclid.tuple3D.Point3D;
public abstract class Point2DBasicsTest<T extends Point2DBasics> extends Tuple2DBasicsTest<T>
{
// Read-only part
@Test
public void testDistance()
{
Random random = new Random(654135L);
for (int i = 0; i < ITERATIONS; i++)
{
Vector2D translation = EuclidCoreRandomTools.nextVector2DWithFixedLength(random, 1.0);
double expectedDistance = EuclidCoreRandomTools.nextDouble(random, 0.0, 10.0);
translation.scale(expectedDistance);
T p1 = createRandomTuple(random);
T p2 = createTuple(p1.getX() + translation.getX(), p1.getY() + translation.getY());
double actualDistance = p1.distance(p2);
assertEquals(expectedDistance, actualDistance, getEpsilon());
}
}
@Test
public void testDistanceSquared()
{
Random random = new Random(654135L);
for (int i = 0; i < ITERATIONS; i++)
{
Vector2D translation = EuclidCoreRandomTools.nextVector2DWithFixedLength(random, 1.0);
double expectedDistanceSquared = EuclidCoreRandomTools.nextDouble(random, 0.0, 10.0);
translation.scale(EuclidCoreTools.squareRoot(expectedDistanceSquared));
T p1 = createRandomTuple(random);
T p2 = createTuple(p1.getX() + translation.getX(), p1.getY() + translation.getY());
double actualDistanceSquared = p1.distanceSquared(p2);
assertEquals(expectedDistanceSquared, actualDistanceSquared, getEpsilon());
}
}
@Test
public void testDistanceXY()
{
Random random = new Random(654135L);
for (int i = 0; i < ITERATIONS; i++)
{
Vector2D translation = EuclidCoreRandomTools.nextVector2DWithFixedLength(random, 1.0);
double expectedDistance = EuclidCoreRandomTools.nextDouble(random, 0.0, 10.0);
translation.scale(expectedDistance);
T p1 = createRandomTuple(random);
Point3D p2 = new Point3D(p1.getX() + translation.getX(), p1.getY() + translation.getY(), random.nextDouble());
double actualDistance = p1.distanceXY(p2);
assertEquals(expectedDistance, actualDistance, getEpsilon());
}
}
@Test
public void testDistanceXYSquared()
{
Random random = new Random(654135L);
for (int i = 0; i < ITERATIONS; i++)
{
Vector2D translation = EuclidCoreRandomTools.nextVector2DWithFixedLength(random, 1.0);
double expectedDistanceSquared = EuclidCoreRandomTools.nextDouble(random, 0.0, 10.0);
translation.scale(EuclidCoreTools.squareRoot(expectedDistanceSquared));
T p1 = createRandomTuple(random);
Point3D p2 = new Point3D(p1.getX() + translation.getX(), p1.getY() + translation.getY(), random.nextDouble());
double actualDistance = p1.distanceXYSquared(p2);
assertEquals(expectedDistanceSquared, actualDistance, getEpsilon());
}
}
@Test
public void testDistanceFromOrigin() throws Exception
{
Random random = new Random(654135L);
for (int i = 0; i < ITERATIONS; i++)
{
Vector2D translation = EuclidCoreRandomTools.nextVector2DWithFixedLength(random, 1.0);
double expectedDistance = EuclidCoreRandomTools.nextDouble(random, 0.0, 10.0);
translation.scale(expectedDistance);
T p = createTuple(translation.getX(), translation.getY());
double actualDistance = p.distanceFromOrigin();
assertEquals(expectedDistance, actualDistance, getEpsilon());
}
}
@Test
public void testDistanceFromOriginSquared() throws Exception
{
Random random = new Random(654135L);
for (int i = 0; i < ITERATIONS; i++)
{
Vector2D translation = EuclidCoreRandomTools.nextVector2DWithFixedLength(random, 1.0);
double expectedDistanceSquared = EuclidCoreRandomTools.nextDouble(random, 0.0, 10.0);
translation.scale(EuclidCoreTools.squareRoot(expectedDistanceSquared));
T p = createTuple(translation.getX(), translation.getY());
double actualDistance = p.distanceFromOriginSquared();
assertEquals(expectedDistanceSquared, actualDistance, getEpsilon());
}
}
// Basics part
@Test
public void testApplyTransform() throws Exception
{
Random random = new Random(2342L);
for (int i = 0; i < ITERATIONS; i++)
{
T original = createRandomTuple(random);
T actual = createEmptyTuple();
T expected = createEmptyTuple();
RigidBodyTransform rigidBodyTransform = new RigidBodyTransform();
rigidBodyTransform.setRotationYaw(EuclidCoreRandomTools.nextDouble(random, Math.PI));
rigidBodyTransform.setTranslation(EuclidCoreRandomTools.nextVector3D(random, 0.0, 10.0));
expected.set(original);
rigidBodyTransform.transform(expected);
actual.set(original);
actual.applyTransform(rigidBodyTransform);
EuclidCoreTestTools.assertTuple2DEquals(expected, actual, getEpsilon());
actual.set(original);
actual.applyTransform(rigidBodyTransform, false);
EuclidCoreTestTools.assertTuple2DEquals(expected, actual, getEpsilon());
actual.set(original);
actual.applyTransform(rigidBodyTransform, true);
EuclidCoreTestTools.assertTuple2DEquals(expected, actual, getEpsilon());
rigidBodyTransform = EuclidCoreRandomTools.nextRigidBodyTransform(random);
try
{
actual.applyTransform(rigidBodyTransform);
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
catch (NotAMatrix2DException | NotAnOrientation2DException e)
{
// good
}
catch (Exception e)
{
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
try
{
actual.applyTransform(rigidBodyTransform, true);
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
catch (NotAMatrix2DException | NotAnOrientation2DException e)
{
// good
}
catch (Exception e)
{
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
actual.applyTransform(rigidBodyTransform, false);
}
}
@Test
public void testApplyInverseTransform() throws Exception
{
Random random = new Random(2342L);
for (int i = 0; i < ITERATIONS; i++)
{
T original = createRandomTuple(random);
T actual = createEmptyTuple();
T expected = createEmptyTuple();
RigidBodyTransform rigidBodyTransform = new RigidBodyTransform();
rigidBodyTransform.setRotationYaw(EuclidCoreRandomTools.nextDouble(random, Math.PI));
rigidBodyTransform.setTranslation(EuclidCoreRandomTools.nextVector3D(random, 0.0, 10.0));
expected.set(original);
actual.set(original);
actual.applyTransform(rigidBodyTransform);
actual.applyInverseTransform(rigidBodyTransform);
EuclidCoreTestTools.assertTuple2DEquals(expected, actual, getEpsilon());
actual.set(original);
actual.applyTransform(rigidBodyTransform, false);
actual.applyInverseTransform(rigidBodyTransform, false);
EuclidCoreTestTools.assertTuple2DEquals(expected, actual, getEpsilon());
actual.set(original);
actual.applyTransform(rigidBodyTransform, true);
actual.applyInverseTransform(rigidBodyTransform, true);
EuclidCoreTestTools.assertTuple2DEquals(expected, actual, getEpsilon());
rigidBodyTransform = EuclidCoreRandomTools.nextRigidBodyTransform(random);
try
{
actual.applyInverseTransform(rigidBodyTransform);
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
catch (NotAMatrix2DException | NotAnOrientation2DException e)
{
// good
}
catch (Exception e)
{
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
try
{
actual.applyInverseTransform(rigidBodyTransform, true);
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
catch (NotAMatrix2DException | NotAnOrientation2DException e)
{
// good
}
catch (Exception e)
{
fail("Should have thrown a NotAMatrix2DException or NotAnOrientation2DException.");
}
actual.applyInverseTransform(rigidBodyTransform, false);
}
}
@Test
public void testGeometricallyEquals() throws Exception
{
Point2DBasics pointA;
Point2DBasics pointB;
Random random = new Random(621541L);
for (int i = 0; i < 100; ++i)
{
pointA = EuclidCoreRandomTools.nextPoint2D(random);
pointB = EuclidCoreRandomTools.nextPoint2D(random);
if (pointA.epsilonEquals(pointB, getEpsilon()))
{
assertTrue(pointA.geometricallyEquals(pointB, EuclidCoreTools.squareRoot(3) * getEpsilon()));
}
else
{
if (EuclidCoreTools.norm(pointA.getX() - pointB.getX(), pointA.getY() - pointB.getY()) <= getEpsilon())
{
assertTrue(pointA.geometricallyEquals(pointB, getEpsilon()));
}
else
{
assertFalse(pointA.geometricallyEquals(pointB, getEpsilon()));
}
}
pointA = EuclidCoreRandomTools.nextPoint2D(random);
pointB = new Point2D(pointA);
assertTrue(pointA.geometricallyEquals(pointB, 0));
pointB.set(pointA.getX() + 0.9d * getEpsilon(), pointA.getY());
assertTrue(pointA.geometricallyEquals(pointB, getEpsilon()));
pointB.set(pointA.getX() + 1.1d * getEpsilon(), pointA.getY());
assertFalse(pointA.geometricallyEquals(pointB, getEpsilon()));
pointB.set(pointA.getX(), pointA.getY() + 0.9d * getEpsilon());
assertTrue(pointA.geometricallyEquals(pointB, getEpsilon()));
pointB.set(pointA.getX(), pointA.getY() + 1.1d * getEpsilon());
assertFalse(pointA.geometricallyEquals(pointB, getEpsilon()));
}
}
}
|
/*
* ---license-start
* eu-digital-green-certificates / dgca-verifier-app-android
* ---
* Copyright (C) 2021 T-Systems International GmbH and all other contributors
* ---
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ---license-end
*
* Created by climent on 6/7/21 3:04 PM
*/
package it.ministerodellasalute.verificaC19.ui
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.mockk
import io.mockk.slot
import it.ministerodellasalute.verificaC19.data.VerifierRepository
import it.ministerodellasalute.verificaC19.data.local.Preferences
import it.ministerodellasalute.verificaC19.utils.mock.ServiceMocks
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class FirstViewModelTest {
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
@RelaxedMockK
private lateinit var preferences: Preferences
@RelaxedMockK
private lateinit var verifierRepository: VerifierRepository
private lateinit var viewModel: FirstViewModel
@Before
fun setup() {
MockKAnnotations.init(this)
viewModel = FirstViewModel(verifierRepository, preferences)
}
@Test
fun `get AppMinVersion from server`() {
val response = ServiceMocks.getVerificationRulesStringResponse()
every { preferences.validationRulesJson }.returns(response)
assertEquals( viewModel.getAppMinVersion(), "4.1.1")
}
@Test
fun `get Last Fetch Date when data not found`() {
every { preferences.dateLastFetch}.returns(-1L)
assertEquals( viewModel.getDateLastSync(), -1)
}
@Test
fun `get Last Fetch Date when data is present`() {
val currentDate = System.currentTimeMillis()
every { preferences.dateLastFetch}.returns(currentDate)
assertEquals( viewModel.getDateLastSync(), currentDate)
}
@Test
fun `get Certificate Fetch Status when the request is not ready`() {
val response = MutableLiveData(true)
val mockObserver = mockk<Observer<Boolean>>()
val slot = slot<Boolean>()
val listOfResponse = arrayListOf<Boolean>()
every { verifierRepository.getCertificateFetchStatus()}.returns(response)
every { mockObserver.onChanged(capture(slot)) } answers {
listOfResponse.add(slot.captured)
}
viewModel = FirstViewModel(verifierRepository, preferences)
viewModel.fetchStatus.observeForever(mockObserver)
assertEquals(true, listOfResponse[0])
}
@Test
fun `get Certificate Fetch Status when the request is ready`() {
val response = MutableLiveData(false)
val mockObserver = mockk<Observer<Boolean>>()
val slot = slot<Boolean>()
val listOfResponse = arrayListOf<Boolean>()
every { verifierRepository.getCertificateFetchStatus()}.returns(response)
every { mockObserver.onChanged(capture(slot)) } answers {
listOfResponse.add(slot.captured)
}
viewModel = FirstViewModel(verifierRepository, preferences)
viewModel.fetchStatus.observeForever(mockObserver)
assertEquals(false, listOfResponse[0])
}
} |
CREATE TABLE "SalariesFrance_13"(
"col_00" varchar(4) NOT NULL,
"col_01" varchar(46) NOT NULL,
"col_02" varchar(40),
"col_03" varchar(162) NOT NULL,
"col_04" varchar(2) NOT NULL,
"col_05" varchar(138) NOT NULL,
"col_06" decimal(4, 0),
"col_07" double,
"col_08" decimal(18, 14),
"col_09" double,
"col_10" double,
"col_11" double,
"col_12" double,
"col_13" double,
"col_14" double,
"col_15" double,
"col_16" double,
"col_17" double,
"col_18" double,
"col_19" varchar(5) NOT NULL,
"col_20" varchar(5),
"col_21" smallint NOT NULL,
"col_22" double,
"col_23" double,
"col_24" double,
"col_25" double,
"col_26" double,
"col_27" double,
"col_28" double,
"col_29" double,
"col_30" double,
"col_31" double,
"col_32" double,
"col_33" double,
"col_34" double,
"col_35" varchar(74),
"col_36" varchar(77),
"col_37" varchar(92),
"col_38" varchar(95),
"col_39" decimal(15, 13),
"col_40" double,
"col_41" smallint,
"col_42" smallint,
"col_43" varchar(33) NOT NULL,
"col_44" smallint NOT NULL,
"col_45" varchar(27) NOT NULL,
"col_46" varchar(1) NOT NULL,
"col_47" smallint NOT NULL,
"col_48" varchar(5),
"col_49" varchar(95),
"col_50" double,
"col_51" double,
"col_52" smallint,
"col_53" varchar(38),
"col_54" varchar(4) NOT NULL,
"col_55" varchar(35) NOT NULL,
"col_56" varchar(46) NOT NULL
);
|
feature 'testing initialization of server' do
scenario 'can run app and visit /' do
visit('/')
expect(page).to have_content('Current temperature')
end
end
|
/**
* Copyright 2015 www.alaraph.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This is my solution to problem: https://www.hackerrank.com/challenges/number-of-binary-search-tree
* [email protected]
*/
package com.alaraph.hackerrank.nbinstrees
import scala.io.StdIn.readLine
object Solution {
def main(args: Array[String]) {
val nLines = readLine.toInt
require(1 <= nLines && nLines <= 1000)
val input = (for (i <- 1 to nLines) yield readLine) map(_.toInt)
input foreach {
x => require (1 <= x && x <= 1000)
println(g(x) % (BigInt(10).pow(8)+7))
}
}
val cache = collection.mutable.Map[Int, BigInt]()
def g(N: Int): BigInt = {
def f(j: Int, acc: BigInt): BigInt =
j match {
case N => acc+g(N-1)
case 1 => f(j+1, acc+g(N-1))
case _ => f(j+1, acc+g(j-1)*g(N-j))
}
N match {
case 1 => 1
case _ => cache getOrElseUpdate(N, f(1, 0))
}
}
}
|
module Swaggerator
module Mockers
class ActionParamInterceptor
attr_reader :callstack
def initialize
@callstack= []
end
# This is one of the few good uses of method_misisng
# Overzealous programmers tend to overuse this to show off
# Their Reflection skills and make searching for code a pain
# for everyone
def method_missing(name, *args, &block)
@callstack << {name: name, args: args}
## Ignore the block given cuz we can't really do much with it
end
end
end
end
|
import * as express from "express";
import {isHelpScoutIntegrationEnabled, validateHelpScoutSignature} from "../../middleware";
import {
IFormItem,
IHelpScoutEmailNotFoundTemplate,
IHelpScoutFormItem,
IHelpScoutMainTemplate,
IUser,
User
} from "../../schema";
import bodyParser = require("body-parser");
import * as moment from "moment-timezone";
import {Template} from "../templates";
import * as Handlebars from "handlebars";
import * as Branches from "../../branch";
import {config} from "../../common";
export const helpScoutRoutes = express.Router({"mergeParams": true});
export type RequestWithRawBody = express.Request & { rawBody: string };
helpScoutRoutes.use(isHelpScoutIntegrationEnabled);
helpScoutRoutes.use(bodyParser.json({
verify: (req: RequestWithRawBody, res, buffer, encoding) => {
if (buffer && buffer.length) {
req.rawBody = buffer.toString(encoding || 'utf-8');
}
}
}));
helpScoutRoutes.use(validateHelpScoutSignature);
helpScoutRoutes.route("/userInfo").post(helpScoutUserInfoHandler);
async function findUserByEmail(email: string) {
return User.findOne({
email
});
}
function safe(text: string) {
return Handlebars.Utils.escapeExpression(text);
}
const EmailNotFoundTemplate = new Template<IHelpScoutEmailNotFoundTemplate>("helpscout/email_not_found.html");
const MainHelpScoutTemplate = new Template<IHelpScoutMainTemplate>("helpscout/main.html");
async function getFormAnswers(userData: IFormItem[], branch: string): Promise<IHelpScoutFormItem[]> {
let branchName = await Branches.BranchConfig.getCanonicalName(branch);
let questionBranch = branchName ? await Branches.BranchConfig.loadBranchFromDB(branchName) : null;
if (questionBranch) {
const hsQuestionNames = questionBranch?.questions
.filter(question => question.showInHelpScout)
.map(question => question.name);
return userData
.filter(question => hsQuestionNames.includes(question.name))
.map((question: IFormItem): IHelpScoutFormItem => {
let name = question.name.replace(/-/g, " ");
name = `${name.charAt(0).toUpperCase()}${name.slice(1)}`;
let prettyValue: string = "";
if (!question.value) {
prettyValue = "No response";
} else if (question.type === "file") {
const file = question.value as Express.Multer.File;
prettyValue = file.path;
} else if (question.value instanceof Array) {
prettyValue = question.value.join(", ");
} else {
prettyValue = question.value as string;
}
return {
...question,
prettyValue,
name
};
});
}
return [];
}
async function helpScoutUserInfoHandler(request: express.Request, response: express.Response) {
const email = safe(request.body.customer.email);
const user: IUser | null = await findUserByEmail(email);
if (!user) {
response.status(200).json({
html: EmailNotFoundTemplate.render({ email })
});
} else {
const helpScoutInput: IHelpScoutMainTemplate = {
name: user.name,
email: user.email,
uuid: user.uuid,
rootURL: config.server.rootURL,
applicationSubmitTime: user.applicationSubmitTime ? moment(user.applicationSubmitTime)
.format("DD-MMM-YYYY h:mm a") : undefined,
applicationQuestionsToShow: [],
confirmationQuestionsToShow: [],
applied: user.applied,
accepted: user.accepted,
confirmed: user.confirmed,
applicationBranch: user.applicationBranch,
confirmationBranch: user.confirmationBranch,
confirmationSubmitTime: user.confirmationSubmitTime ? moment(user.confirmationSubmitTime)
.format("DD-MMM-YYYY h:mm a") : undefined
};
if (user.applicationBranch && user.applicationData) {
helpScoutInput.applicationQuestionsToShow = await getFormAnswers(user.applicationData, user.applicationBranch);
}
if (user.confirmationBranch && user.confirmationData) {
helpScoutInput.confirmationQuestionsToShow = await getFormAnswers(user.confirmationData, user.confirmationBranch);
}
response.status(200).json({
"html": MainHelpScoutTemplate.render(helpScoutInput)
});
}
}
|
#!/bin/bash
usage() {
cat << EOF
Usage: $0 {pdffile|picture [picture]*} outputfile
example:
$0 test.pdf test.zip
$0 *.png env.yml.gz; gzip -d env.yml.gz
input linked qrcode pictures or a pdf with linked qrcodes.
decode the qrcodes and base32 decode the resulting output.
input order of pictures is not relevant for the output.
EOF
exit 1
}
if test "$2" = ""; then usage; fi
if test ! -f $1; then usage; fi
if ! which zbarimg > /dev/null; then
echo "error, no zbarimg found. try 'apt install zbar-tools'"
exit 1
fi
# get last parameter and remove from args
outputfile=${@:${#@}}
set -- "${@:1:$(($#-1))}"
zbarimg --raw -q "-S*.enable=0" "-Sqrcode.enable=1" $@ |
sort -n | cut -f 2 -d " " | tr -d "\n" |
python -c "import sys, base64; \
sys.stdout.write(base64.b32decode(sys.stdin.read()))" > $outputfile
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EtwStream
{
// shim of EtwStreamService
public static class EtwStreamService
{
static readonly CancellationTokenSource source = new CancellationTokenSource();
public static CancellationToken TerminateToken { get; }
public static ISubscriptionContainer Container { get; }
static EtwStreamService()
{
TerminateToken = source.Token;
Container = new SubscriptionContainer();
}
public static void CompleteService()
{
source.Cancel();
(Container as SubscriptionContainer)?.Dispose();
}
}
}
|
<?php
/****************************************************************************************************
*
* VIEWS/admin/varios/identidad.php
*
* Descripci�n:
* Vista que muestra la identidad
*
* Fecha de Creaci�n:
* 30/Octubre/2011
*
* Ultima actualizaci�n:
* 29/Noviembre/2011
*
* Autor:
* ISC Rogelio Castañeda Andrade
* [email protected]
* @rogelio_cas
*
****************************************************************************************************/
?>
<div class="cont_admin">
<div class="titulo"><?=$titulo?></div>
<div class="text">
<?php
$formulario = array(
// * Boton submit
'boton' => array (
'id' => 'modificar',
'name' => 'modificar',
'class' => 'in_button',
'onfocus' => 'hover(\'modificar\')'
),
// Texto
'texto' => array (
'name' => 'texto',
'id' => 'texto',
'value' => $tex,
'onfocus' => "hover('texto')",
)
);
echo form_open('',array('name' => 'formulario', 'id' => 'formulario'));
echo '<table class="tabla_form" width="980">';
echo '<tr><th class="text_form">Titulo: </th>';
echo '<td>'.$tit.'</td>';
echo '<tr><th class="text_form" valign="top" style="padding-top:10px">Texto: </th>';
echo '<td>'.form_textarea($formulario['texto']).'</td></tr>';
echo '</table><br />';
echo '<div style="width:980px; text-align:center;">'.form_submit($formulario['boton'],'Modificar').'</div>';
echo form_close();
?>
</div>
</div> |
export const ADD_CATEGORY_REQUEST = "ADD_CATEGORY_REQUEST";
export const ADD_CATEGORY_SUCCESS = "ADD_CATEGORY_SUCCESS";
export const ADD_CATEGORY_FAILURE = "ADD_CATEGORY_FAILURE";
export const GET_CATEGORIES_REQUEST = "GET_CATEGORIES_REQUEST";
export const GET_CATEGORIES_SUCCESS = "GET_CATEGORIES_SUCCESS";
export const GET_CATEGORIES_FAILURE = "GET_CATEGORIES_FAILURE";
export const DELETE_CATEGORIES_REQUEST = "DELETE_CATEGORIES_REQUEST";
export const DELETE_CATEGORIES_SUCCESS = "DELETE_CATEGORIES_SUCCESS";
export const DELETE_CATEGORIES_FAILURE = "DELETE_CATEGORIES_FAILURE";
|
library tool.dev;
import 'dart:async';
import 'package:dart_dev/dart_dev.dart' show dev, config;
Future<Null> main(List<String> args) async {
const directories = const <String>[
'lib/',
'lib/src/',
'test/unit/',
];
config.format..lineLength = 80;
config.analyze
..strong = true
..fatalWarnings = false
..entryPoints = directories;
config.test
..concurrency = 1
..unitTests = [
'test/unit/',
];
config.coverage
..html = true
..reportOn = ['lib/'];
await dev(args);
}
|
package com.raxdenstudios.commons.permissions.model
import androidx.annotation.StringRes
import com.raxdenstudios.commons.permissions.R
sealed class RationaleDialog(
@StringRes val reason: Int,
@StringRes val reasonDescription: Int,
@StringRes val acceptLabel: Int,
@StringRes val deniedLabel: Int
) {
object Camera : RationaleDialog(
R.string.permission_rationale_camera_title,
R.string.permission_rationale_camera_message,
R.string.permission_rationale_camera_positive,
R.string.permission_rationale_camera_negative,
)
object AccessFineLocation : RationaleDialog(
R.string.permission_rationale_access_fine_location_title,
R.string.permission_rationale_access_fine_location_message,
R.string.permission_rationale_access_fine_location_positive,
R.string.permission_rationale_access_fine_location_negative,
)
}
|
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller, io } = app;
router.get('/', controller.home.index);
// https://eggjs.org/zh-cn/tutorials/socketio.html
// 当服务器收到客户端的addMessage时间之后,会交给addMessage方法来处理
// 向服务器发射一个新的消息,并且让服务器广播给所有的客户端
io.route('addMessage', io.controller.room.addMessage);
// 获取所有的历史消息
io.route("getAllMessages", io.controller.room.getAllMessages);
};
|
import {
getCenterXCoord,
getInnerLeftCoord,
getInnerRightCoord,
getLeftCoord,
getRightCoord,
XCoordConfig,
} from "./getCoord";
import { FixedPositionOptions, HorizontalPosition } from "./types";
/**
* @private
*/
interface XPosition {
left: number;
right?: number;
width?: number;
minWidth?: number;
actualX: HorizontalPosition;
}
/**
* @private
*/
export interface FixConfig extends XCoordConfig {
vwMargin: number;
screenRight: number;
disableSwapping: boolean;
}
/**
* @private
*/
interface Options
extends Required<
Pick<
FixedPositionOptions,
"vwMargin" | "xMargin" | "width" | "disableSwapping"
>
> {
x: HorizontalPosition;
vw: number;
elWidth: number;
initialX?: number;
containerRect: DOMRect | ClientRect;
}
/**
* Attempts to position the fixed element so that it will appear to the left of
* the container element but also within the viewport boundaries. When swapping
* is enabled, it will attempt to swap to the right position if it can't fit
* within the viewport to the left. If it can't fit in the viewport even after
* being swapped to the right or swapping is disabled, it will be positioned to
* the viewport left boundary.
*
* @private
*/
export function createAnchoredLeft(config: FixConfig): XPosition {
const { vwMargin, screenRight, elWidth, disableSwapping } = config;
let left = getLeftCoord(config);
let actualX: HorizontalPosition = "left";
if (left >= vwMargin) {
return { actualX, left };
}
const swappedLeft = getRightCoord(config);
if (disableSwapping || swappedLeft + elWidth > screenRight) {
left = vwMargin;
} else {
left = swappedLeft;
actualX = "right";
}
return { actualX, left };
}
/**
* Attempts to position the fixed element so that it will appear to the
* inner-left of the container element but also within the viewport boundaries.
* When swapping is enabled, it will attempt to swap to the right position if it
* can't fit within the viewport to the left. If it can't fit in the viewport
* even after being swapped to the right or swapping is disabled, it will be
* positioned to the viewport left boundary.
*
* @private
*/
export function createAnchoredInnerLeft(config: FixConfig): XPosition {
const { vwMargin, screenRight, elWidth, disableSwapping } = config;
let left = getInnerLeftCoord(config);
let actualX: HorizontalPosition = "inner-left";
if (left + elWidth <= screenRight) {
return { actualX, left };
}
const swappedLeft = getInnerRightCoord(config);
if (disableSwapping || swappedLeft < vwMargin) {
left = vwMargin;
} else {
left = swappedLeft;
actualX = "inner-right";
}
return { actualX, left };
}
/**
* Attempts to position the fixed element so that it will appear at the center
* of the container element but also within the viewport boundaries. If the
* centered element can't fit within the viewport, it will use the vwMargin
* value if it overflowed to the left, it'll position to the screen right
* boundary.
*
* @private
*/
export function createAnchoredCenter(config: FixConfig): XPosition {
const { vwMargin, screenRight, elWidth } = config;
let left = getCenterXCoord(config);
if (left < vwMargin) {
left = vwMargin;
} else if (left + elWidth > screenRight || left < vwMargin) {
left = screenRight - elWidth;
}
return { actualX: "center", left };
}
/**
* Attempts to position the fixed element so that it will appear to the
* inner-right of the container element but also within the viewport boundaries.
* When swapping is enabled, it will attempt to swap to the inner-left position
* if it can't fit within the viewport to the right. If it can't fit in the
* viewport even after being swapped to the left or swapping is disabled, it
* will be positioned to the viewport right boundary.
*
* @private
*/
export function createAnchoredInnerRight(config: FixConfig): XPosition {
const { screenRight, vwMargin, elWidth, disableSwapping } = config;
let left = getInnerRightCoord(config);
let actualX: HorizontalPosition = "inner-right";
if (left >= vwMargin) {
return { actualX, left };
}
const swappedLeft = getInnerLeftCoord(config);
if (disableSwapping || swappedLeft + elWidth > screenRight) {
left = screenRight - elWidth;
} else {
left = swappedLeft;
actualX = "inner-left";
}
return { actualX, left };
}
/**
* Attempts to position the fixed element so that it will appear to the right of
* the container element but also within the viewport boundaries. When swapping
* is enabled, it will attempt to swap to the left position if it can't fit
* within the viewport to the right. If it can't fit in the viewport even after
* being swapped to the left or swapping is disabled, it will be positioned to
* the viewport right boundary.
*
* @private
*/
export function createAnchoredRight(config: FixConfig): XPosition {
const { screenRight, vwMargin, elWidth, disableSwapping } = config;
let left = getRightCoord(config);
let actualX: HorizontalPosition = "right";
if (left + elWidth <= screenRight) {
return { actualX, left };
}
const swappedLeft = getLeftCoord(config);
if (disableSwapping || swappedLeft < vwMargin) {
left = screenRight - elWidth;
} else {
left = swappedLeft;
actualX = "left";
}
return { actualX, left };
}
interface EqualWidthOptions
extends Pick<
Options,
| "x"
| "vw"
| "elWidth"
| "xMargin"
| "vwMargin"
| "containerRect"
| "initialX"
> {
isMinWidth: boolean;
}
/**
* @private
*/
export function createEqualWidth({
x,
vw,
elWidth,
xMargin,
vwMargin,
initialX,
containerRect,
isMinWidth,
}: EqualWidthOptions): XPosition {
const left = initialX ?? containerRect.left + xMargin;
let width: number | undefined = containerRect.width - xMargin * 2;
let minWidth: number | undefined;
let right: number | undefined;
if (isMinWidth) {
minWidth = width;
width = undefined;
if (left + elWidth > vw - vwMargin) {
right = vwMargin;
}
}
// going to assume that the container element is visible in the DOM and just
// make the fixed element have the same left and right corners
return {
left,
right,
width,
minWidth,
actualX: x,
};
}
/**
* Creates the horizontal position for a fixed element with the provided
* options.
* @private
*/
export function createHorizontalPosition({
x,
vw,
vwMargin,
xMargin,
width,
elWidth,
initialX,
containerRect,
disableSwapping,
}: Options): XPosition {
if (width === "min" || width === "equal") {
return createEqualWidth({
x,
vw,
vwMargin,
xMargin,
elWidth,
initialX,
containerRect,
isMinWidth: width === "min",
});
}
if (elWidth > vw - vwMargin * 2) {
// if the element's width is greater than the viewport's width minus the
// margin on both sides, just make the element span the entire viewport with
// the margin
return {
left: vwMargin,
right: vwMargin,
actualX: x,
};
}
const config: FixConfig = {
vwMargin,
xMargin,
elWidth,
initialX,
screenRight: vw - vwMargin,
containerRect,
disableSwapping,
};
switch (x) {
case "left":
return createAnchoredLeft(config);
case "inner-left":
return createAnchoredInnerLeft(config);
case "center":
return createAnchoredCenter(config);
case "inner-right":
return createAnchoredInnerRight(config);
case "right":
return createAnchoredRight(config);
default:
throw new Error("This should never happen");
}
}
|
//! Provide Host I/O operations for the target.
use bitflags::bitflags;
use crate::arch::Arch;
use crate::target::Target;
bitflags! {
/// Host flags for opening files.
///
/// Extracted from the GDB documentation at
/// [Open Flags](https://sourceware.org/gdb/current/onlinedocs/gdb/Open-Flags.html#Open-Flags)
pub struct HostIoOpenFlags: u32 {
/// A read-only file.
const O_RDONLY = 0x0;
/// A write-only file.
const O_WRONLY = 0x1;
/// A read-write file.
const O_RDWR = 0x2;
/// Append to an existing file.
const O_APPEND = 0x8;
/// Create a non-existent file.
const O_CREAT = 0x200;
/// Truncate an existing file.
const O_TRUNC = 0x400;
/// Exclusive access.
const O_EXCL = 0x800;
}
}
bitflags! {
/// Host file permissions.
///
/// Extracted from the GDB documentation at
/// [mode_t Values](https://sourceware.org/gdb/current/onlinedocs/gdb/mode_005ft-Values.html#mode_005ft-Values)
pub struct HostIoOpenMode: u32 {
/// A regular file.
const S_IFREG = 0o100000;
/// A directory.
const S_IFDIR = 0o40000;
/// User read permissions.
const S_IRUSR = 0o400;
/// User write permissions.
const S_IWUSR = 0o200;
/// User execute permissions.
const S_IXUSR = 0o100;
/// Group read permissions.
const S_IRGRP = 0o40;
/// Group write permissions
const S_IWGRP = 0o20;
/// Group execute permissions.
const S_IXGRP = 0o10;
/// World read permissions.
const S_IROTH = 0o4;
/// World write permissions
const S_IWOTH = 0o2;
/// World execute permissions.
const S_IXOTH = 0o1;
}
}
/// Data returned by a host fstat request.
///
/// Extracted from the GDB documentation at
/// [struct stat](https://sourceware.org/gdb/current/onlinedocs/gdb/struct-stat.html#struct-stat)
#[derive(Debug)]
pub struct HostIoStat {
/// The device.
pub st_dev: u32,
/// The inode.
pub st_ino: u32,
/// Protection bits.
pub st_mode: HostIoOpenMode,
/// The number of hard links.
pub st_nlink: u32,
/// The user id of the owner.
pub st_uid: u32,
/// The group id of the owner.
pub st_gid: u32,
/// The device type, if an inode device.
pub st_rdev: u32,
/// The size of the file in bytes.
pub st_size: u64,
/// The blocksize for the filesystem.
pub st_blksize: u64,
/// The number of blocks allocated.
pub st_blocks: u64,
/// The last time the file was accessed, in seconds since the epoch.
pub st_atime: u32,
/// The last time the file was modified, in seconds since the epoch.
pub st_mtime: u32,
/// The last time the file was changed, in seconds since the epoch.
pub st_ctime: u32,
}
/// Select the filesystem vFile operations will operate on. Used by vFile setfs
/// command.
#[derive(Debug)]
pub enum FsKind {
/// Select the filesystem as seen by the remote stub.
Stub,
/// Select the filesystem as seen by process pid.
Pid(crate::common::Pid),
}
/// Errno values for Host I/O operations.
///
/// Extracted from the GDB documentation at
/// <https://sourceware.org/gdb/onlinedocs/gdb/Errno-Values.html>
#[derive(Debug)]
pub enum HostIoErrno {
/// Operation not permitted (POSIX.1-2001).
EPERM = 1,
/// No such file or directory (POSIX.1-2001).
///
/// Typically, this error results when a specified pathname does not exist,
/// or one of the components in the directory prefix of a pathname does not
/// exist, or the specified pathname is a dangling symbolic link.
ENOENT = 2,
/// Interrupted function call (POSIX.1-2001); see signal(7).
EINTR = 4,
/// Bad file descriptor (POSIX.1-2001).
EBADF = 9,
/// Permission denied (POSIX.1-2001).
EACCES = 13,
/// Bad address (POSIX.1-2001).
EFAULT = 14,
/// Device or resource busy (POSIX.1-2001).
EBUSY = 16,
/// File exists (POSIX.1-2001).
EEXIST = 17,
/// No such device (POSIX.1-2001).
ENODEV = 19,
/// Not a directory (POSIX.1-2001).
ENOTDIR = 20,
/// Is a directory (POSIX.1-2001).
EISDIR = 21,
/// Invalid argument (POSIX.1-2001).
EINVAL = 22,
/// Too many open files in system (POSIX.1-2001). On Linux, this is probably
/// a result of encountering the /proc/sys/fs/file-max limit (see proc(5)).
ENFILE = 23,
/// Too many open files (POSIX.1-2001). Commonly caused by exceeding the
/// RLIMIT_NOFILE resource limit described in getrlimit(2).
EMFILE = 24,
/// File too large (POSIX.1-2001).
EFBIG = 27,
/// No space left on device (POSIX.1-2001).
ENOSPC = 28,
/// Invalid seek (POSIX.1-2001).
ESPIPE = 29,
/// Read-only filesystem (POSIX.1-2001).
EROFS = 30,
/// Filename too long (POSIX.1-2001).
ENAMETOOLONG = 91,
/// Unknown errno - there may not be a GDB mapping for this value
EUNKNOWN = 9999,
}
/// The error type for Host I/O operations.
pub enum HostIoError<E> {
/// An operation-specific non-fatal error code.
///
/// See [`HostIoErrno`] for more details.
Errno(HostIoErrno),
/// A target-specific fatal error.
///
/// **WARNING:** Returning this error will immediately halt the target's
/// execution and return a `GdbStubError::TargetError`!
///
/// Note that returning this error will _not_ notify the GDB client that the
/// debugging session has been terminated, making it possible to resume
/// execution after resolving the error and/or setting up a post-mortem
/// debugging environment.
Fatal(E),
}
/// When the `std` feature is enabled, `HostIoError` implements
/// `From<std::io::Error>`, mapping [`std::io::ErrorKind`] to the appropriate
/// [`HostIoErrno`] when possible, and falling back to [`HostIoErrno::EUNKNOWN`]
/// when no mapping exists.
#[cfg(feature = "std")]
impl<E> From<std::io::Error> for HostIoError<E> {
fn from(e: std::io::Error) -> HostIoError<E> {
use std::io::ErrorKind::*;
let errno = match e.kind() {
PermissionDenied => HostIoErrno::EPERM,
NotFound => HostIoErrno::ENOENT,
Interrupted => HostIoErrno::EINTR,
AlreadyExists => HostIoErrno::EEXIST,
InvalidInput => HostIoErrno::EINVAL,
_ => HostIoErrno::EUNKNOWN,
};
HostIoError::Errno(errno)
}
}
/// A specialized `Result` type for Host I/O operations. Supports reporting
/// non-fatal errors back to the GDB client.
///
/// See [`HostIoError`] for more details.
pub type HostIoResult<T, Tgt> = Result<T, HostIoError<<Tgt as Target>::Error>>;
/// Target Extension - Perform I/O operations on host
pub trait HostIo: Target {
/// Support `open` operation.
#[inline(always)]
fn support_open(&mut self) -> Option<HostIoOpenOps<Self>> {
None
}
/// Support `close` operation.
#[inline(always)]
fn support_close(&mut self) -> Option<HostIoCloseOps<Self>> {
None
}
/// Support `pread` operation.
#[inline(always)]
fn support_pread(&mut self) -> Option<HostIoPreadOps<Self>> {
None
}
/// Support `pwrite` operation.
#[inline(always)]
fn support_pwrite(&mut self) -> Option<HostIoPwriteOps<Self>> {
None
}
/// Support `fstat` operation.
#[inline(always)]
fn support_fstat(&mut self) -> Option<HostIoFstatOps<Self>> {
None
}
/// Support `unlink` operation.
#[inline(always)]
fn support_unlink(&mut self) -> Option<HostIoUnlinkOps<Self>> {
None
}
/// Support `readlink` operation.
#[inline(always)]
fn support_readlink(&mut self) -> Option<HostIoReadlinkOps<Self>> {
None
}
/// Support `setfs` operation.
#[inline(always)]
fn support_setfs(&mut self) -> Option<HostIoSetfsOps<Self>> {
None
}
}
define_ext!(HostIoOps, HostIo);
/// Nested Target Extension - Host I/O open operation.
pub trait HostIoOpen: HostIo {
/// Open a file at `filename` and return a file descriptor for it, or return
/// [`HostIoError::Errno`] if an error occurs.
///
/// `flags` are the flags used when opening the file (see
/// [`HostIoOpenFlags`]), and `mode` is the mode used if the file is
/// created (see [`HostIoOpenMode`]).
fn open(
&mut self,
filename: &[u8],
flags: HostIoOpenFlags,
mode: HostIoOpenMode,
) -> HostIoResult<u32, Self>;
}
define_ext!(HostIoOpenOps, HostIoOpen);
/// Nested Target Extension - Host I/O close operation.
pub trait HostIoClose: HostIo {
/// Close the open file corresponding to `fd`.
fn close(&mut self, fd: u32) -> HostIoResult<(), Self>;
}
define_ext!(HostIoCloseOps, HostIoClose);
/// Nested Target Extension - Host I/O pread operation.
pub trait HostIoPread: HostIo {
/// Read data from the open file corresponding to `fd`.
///
/// Up to `count` bytes will be read from the file, starting at `offset`
/// relative to the start of the file.
///
/// Return the number of bytes written into `buf` (which may be less than
/// `count`).
///
/// If `offset` is greater than the length of the underlying data, return
/// `Ok(0)`.
fn pread(
&mut self,
fd: u32,
count: usize,
offset: u64,
buf: &mut [u8],
) -> HostIoResult<usize, Self>;
}
define_ext!(HostIoPreadOps, HostIoPread);
/// Nested Target Extension - Host I/O pwrite operation.
pub trait HostIoPwrite: HostIo {
/// Write `data` to the open file corresponding to `fd`.
///
/// Start the write at `offset` from the start of the file.
///
/// Return the number of bytes written, which may be shorter
/// than the length of data, or [`HostIoError::Errno`] if an error occurred.
fn pwrite(
&mut self,
fd: u32,
offset: <Self::Arch as Arch>::Usize,
data: &[u8],
) -> HostIoResult<<Self::Arch as Arch>::Usize, Self>;
}
define_ext!(HostIoPwriteOps, HostIoPwrite);
/// Nested Target Extension - Host I/O fstat operation.
pub trait HostIoFstat: HostIo {
/// Get information about the open file corresponding to `fd`.
///
/// On success return a [`HostIoStat`] struct.
/// Return [`HostIoError::Errno`] if an error occurs.
fn fstat(&mut self, fd: u32) -> HostIoResult<HostIoStat, Self>;
}
define_ext!(HostIoFstatOps, HostIoFstat);
/// Nested Target Extension - Host I/O unlink operation.
pub trait HostIoUnlink: HostIo {
/// Delete the file at `filename` on the target.
fn unlink(&mut self, filename: &[u8]) -> HostIoResult<(), Self>;
}
define_ext!(HostIoUnlinkOps, HostIoUnlink);
/// Nested Target Extension - Host I/O readlink operation.
pub trait HostIoReadlink: HostIo {
/// Read value of symbolic link `filename` on the target.
///
/// Return the number of bytes written into `buf`.
///
/// Unlike most other Host IO handlers, if the resolved file path exceeds
/// the length of the provided `buf`, the target should NOT return a
/// partial response, and MUST return a `Err(HostIoErrno::ENAMETOOLONG)`.
fn readlink(&mut self, filename: &[u8], buf: &mut [u8]) -> HostIoResult<usize, Self>;
}
define_ext!(HostIoReadlinkOps, HostIoReadlink);
/// Nested Target Extension - Host I/O setfs operation.
pub trait HostIoSetfs: HostIo {
/// Select the filesystem on which vFile operations with filename arguments
/// will operate. This is required for GDB to be able to access files on
/// remote targets where the remote stub does not share a common filesystem
/// with the inferior(s).
///
/// See [`FsKind`] for the meaning of `fs`.
///
/// If setfs indicates success, the selected filesystem remains selected
/// until the next successful setfs operation.
fn setfs(&mut self, fs: FsKind) -> HostIoResult<(), Self>;
}
define_ext!(HostIoSetfsOps, HostIoSetfs);
|
// !LANGUAGE: -JvmStaticInInterface
// !DIAGNOSTICS: -UNUSED_VARIABLE
class A {
companion object {
@JvmStatic fun a1() {
}
}
object A {
@JvmStatic fun a2() {
}
}
fun test() {
val s = object {
@JvmStatic fun a3() {
}
}
}
@JvmStatic fun a4() {
}
}
interface B {
companion object {
@JvmStatic fun a1() {
}
}
object A {
@JvmStatic fun a2() {
}
}
fun test() {
val s = object {
@JvmStatic fun a3() {
}
}
}
@JvmStatic fun a4() {
}
} |
use super::browser_info;
use super::*;
use alfred::ItemBuilder;
use std::io::Write;
/// Providing this command with a URL will try to remove the related bookmark from Pinboard.
/// If no URL is provided, this command will fetch browser's tab info and show and Alfred item that
/// can be used for deletion in next step.
///
// TODO: right now we accept deleting tag & url at the same time. If user asks to delete a tag
// only, this function will automatically grab browser's url and return an Alfred item containing
// it while deleting the given tag as well. I believe these two options should be made exclusively
// mutual.
impl<'api, 'pin> Runner<'api, 'pin> {
pub fn delete(&mut self, cmd: SubCommand) {
debug!("Starting in delete");
let (url, tag) = match cmd {
SubCommand::Delete { url, tag } => (url, tag),
_ => unreachable!(),
};
if let Some(tag) = tag {
debug!(" tag: {}", tag);
if let Err(e) = self.pinboard.as_ref().unwrap().delete_tag(tag) {
let _ = io::stdout()
.write(format!("Error: {}", e).as_ref())
.expect("Couldn't write to stdout");
process::exit(1);
} else {
let _ = io::stdout()
.write(b"Successfully deleted tag.")
.expect("Couldn't write to stdout");
if self.config.as_ref().unwrap().auto_update_cache {
self.update_cache();
}
}
return;
}
if let Some(url) = url {
debug!(" url: {}", url);
if let Err(e) = self.pinboard.as_ref().unwrap().delete(&url) {
let _ = io::stdout()
.write(format!("Error: {}", e).as_ref())
.expect("Couldn't write to stdout");
process::exit(1);
} else {
let _ = io::stdout()
.write(b"Successfully deleted bookmark.")
.expect("Couldn't write to stdout");
if self.config.as_ref().unwrap().auto_update_cache {
self.update_cache();
}
}
} else {
let tab_info;
let item = match browser_info::get() {
Ok(browser_tab_info) => {
tab_info = browser_tab_info;
ItemBuilder::new(tab_info.title.as_str())
.subtitle(tab_info.url.as_str())
.arg(tab_info.url.as_str())
.quicklook_url(tab_info.url.as_str())
.text_large_type(tab_info.title.as_str())
.text_copy(tab_info.url.as_str())
.icon_path("bookmark-delete.png")
.into_item()
}
Err(e) => {
warn!("Couldn't get browser info: {:?}", e);
ItemBuilder::new("Couldn't get browser's info!")
.subtitle("Error")
.icon_path("erroricon.icns")
.into_item()
}
};
if let Err(e) = self.write_output_items(vec![item]) {
error!("delete: Couldn't write to Alfred: {:?}", e);
}
}
}
}
|
package repo
import (
"encoding/json"
"fmt"
"io/ioutil"
"messfar-telegram/domain"
"messfar-telegram/util"
"net/http"
"github.com/pkg/errors"
)
type TelgramService struct {
URL string
BotToken string
}
func NewTelgramService(URL, botToken string) domain.TelegramService {
return &TelgramService{
URL: URL,
BotToken: botToken,
}
}
func (service *TelgramService) GetFileInfo(fileID string) (*domain.GetFileInfoResponse, error) {
res, err := http.Get(fmt.Sprintf("%s/bot%s/getFile?file_id=%s", service.URL, service.BotToken, fileID))
if err != nil {
return nil, errors.Wrap(err, "get req fail")
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrap(err, "read body fail")
}
var fileInfoResponse domain.GetFileInfoResponse
json.Unmarshal(body, &fileInfoResponse)
return &fileInfoResponse, nil
}
func (service *TelgramService) DownloadFile(filePath string) ([]byte, error) {
fileBytes, err := util.DownloadFile(fmt.Sprintf("%s/file/bot%s/%s", service.URL, service.BotToken, filePath))
if err != nil {
return nil, errors.Wrap(err, "download file failed")
}
return fileBytes, nil
}
|
# frozen_string_literal: true
module FinnhubServices
# ApiError is a generic error that occurs due to an error after a request to finnhub.
class ApiError < StandardError
def initialize(msg = nil)
super
end
# TooManyRequests is an error that occurs due to too many requests to finnhub.
# The user must stop executing requests within 1 minute if it receives this error.
class TooManyRequests < ApiError
def initialize
super('Finnhub has returned 429 error')
end
end
# UnknownSymbol is an error that occurs due to failed attempt on finding the symbol on finnhub.
class UnknownSymbol < ApiError
def initialize(symbol)
super("Finnhub couldn't find symbol #{symbol}")
end
end
end
end
|
<?php
namespace Crater\Http\Controllers\V1\Admin\Payment;
use Crater\Http\Controllers\Controller;
use Crater\Http\Requests\PaymentMethodRequest;
use Crater\Http\Resources\PaymentMethodResource;
use Crater\Models\PaymentMethod;
use Illuminate\Http\Request;
class PaymentMethodsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$this->authorize('viewAny', PaymentMethod::class);
$limit = $request->has('limit') ? $request->limit : 5;
$paymentMethods = PaymentMethod::applyFilters($request->all())
->where('type', PaymentMethod::TYPE_GENERAL)
->whereCompany()
->latest()
->paginateData($limit);
return PaymentMethodResource::collection($paymentMethods);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(PaymentMethodRequest $request)
{
$this->authorize('create', PaymentMethod::class);
$paymentMethod = PaymentMethod::createPaymentMethod($request);
return new PaymentMethodResource($paymentMethod);
}
/**
* Display the specified resource.
*
* @param \Crater\Models\PaymentMethod $paymentMethod
* @return \Illuminate\Http\Response
*/
public function show(PaymentMethod $paymentMethod)
{
$this->authorize('view', $paymentMethod);
return new PaymentMethodResource($paymentMethod);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \Crater\Models\PaymentMethod $paymentMethod
* @return \Illuminate\Http\Response
*/
public function update(PaymentMethodRequest $request, PaymentMethod $paymentMethod)
{
$this->authorize('update', $paymentMethod);
$paymentMethod->update($request->getPaymentMethodPayload());
return new PaymentMethodResource($paymentMethod);
}
/**
* Remove the specified resource from storage.
*
* @param \Crater\Models\PaymentMethod $paymentMethod
* @return \Illuminate\Http\Response
*/
public function destroy(PaymentMethod $paymentMethod)
{
$this->authorize('delete', $paymentMethod);
if ($paymentMethod->payments()->exists()) {
return respondJson('payments_attached', 'Payments Attached.');
}
if ($paymentMethod->expenses()->exists()) {
return respondJson('expenses_attached', 'Expenses Attached.');
}
$paymentMethod->delete();
return response()->json([
'success' => 'Payment method deleted successfully',
]);
}
}
|
import { Scene } from "phaser";
import { GameStatsService } from 'src/app/game-stats.service';
import { Score } from '../domain/score';
export class MainScene extends Scene
{
private phaserSprite: Phaser.GameObjects.Sprite;
private platforms : Phaser.Physics.Arcade.StaticGroup;
private player : any;// Phaser.Physics.Arcade.Sprite;
private cursors //: Phaser.Input.Keyboard.CursorKeys;
private escape : Phaser.Input.Keyboard.Key;
private stars : Phaser.Physics.Arcade.Group;
constructor()
{
super("main");
GameStatsService.instance.keyPressed.subscribe((key) => {
if (key === 'gravity_inverse')
{
if (this.physics.world.gravity.y > 0)
this.physics.world.gravity.y = -900;
else
this.physics.world.gravity.y = 300;
}
});
}
preload(): void {
var width = this.sys.canvas.width;
var height = this.sys.canvas.height;
this.load.image('ground', '/assets/game/platform.png');
this.load.image('star', '/assets/game/star.png');
this.load.image('bomb', '/assets/game/bomb.png');
this.load.spritesheet('dude', '/assets/game/dude.png', { frameWidth: 32, frameHeight: 48 });
var texture = this.textures.createCanvas('gradient', width, height);
var context = texture.getContext();
var grd = context.createLinearGradient(0, 0, width, height); // ERROR LINE
grd.addColorStop(0, '#FFFFFF');
grd.addColorStop(1, '#004CB3');
context.fillStyle = grd;
context.fillRect(0, 0, width, height);
// Call this if running under WebGL, or you'll see nothing change
texture.refresh();
}
create(): void {
var width = this.sys.canvas.width;
var height = this.sys.canvas.height;
this.add.image((width / 2),(height / 2), 'gradient');
this.platforms = this.physics.add.staticGroup();
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
this.platforms.create(600, 400, 'ground');
this.platforms.create(50, 250, 'ground');
this.platforms.create(750, 220, 'ground');
this.player = this.physics.add.sprite((width / 2),0, 'dude');
this.player.setBounce(0.2);
this.player.setCollideWorldBounds(true);
this.player.body.setGravityY(300);
this.stars = this.physics.add.group({
key: 'star',
repeat: 11,
setXY: { x: 12, y: 0, stepX: 70 }
});
this.stars.children.iterate(function (child : any) {
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
this.physics.add.collider(this.stars, this.platforms);
this.physics.add.collider(this.player, this.platforms);
this.physics.add.overlap(this.player, this.stars, this.collectStar, null, this);
this._createAnimations();
this.cursors = this.input.keyboard.createCursorKeys();
}
private collectStar(player, star)
{
star.disableBody(true, true);
let score = new Score();
score.Stars = 1;
GameStatsService.instance.emitScore(score);
}
private lastKey : string = "";
update()
{
if (this.cursors.left.isDown)
{
if (this.lastKey !== 'left') {
GameStatsService.instance.emitKey('left');
this.lastKey = 'left';
}
this.player.setVelocityX(-160);
this.player.anims.play('left', true);
}
else if (this.cursors.right.isDown)
{
if (this.lastKey !== 'right') {
GameStatsService.instance.emitKey('right');
this.lastKey = 'right';
}
this.player.setVelocityX(160);
this.player.anims.play('right', true);
}
else
{
if (this.lastKey !== 'none') {
GameStatsService.instance.emitKey('none');
this.lastKey = 'none';
}
this.player.setVelocityX(0);
this.player.anims.play('turn');
}
if (this.cursors.up.isDown && this.player.body.touching.down)
{
if (this.lastKey !== 'up') {
GameStatsService.instance.emitKey('up');
this.lastKey = 'up';
}
this.player.setVelocityY(-330);
}
}
_createAnimations()
{
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', {
start: 0,
end: 3
}),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [{
key: 'dude',
frame: 4
}],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', {
start: 5,
end: 8
}),
frameRate: 10,
repeat: -1
});
}
} |
package com.emc.mongoose.api.model.storage;
/**
Created by andrey on 14.03.17.
*/
public final class BasicCredential
implements Credential {
private final String uid;
private final String secret;
protected BasicCredential(final String uid, final String secret) {
this.uid = uid;
this.secret = secret;
}
@Override
public final String getUid() {
return uid;
}
@Override
public final String getSecret() {
return secret;
}
@Override
public final boolean equals(final Object other) {
if(!(other instanceof BasicCredential)) {
return false;
}
final BasicCredential otherCred = (BasicCredential) other;
if(uid != null) {
if(uid.equals(otherCred.uid)) {
if(secret != null) {
return secret.equals(otherCred.secret);
} else if(otherCred.secret == null) {
return true;
}
}
} else {
if(otherCred.uid == null) {
if(secret != null) {
return secret.equals(otherCred.secret);
} else if(otherCred.secret == null) {
return true;
}
}
}
return false;
}
@Override
public final int hashCode() {
return (uid == null ? 0 : uid.hashCode()) ^ (secret == null ? 0 : secret.hashCode());
}
}
|
from django_otp.oath import TOTP
import time
class TOTPVerification:
def __init__(self, key):
# secret key that will be used to generate a token,
# User can provide a custom value to the key.
self.key = key
# counter with which last token was verified.
# Next token must be generated at a higher counter value.
self.last_verified_counter = -1
# this value will return True, if a token has been successfully
# verified.
self.verified = False
# number of digits in a token. Default is 6
self.number_of_digits = 6
# validity period of a token. Default is 30 second.
self.token_validity_period = 30
def totp_obj(self):
# create a TOTP object
totp = TOTP(key=self.key,
step=self.token_validity_period,
digits=self.number_of_digits)
# the current time will be used to generate a counter
totp.time = time.time()
return totp
def generate_token(self):
# get the TOTP object and use that to create token
totp = self.totp_obj()
# token can be obtained with `totp.token()`
token = str(totp.token()).zfill(6)
return token
def verify_token(self, token, tolerance=0):
try:
# convert the input token to integer
token = int(token)
except ValueError:
# return False, if token could not be converted to an integer
self.verified = False
else:
totp = self.totp_obj()
# check if the current counter value is higher than the value of
# last verified counter and check if entered token is correct by
# calling totp.verify_token()
if ((totp.t() > self.last_verified_counter) and
(totp.verify(token, tolerance=tolerance))):
# if the condition is true, set the last verified counter value
# to current counter value, and return True
self.last_verified_counter = totp.t()
self.verified = True
else:
# if the token entered was invalid or if the counter value
# was less than last verified counter, then return False
self.verified = False
return self.verified
# if __name__ == '__main__':
# # verify token the normal way
# phone1 = TOTPVerification(random_hex(20))
# while True:
# generated_token = phone1.generate_token()
# print("Generated token is: ", generated_token)
# token = int(input("Enter token: "))
# print(phone1.verify_token(token))
|
:- module(matcher,[functionMatcher/6]).
:- use_module(canon).
:- use_module(errors).
:- use_module(types).
:- use_module(misc).
:- use_module(location).
:- use_module(freevars).
:- use_module(terms).
:- use_module(transutils).
functionMatcher(Lc,Ar,Nm,Tp,Eqns,fnDef(Lc,Nm,Tp,NVrs,Reslt)) :-
genVars(Ar,NVrs),
makeTriples(Eqns,0,Tpls),
genRaise(Lc,Error),
matchTriples(Lc,NVrs,Tpls,Error,Reslt),!.
functionMatcher(Lc,_Ar,Nm,Tp,_Eqns,fnDef(Lc,Nm,Tp,[],enum("void"))) :-
reportError("(internal) failed to construct function for %s",[Nm],Lc).
genRaise(Lc,error(Lc,"no matches")).
matchTriples(_,[],Tps,Deflt,Reslt) :-
conditionalize(Tps,Deflt,Reslt).
matchTriples(Lc,Vrs,Tpls,Deflt,Reslt) :-
partitionTriples(Tpls,Segments),
matchSegments(Segments,Vrs,Lc,Deflt,Reslt).
matchSegments([],_,_,Deflt,Deflt).
matchSegments([Seg|M],Vrs,Lc,Deflt,Reslt) :-
matchSegments(M,Vrs,Lc,Deflt,Partial),
matchSegment(Seg,Vrs,Lc,Partial,Reslt).
matchSegment(Seg,Vrs,Lc,Deflt,Reslt) :-
segmentMode(Seg,Mode),
compileMatch(Mode,Seg,Vrs,Lc,Deflt,Reslt).
segmentMode([Tr|_],Mode) :-
tripleArgMode(Tr,Mode).
compileMatch(inScalars,Tpls,Vrs,Lc,Deflt,Reslt) :-
matchScalars(Tpls,Vrs,Lc,Deflt,Reslt).
compileMatch(inConstructors,Tpls,Vrs,Lc,Deflt,Reslt) :-
matchConstructors(Lc,Tpls,Vrs,Deflt,Reslt).
compileMatch(inVars,Tpls,Vrs,Lc,Deflt,Reslt) :-
matchVars(Lc,Vrs,Tpls,Deflt,Reslt).
conditionalize([],Deflt,Deflt).
conditionalize([(_,(Lc,Bnds,Test,Val),_)|M],Deflt,Repl) :-!,
pullWhere(Val,enum("star.core#true"),Vl,C0),
mergeGoal(Test,C0,Lc,TT),
(TT=enum("star.core#true") ->
applyBindings(Bnds,Lc,Vl,Repl);
conditionalize(M,Deflt,Other),
applyBindings(Bnds,Lc,Vl,TVl),
Repl = cnd(Lc,TT,TVl,Other)
).
applyBindings(Bnds,Lc,Val,DVal) :-
filter(Bnds,matcher:filterBndVar(Val),VBnds),!,
(VBnds=[] -> DVal=Val ; DVal = varNames(Lc,VBnds,Val)).
filterBndVar(Val,(Nm,X)) :-
\+ string_concat("_",_,Nm),
idInTerm(idnt(X),Val).
argMode(idnt(_),inVars).
argMode(voyd,inScalars).
argMode(intgr(_),inScalars).
argMode(float(_),inScalars).
argMode(strg(_),inScalars).
argMode(lbl(_,_),inScalars).
argMode(whr(_,T,_),M) :- argMode(T,M).
argMode(enum(_),inConstructors).
argMode(ctpl(_,_),inConstructors).
makeTriples([],_,[]).
makeTriples([Rl|L],Ix,[Tr|LL]) :-
makeEqnTriple(Rl,Ix,Tr),
Ix1 is Ix+1,
makeTriples(L,Ix1,LL).
makeEqnTriple((Lc,Args,Cnd,Val),Ix,(Args,(Lc,[],enum("star.core#true"),whr(Lc,Val,Cnd)),Ix)).
partitionTriples([Tr|L],[[Tr|LL]|Tx]) :-
tripleArgMode(Tr,M),
partTriples(L,L0,M,LL),
partitionTriples(L0,Tx).
partitionTriples([],[]).
partTriples([],[],_,[]).
partTriples([Tr|L],Lx,M,[Tr|LL]) :-
tripleArgMode(Tr,M),
partTriples(L,Lx,M,LL).
partTriples(L,L,_,[]).
tripleArgMode(([A|_],_,_),Mode) :-
argMode(A,Mode),!.
% genVars(0,[]).
% genVars(Ar,[idnt(NN)|LL]) :-
% Ar>0,
% genstr("_",NN),
% Ar1 is Ar-1,
% genVars(Ar1,LL).
newVars([],V,V).
newVars([_|L],V,[idnt(NN)|VV]) :-
genstr("_",NN),
newVars(L,V,VV).
matchScalars(Tpls,[V|Vrs],Lc,Deflt,CaseExp) :-
sort(Tpls,matcher:compareScalarTriple,ST),
formCases(ST,matcher:sameScalarTriple,Lc,Vrs,Deflt,Cases),
mkCase(Lc,V,Cases,Deflt,CaseExp).
mkCase(Lc,V,[(Lbl,Exp,Lc)],Deflt,cnd(Lc,mtch(Lc,Lbl,V),Exp,Deflt)) :-!.
mkCase(Lc,V,Cases,Deflt,case(Lc,V,Cases,Deflt)).
matchConstructors(Lc,Tpls,[V|Vrs],Deflt,CaseExp) :-
sort(Tpls,matcher:compareConstructorTriple,ST),
formCases(ST,matcher:sameConstructorTriple,Lc,Vrs,Deflt,Cases),
mkCase(Lc,V,Cases,Deflt,CaseExp).
formCases([],_,_,[],_,[]) :- !.
formCases([],_,_,_,_,[]).
formCases([Tr|Trpls],Cmp,Lc,Vrs,Deflt,[(Lbl,Case,Lc)|Cses]) :-
pickMoreCases(Tr,Trpls,Tx,Cmp,More),
formCase(Tr,Lbl,[Tr|Tx],Lc,Vrs,Deflt,Case),
formCases(More,Cmp,Lc,Vrs,Deflt,Cses).
formCase(([Lbl|_],_,_),Lbl,Tpls,Lc,Vrs,Deflt,Case) :-
isScalar(Lbl),!,
subTriples(Tpls,STpls),
matchTriples(Lc,Vrs,STpls,Deflt,Case).
formCase(([enum(Lb)|_],_,_),enum(Lb),Tpls,Lc,Vrs,Deflt,Case) :-
subTriples(Tpls,STpls),
matchTriples(Lc,Vrs,STpls,Deflt,Case).
formCase(([ctpl(Op,Args)|_],_,_),ctpl(Op,NVrs),Tpls,Lc,Vrs,Deflt,Case) :-
length(Args,Ar),
genVars(Ar,NVrs),
concat(NVrs,Vrs,NArgs),
subTriples(Tpls,NTpls),
matchTriples(Lc,NArgs,NTpls,Deflt,Case).
pickMoreCases(_,[],[],_,[]).
pickMoreCases(Tr,[A|Trpls],[A|Tx],Cmp,More) :-
call(Cmp,Tr,A),!,
pickMoreCases(Tr,Trpls,Tx,Cmp,More).
pickMoreCases(_,Trpls,[],_,Trpls).
isScalar(S) :- argMode(S,inScalars),!.
mergeTriples(L1,L2,L3) :-
sortedMerge(L1,L2,matcher:earlierIndex,L3).
subTriples([],[]).
subTriples([T1|Tr1],[ST1|STr1]) :-
subTriple(T1,ST1),
subTriples(Tr1,STr1).
subTriple(([ctpl(_,CArgs)|Args],V,X),(NArgs,V,X)) :-!,
concat(CArgs,Args,NArgs).
subTriple(([_|Args],V,X),(Args,V,X)).
earlierIndex((_,_,Ix1),(_,_,Ix2)) :-
Ix1<Ix2.
compareConstructorTriple(([A|_],_,_,_),([B|_],_,_,_)) :-
compareConstructor(A,B).
compareConstructor(A,B) :-
constructorName(A,ANm),
constructorName(B,BNm),
str_lt(ANm,BNm).
sameConstructorTriple(([A|_],_,_),([B|_],_,_)) :-
sameConstructor(A,B).
sameConstructor(A,B) :-
constructorName(A,Nm),
constructorName(B,Nm).
constructorName(enum(Nm),Nm).
constructorName(lbl(Nm,_),Nm).
constructorName(ctpl(C,_),Nm) :-
constructorName(C,Nm).
compareScalarTriple(([A|_],_,_),([B|_],_,_)) :-
compareScalar(A,B).
compareScalar(intgr(A),intgr(B)) :-!,
A<B.
compareScalar(float(A),float(B)) :-!,
A<B.
compareScalar(strg(A),strg(B)) :-!,
str_lt(A,B).
compareScalar(lbl(L1,_A1),lbl(L2,_A2)) :-
str_lt(L1,L2),!.
compareScalar(lbl(L,A1),lbl(L,A2)) :-
A1<A2.
sameScalarTriple(([A|_],_,_),([A|_],_,_)).
matchVars(Lc,[V|Vrs],Triples,Deflt,Reslt) :-
applyVar(V,Triples,NTriples),
matchTriples(Lc,Vrs,NTriples,Deflt,Reslt).
applyVar(_,[],[]).
applyVar(V,[([idnt(XV)|Args],(Lc,Bnd,Cond,Vl),Ix)|Tpls],[(NArgs,(Lc,[(XV,V)|Bnd],NCond,NVl),Ix)|NTpls]) :-
Vrs = [(XV,V)],
substTerm(Vrs,Vl,NVl),
substTerms(Vrs,Args,NArgs),
substTerm(Vrs,Cond,NCond),
applyVar(V,Tpls,NTpls).
applyVar(V,[([whr(Lcw,idnt(XV),Cond)|Args],(Lc,Bnd,Test,Vl),Ix)|Tpls],
[(NArgs,(Lc,[(XV,V)|Bnd],NCnd,NVl),Ix)|NTpls]) :-
Vrs = [(XV,V)],
substTerm(Vrs,Vl,NVl),
substTerm(Vrs,Cond,NCond),
substTerm(Vrs,Test,NTest),
mergeGoal(NTest,NCond,Lcw,NCnd),
substTerms(Vrs,Args,NArgs),
applyVar(V,Tpls,NTpls).
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
// https://www.hackerrank.com/challenges/crush
public class Solution {
/*
// examples:
1 6 100
2 3 200
answer: 100 300 300 100 100 100
my_answer: 100 200 0 -200 0 0 -100
100 300 300 100 100 100 0
// example 2:
1 3 100
2 3 100
4 5 100
3 4 100
answer: 100 200 300 200 100
my_answer: 100 100 100 0 0 -100
100 200 300 300 300 0
// example 3:
5 3
1 2 100
2 5 100
3 4 100
answer: 100 200 200 200 100
my_answer: 100 100 100 0 100 -100
100 200 200 200 100 0
*/
public static void main(String[] args) {
// read input from STDIN
Scanner in = new Scanner(System.in);
// read n & m
int n = in.nextInt(), m = in.nextInt();
// use an array with n+1 elements (n+1'th element is to limit the n'th element)
long[] ar = new long[n+1];
// read inputs
for (int op = 0; op < m; op++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
int k = in.nextInt();
// add to the element at index a the number k
ar[a] += k;
// substract from the element at index b+1 the number k
ar[b+1] -= k;
}
// max is the biggest number
long max = Long.MIN_VALUE;
for (int i = 1; i < n; i++) {
// add the value from left
ar[i] += ar[i-1];
// update the maximum
if (ar[i] > max)
max = ar[i];
}
// print to STDOUT the maximum value
System.out.println(max);
// close scanner
in.close();
}
}
|
package cn.qiuxiang.react.baidumap.modules
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.SDKInitializer.*
import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter
@Suppress("unused")
class BaiduMapInitializerModule(private val context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {
class SDKReceiver(promise: Promise) : BroadcastReceiver() {
private var promise: Promise? = promise
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK) {
promise?.resolve(null)
} else {
val code = intent.getIntExtra(SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE, 0)
promise?.reject(code.toString(), intent.action)
}
}
}
private val emitter by lazy { context.getJSModule(RCTDeviceEventEmitter::class.java) }
override fun getName(): String {
return "BaiduMapInitializer"
}
override fun canOverrideExistingModule(): Boolean {
return true
}
@ReactMethod
fun init(promise: Promise) {
val intentFilter = IntentFilter()
intentFilter.addAction(SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)
intentFilter.addAction(SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)
context.currentActivity?.registerReceiver(SDKReceiver(promise), intentFilter)
SDKInitializer.initialize(context.applicationContext)
}
}
|
;; APPLE LOCAL file v7 support. Merge from Codesourcery
;; ARM instruction patterns for hardware division
;; Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
;; Written by CodeSourcery, LLC.
;;
;; This file is part of GCC.
;;
;; GCC is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;;
;; GCC is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GCC; see the file COPYING. If not, write to
;; the Free Software Foundation, 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
(define_insn "divsi3"
[(set (match_operand:SI 0 "s_register_operand" "=r")
(div:SI (match_operand:SI 1 "s_register_operand" "r")
(match_operand:SI 2 "s_register_operand" "r")))]
"arm_arch_hwdiv"
"sdiv%?\t%0, %1, %2"
[(set_attr "predicable" "yes")
(set_attr "insn" "sdiv")]
)
(define_insn "udivsi3"
[(set (match_operand:SI 0 "s_register_operand" "=r")
(udiv:SI (match_operand:SI 1 "s_register_operand" "r")
(match_operand:SI 2 "s_register_operand" "r")))]
"arm_arch_hwdiv"
"udiv%?\t%0, %1, %2"
[(set_attr "predicable" "yes")
(set_attr "insn" "udiv")]
)
|
#!/bin/bash
#Response for bad arguments or unsupported features
BADARG='The app you specified does not exist. Check the name again (note: it is case sensitive)'
NOARGSUPPORT='This app doesn''t support the '$1' option. Check the readme file for which operations are supported for each app.'
eval set -- "$ARGS";
#Nothing passed in so just blank the ARGS variable
if [[ $1 = '--' ]]; then
ARGS=''
fi
#Options
while true; do
case "$1" in
-h|--help)
shift;
if [[ -n $1 ]]; then
help
fi
;;
-i|--install)
shift;
if [[ -n $1 ]]; then
install="$1";
if [[ -f $SCRIPTPATH/$1/$1-installer.sh ]]; then
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/$1/$1-installer.sh"
elif [[ -f $SCRIPTPATH/utils/$1/$1-installer.sh ]]; then
if [[ -f $SCRIPTPATH/utils/$1/$1-constants.sh ]]; then
source "$SCRIPTPATH/utils/$1/$1-constants.sh"
fi
source "$SCRIPTPATH/utils/$1/$1-installer.sh"
else
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
fi
shift;
fi
;;
-u|--uninstall)
shift;
if [[ -n $1 ]]; then
uninstall="$1";
if [[ -f $SCRIPTPATH/$1/$1-uninstaller.sh ]]; then
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/$1/$1-uninstaller.sh"
elif [[ -f $SCRIPTPATH/utils/$1/$1-uninstaller.sh ]]; then
if [[ -f $SCRIPTPATH/utils/$1/$1-constants.sh ]]; then
source "$SCRIPTPATH/utils/$1/$1-constants.sh"
fi
source "$SCRIPTPATH/utils/$1/$1-uninstaller.sh"
else
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
fi
shift;
fi
;;
-b|--backup)
shift;
if [[ -n $1 ]]; then
backup="$1";
if [[ ! -f $SCRIPTPATH/$1/$1-constants.sh ]]; then
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
else
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/inc/app-backup-controller.sh"
fi
shift;
fi
;;
-r|--restore)
shift;
if [[ -n $1 ]]; then
restore="$1";
if [[ ! -f $SCRIPTPATH/$1/$1-constants.sh ]]; then
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
else
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/inc/app-restore-controller.sh"
fi
shift;
fi
;;
-m|--manualupdate)
shift;
if [[ -n $1 ]]; then
manualupdate="$1";
if [[ -f $SCRIPTPATH/$1/$1-update.sh ]]; then
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/$1/$1-update.sh"
elif [[ -f $SCRIPTPATH/utils/$1/$1-update.sh ]]; then
if [[ -f $SCRIPTPATH/utils/$1/$1-constants.sh ]]; then
source "$SCRIPTPATH/utils/$1/$1-constants.sh"
fi
source "$SCRIPTPATH/utils/$1/$1-update.sh"
else
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
fi
shift;
fi
;;
-p|--passwordreset)
shift;
if [[ -n $1 ]]; then
passwordreset="$1";
if [[ ! -f $SCRIPTPATH/$1/$1-constants.sh ]]; then
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
else
if grep -q "Reset Password" "$SCRIPTPATH/$1/$1-menu.sh"; then
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/inc/app-password-reset.sh"
else
echo
echo
echo "$NOARGSUPPORT"
source "$SCRIPTPATH/inc/exit.sh"
fi
fi
shift;
fi
;;
-a|--accessdetails)
shift;
if [[ -n $1 ]]; then
accessdetails="$1";
if [[ ! -f $SCRIPTPATH/$1/$1-constants.sh ]]; then
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
else
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/inc/app-access-details.sh"
fi
shift;
fi
;;
-x|--reverseproxy)
shift;
if [[ -x $1 ]]; then
reverseproxy="$1";
if [[ ! -f $SCRIPTPATH/$1/$1-constants.sh ]]; then
echo
echo
echo "$BADARG"
source "$SCRIPTPATH/inc/exit.sh"
else
source "$SCRIPTPATH/$1/$1-constants.sh"
source "$SCRIPTPATH/utils/nginx/nginx-enable-location.sh"
fi
shift;
fi
;;
-t|--updatetoolkit)
shift;
updatetoolkit="1";
source "$SCRIPTPATH/maintenance/update.sh"
;;
-U|--updateall)
shift;
updateall="1";
source "$SCRIPTPATH/maintenance/distro-update.sh"
;;
--)
shift;
break;
;;
esac
done
|
/*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twosigma.flint.util.collection
import org.scalatest.FlatSpec
import java.util.{ LinkedList => JLinkedList }
import scala.collection.JavaConverters._
class LinkedListHolderSpec extends FlatSpec {
"LinkedListHolder" should "dropWhile correctly" in {
import Implicits._
val l = new JLinkedList[Int]()
val n = 10
val p = 3
l.addAll((1 to n).asJava)
val (dropped1, rest1) = l.dropWhile { i => i > p }
assert(dropped1.size() == 0)
assert(rest1.toArray.deep == l.toArray.deep)
val (dropped2, rest2) = l.dropWhile { i => i < p }
assert(dropped2.toArray.deep == (1 until p).toArray.deep)
assert(rest2.toArray.deep == (p to n).toArray.deep)
}
it should "foldLeft correctly" in {
import com.twosigma.flint.util.collection.Implicits._
val l = new JLinkedList[Char]()
assert(l.foldLeft("")(_ + _) == "")
l.add('a')
l.add('b')
l.add('c')
l.add('d')
assert(l.foldLeft("")(_ + _) == "abcd")
}
it should "foldRight correctly" in {
import com.twosigma.flint.util.collection.Implicits._
val l = new JLinkedList[Char]()
assert(l.foldRight("")(_ + _) == "")
l.add('a')
l.add('b')
l.add('c')
l.add('d')
assert(l.foldRight("")(_ + _) == "dcba")
}
}
|
package main.java.com.twu.biblioteca.controllers;
import main.java.com.twu.biblioteca.models.Customer;
import main.java.com.twu.biblioteca.models.Library;
import main.java.com.twu.biblioteca.models.User;
import main.java.com.twu.biblioteca.views.BibliotecaAppView;
import java.util.Scanner;
public class BibliotecaAppController {
private Library library;
private User user;
public BibliotecaAppController(Library library, User user) {
this.library = library;
this.user = user;
}
public void route(String choice) {
if(this.user instanceof Customer) this.routeCustomers(choice);
else this.routeLibrarians(choice);
}
private void routeCustomers(String choice) {
LibraryController libraryController = new LibraryController(this.library, this.user);
BibliotecaAppView bibliotecaAppView = new BibliotecaAppView(this.library, this.user);
if(choice.equals("a") || choice.equals("b")) {
libraryController.selectedListMedia(choice);
this.printMainMenu();
} else if(choice.equals("c") || choice.equals("d")) {
libraryController.selectedReturnMedia(choice);
printMainMenu();
} else if(choice.equals("i")) {
libraryController.selectedUserInformation();
printMainMenu();
} else if(choice.equals("q")) {
// exit program
} else {
bibliotecaAppView.printInvalidOptionMessage();
this.printMainMenu();
}
}
private void routeLibrarians(String choice) {
LibraryController libraryController = new LibraryController(this.library, this.user);
BibliotecaAppView bibliotecaAppView = new BibliotecaAppView(this.library, this.user);
if(choice.equals("a")) {
libraryController.selectedListCheckedOutBooks();
this.printMainMenu();
} else if(choice.equals("q")) {
// exit program
} else {
bibliotecaAppView.printInvalidOptionMessage();
this.printMainMenu();
}
}
public void printMainMenu() {
BibliotecaAppView bibliotecaAppView = new BibliotecaAppView(this.library, this.user);
bibliotecaAppView.printSelectElementInMenuMessage();
bibliotecaAppView.printMenuElements();
bibliotecaAppView.printEnterYourChoiceMessage();
Scanner stdin = new Scanner(System.in);
String choice = stdin.next();
this.route(choice);
}
}
|
require 'ffi/struct'
module FFI
module Elf
class AuxVec < FFI::Struct
TYPES = [
TYPE_NULL = 0, # End of vector
TYPE_IGNORE = 1, # Entry should be ignored
TYPE_EXECFG = 2, # File descriptor of program
TYPE_PHDR = 3, # Program headers for program
TYPE_PHENT = 4, # Size of program header entry
TYPE_PHNUM = 5, # Number of program headers
TYPE_PAGESZ = 6, # System page size
TYPE_BASE = 7, # Base address of interpreter
TYPE_FLAGS = 8, # Flags
TYPE_ENTRY = 9, # Entry point of program
TYPE_NOTELF = 10, # Program is not ELF
TYPE_UID = 11, # Real UID
TYPE_EUID = 12, # Effective UID
TYPE_GID = 13, # Real GID
TYPE_EGID = 14, # Effective GID
TYPE_CLKTCK = 17, # Frequency of times()
TYPE_PLATFORM = 15, # String identifying platform
TYPE_HWCAP = 16, # Machine dependent hints about processor capabilities
TYPE_FPUCW = 18, # Used FPU control word
TYPE_DCACHEBSIZE = 19, # Data cache block size
TYPE_ICACHEBSIZE = 20, # Instruction cache block size
TYPE_UCACHEBSIZE = 21, # Unified cache block size
TYPE_IGNOREPPC = 22, # Entry should be ignored.
TYPE_SECURE = 23, # Boolean, was exec setuid-like?
TYPE_EXECFN = 31, # Filename of executable
TYPE_SYSINFO = 32,
TYPE_SYSINFO_EHDR = 33,
TYPE_L1I_CACHESHAPE = 34,
TYPE_L1D_CACHESHAPE = 35,
TYPE_L2_CACHESHAPE = 36,
TYPE_L3_CACHESHAPE = 37
]
end
end
end
|
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
kotlin("jvm")
id("com.github.johnrengelman.shadow").version("4.0.3")
}
tasks.withType<ShadowJar> {
classifier = ""
}
dependencies {
compile(kotlin("stdlib-jdk8"))
compileOnly("com.fs.starfarer", "starfarer.api", rootProject.extra["starsector.version"] as String)
} |
# CREATNG THE APP SERVICE ON AZURE
$loc = 'southeastasia'
$grp = '07PublishDirectlyDemoRG'
$pln = '07Demo-SEA'
$appname = 'directlypublishingdemo'
az group create --name $grp --location $loc
az appservice plan create --name $pln --resource-group $grp --location $loc --sku S1
az webapp create --name $appname --plan $pln --resource-group $grp
az webapp deployment user set --user-name kamal1 --password kamal12345
# CREATING THE .NET APP
mkdir CoolApp
cd CoolApp
dotnet new mvc --framework netcoreapp3.1 --no-restore
# PUBLISHING IT
git init
git add .
git commit -m initial
# PUBLISHING DOTNET APP TO AZURE
az webapp deployment source config-local-git --name $appname --resource-group $grp
$url=$(az webapp deployment source config-local-git --name $appname --resource-group $grp --output json --query url)
git remote add azure1 $url
git push azure1 master
az group delete --resource-group $grp --yes
|
<?php
$hash = geohash_encode(39.4169170000,100.92224000000);
$arr = geohash_decode($hash);
print_r($arr);
$neighbors = geohash_neighbors($hash);
var_dump($neighbors);
var_dump(geohash_dimension(12));
var_dump(geohash_dimension(5));
|
package org.whitneyrobotics.ftc.teamcode.subsys;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
import org.whitneyrobotics.ftc.teamcode.lib.util.SimpleTimer;
import org.whitneyrobotics.ftc.teamcode.lib.util.Toggler;
public class SussyOuttake {
public Servo gate;
public DcMotor linearSlides;
public SussyOuttake(HardwareMap outtakeMap) {
gate = outtakeMap.servo.get("gateServo");
linearSlides = outtakeMap.get(DcMotorEx.class, "linearSlides");
gate.setPosition(gatePositions[GatePositions.CLOSE.ordinal()]);
linearSlides.setDirection(DcMotor.Direction.REVERSE);
resetEncoder();
}
public double level1 = 0;
public double level2 = -1296;
public double level3 = -2092;
private double motorSpeed = 0.10;
private double acceptableError = 100;
private double[] orderedLevels = {level1, level2, level3};
private Toggler servoGateTog = new Toggler(2);
private Toggler linearSlidesTog = new Toggler(3);
private SimpleTimer outtakeGateTimer = new SimpleTimer();
private enum GatePositions{
CLOSE, OPEN
}
private double[] gatePositions = {1,0.6};
public boolean slidingInProgress = false;
public boolean dropFirstLoop = true; //for setting drop timer
//private boolean outtakeTimerSet = true; <<I don't know what this is used for
//toggler based teleop
public void togglerOuttake(boolean up, boolean down) {
if (!slidingInProgress){linearSlidesTog.changeState(up, down);}
double currentTarget = orderedLevels[linearSlidesTog.currentState()];
if(Math.abs(linearSlides.getCurrentPosition()-currentTarget) <= acceptableError){
linearSlides.setPower(0);
slidingInProgress = false;
} else if(linearSlides.getCurrentPosition()<currentTarget && linearSlides.getCurrentPosition()<10){
linearSlides.setPower(motorSpeed);
slidingInProgress = true;
} else if(!(linearSlides.getCurrentPosition()<-2500)){
linearSlides.setPower(-motorSpeed);
slidingInProgress = true;
}
}
public void togglerOuttakeOld(boolean up,boolean down){
linearSlidesTog.changeState(up,down);
if (linearSlidesTog.currentState() == 0) {
if(linearSlides.getCurrentPosition()>level1){
linearSlides.setPower(-motorSpeed);
} else if (linearSlides.getCurrentPosition()<level1) {
linearSlides.setPower(motorSpeed);
} else {
linearSlides.setPower(0);
}
if (linearSlides.getCurrentPosition() == level1) {
slidingInProgress = false;
} else {slidingInProgress = true;}
} else if (linearSlidesTog.currentState() == 1) {
if(linearSlides.getCurrentPosition()>level2){
linearSlides.setPower(-motorSpeed);
} else if (linearSlides.getCurrentPosition()<level2){
linearSlides.setPower(motorSpeed);
} else {
linearSlides.setPower(0);
}
if (linearSlides.getCurrentPosition() == level2) {
slidingInProgress = false;
} else {slidingInProgress = true;}
} else if (linearSlidesTog.currentState() == 2) {
if(linearSlides.getCurrentPosition()>level3){
linearSlides.setPower(-motorSpeed);
} else if (linearSlides.getCurrentPosition()<level3){
linearSlides.setPower(motorSpeed);
} else {
linearSlides.setPower(0);
}
if (linearSlides.getCurrentPosition() == level3) {
slidingInProgress = false;
} else {slidingInProgress = true;}
}
}
public void togglerServoGate(boolean pressed){
servoGateTog.changeState(pressed);
if (servoGateTog.currentState() == 0) {
gate.setPosition(gatePositions[GatePositions.CLOSE.ordinal()]);
} else {
gate.setPosition(gatePositions[GatePositions.OPEN.ordinal()]);
}
}
public void autoControl(int levelIndex) {
double currentTarget = orderedLevels[levelIndex];
if(Math.abs(linearSlides.getCurrentPosition()-currentTarget) <= acceptableError){
linearSlides.setPower(0);
slidingInProgress = false;
} else if(linearSlides.getCurrentPosition()>currentTarget){
linearSlides.setPower(-motorSpeed);
slidingInProgress = true;
} else {
linearSlides.setPower(motorSpeed);
slidingInProgress = true;
}
}
public boolean autoDrop() { //boolean so our autoop knows if its done
if(dropFirstLoop) {
togglerServoGate(true);
outtakeGateTimer.set(500); /*ms to keep the flap open*/
dropFirstLoop = false;
}
if(outtakeGateTimer.isExpired()){
togglerServoGate(false);
togglerServoGate(true);
dropFirstLoop = true;
return true;
}
return false;
}
public void reset() {
linearSlidesTog.setState(0);
}
public void resetEncoder() {
linearSlides.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
linearSlides.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
public int getTier() { return linearSlidesTog.currentState(); }
}
|
#include <stdio.h>
int main()
{
int a,b,c;
printf("enter two numberes to be added");
scanf("%a%b",&a,&b);
c=a+b;
printf("answer is %c");
return 0;
}
|
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
pub mod ckraw;
pub mod logger;
pub use ckraw::{CkRawAttr, CkRawAttrTemplate, CkRawMechanism};
macro_rules! ck_padded_str {
($src:expr, $len: expr) => {{
let mut ret = [b' '; $len];
let count = std::cmp::min($src.len(), $len);
ret[..count].copy_from_slice(&$src.as_bytes()[..count]);
ret
}};
}
macro_rules! ck_version {
($major:expr, $minor:expr) => {
crate::pkcs11::CK_VERSION {
major: $major,
minor: $minor,
}
};
}
pub enum Error {
BufTooSmall,
MechParamTypeMismatch,
NullPtrDeref,
}
|
<?php declare(strict_types = 1);
namespace Venta\Routing\Factory;
use Venta\Contracts\Container\Invoker;
use Venta\Contracts\Routing\Route as RouteContract;
use Venta\Contracts\Routing\RouteDispatcher as RouteDispatcherContract;
use Venta\Contracts\Routing\RouteDispatcherFactory as RouteDispatcherFactoryContract;
use Venta\Routing\RouteDispatcher;
/**
* Class RouteDispatcherFactory
*
* @package Venta\Routing\Factory
*/
final class RouteDispatcherFactory implements RouteDispatcherFactoryContract
{
/**
* @var Invoker
*/
private $invoker;
/**
* RouteDispatcherFactory constructor.
*
* @param Invoker $invoker
*/
public function __construct(Invoker $invoker)
{
$this->invoker = $invoker;
}
/**
* @inheritDoc
*/
public function create(RouteContract $route): RouteDispatcherContract
{
return new RouteDispatcher($this->invoker, $route);
}
} |
package main
import (
"configurator/config"
"encoding/json"
"fmt"
"os"
//"io/ioutil"
"gopkg.in/yaml.v2"
)
func main() {
stat, err := os.Stdin.Stat()
if err != nil {
panic(err)
}
if (stat.Mode() & os.ModeCharDevice) != 0 {
fmt.Fprintln(os.Stderr, "Usage: <json> | configurator")
os.Exit(1)
}
fmt.Fprintln(os.Stdin)
var boshConfig config.BoshConfig
if err := json.NewDecoder(os.Stdin).Decode(&boshConfig); err != nil {
panic(err)
}
port, err := boshConfig.Port.Int64()
if err != nil {
panic(err)
}
credhubConfig := config.NewDefaultCredhubConfig()
credhubConfig.Server.Port = port
credhubConfig.Security.Authorization.ACLs.Enabled = boshConfig.Authorization.ACLs.Enabled
if boshConfig.Java7TlsCiphersEnabled {
credhubConfig.Server.SSL.Ciphers = config.Java7CipherSuites
}
if len(boshConfig.Authentication.MutualTLS.TrustedCAs) > 0 {
credhubConfig.Server.SSL.ClientAuth = "want"
credhubConfig.Server.SSL.TrustStore = config.ConfigPath + "/mtls_trust_store.jks"
credhubConfig.Server.SSL.TrustStorePassword = "MTLS_TRUST_STORE_PASSWORD_PLACEHOLDER"
credhubConfig.Server.SSL.TrustStoreType = "JKS"
}
if boshConfig.Authentication.UAA.Enabled {
credhubConfig.Security.OAuth2.Enabled = true
credhubConfig.AuthServer.URL = boshConfig.Authentication.UAA.Url
credhubConfig.AuthServer.TrustStore = config.DefaultTrustStorePath
credhubConfig.AuthServer.TrustStorePassword = config.TrustStorePasswordPlaceholder
credhubConfig.AuthServer.InternalURL = boshConfig.Authentication.UAA.InternalUrl
}
if boshConfig.Bootstrap {
credhubConfig.Encryption.KeyCreationEnabled = true
credhubConfig.Flyway.Enabled = true
}
for _, key := range boshConfig.Encryption.Keys {
var providerType string
for _, provider := range boshConfig.Encryption.Providers {
if provider.Name == key.ProviderName {
providerType = provider.Type
if provider.Type == "hsm" {
if provider.ConnectionProperties.Partition != "" && provider.ConnectionProperties.PartitionPassword != "" {
credhubConfig.Hsm.Partition = provider.ConnectionProperties.Partition
credhubConfig.Hsm.PartitionPassword = provider.ConnectionProperties.PartitionPassword
} else {
credhubConfig.Hsm.Partition = provider.Partition
credhubConfig.Hsm.PartitionPassword = provider.PartitionPassword
}
}
break
}
}
var encryptionKeyName string
var encryptionKeyPassword string
if key.KeyProperties.EncryptionKeyName != "" {
encryptionKeyName = key.KeyProperties.EncryptionKeyName
} else if key.KeyProperties.EncryptionPassword != "" {
encryptionKeyPassword = key.KeyProperties.EncryptionPassword
} else if key.EncryptionKeyName != "" {
encryptionKeyName = key.EncryptionKeyName
} else if key.EncryptionPassword != "" {
encryptionKeyPassword = key.EncryptionPassword
}
configKey := config.Key{
ProviderType: providerType,
EncryptionKeyName: encryptionKeyName,
EncryptionPassword: encryptionKeyPassword,
Active: key.Active,
}
credhubConfig.Encryption.Keys = append(credhubConfig.Encryption.Keys, configKey)
}
switch boshConfig.DataStorage.Type {
case "in-memory":
credhubConfig.Flyway.Locations = config.H2MigrationsPath
case "mysql":
credhubConfig.Flyway.Locations = config.MysqlMigrationsPath
connectionString := config.MysqlConnectionString
if boshConfig.DataStorage.RequireTLS {
connectionString = config.MysqlTlsConnectionString
}
credhubConfig.Spring.Datasource.URL = fmt.Sprintf(connectionString,
boshConfig.DataStorage.Host, boshConfig.DataStorage.Port, boshConfig.DataStorage.Database)
credhubConfig.Spring.Datasource.Username = boshConfig.DataStorage.Username
credhubConfig.Spring.Datasource.Password = boshConfig.DataStorage.Password
case "postgres":
credhubConfig.Flyway.Locations = config.PostgresMigrationsPath
connectionString := config.PostgresConnectionString
if boshConfig.DataStorage.RequireTLS {
connectionString = config.PostgresTlsConnectionString
}
credhubConfig.Spring.Datasource.URL = fmt.Sprintf(connectionString,
boshConfig.DataStorage.Host, boshConfig.DataStorage.Port, boshConfig.DataStorage.Database)
credhubConfig.Spring.Datasource.Username = boshConfig.DataStorage.Username
credhubConfig.Spring.Datasource.Password = boshConfig.DataStorage.Password
default:
fmt.Fprintln(os.Stderr, `credhub.data_storage.type must be set to "mysql", "postgres", or "in-memory".`)
os.Exit(1)
}
byteArray, err := yaml.Marshal(credhubConfig)
if err != nil {
panic(err)
}
fmt.Printf("%s", byteArray)
os.Exit(0)
}
|
create table if not exists `associations`
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
deal_id VARCHAR(255) NOT NULL,
card_id VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
create table if not exists `mappings`
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
board_id VARCHAR(255) NOT NULL,
board_list_id VARCHAR(255) NOT NULL,
pipeline_id VARCHAR(255) NOT NULL,
pipeline_stage_id VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
|
# learning
Stuff I make for my own learning! IMO, there's some cool stuff too.
|
#!/bin/bash
set -xeuo pipefail
usage() {
cat <<EOF
Usage: $0 <configuration destination>
Written by Kamil Cukrowski
EOF
}
if [ $# -eq 0 ] || [ -e "${1:-}" ]; then usage; exit 1; fi;
dst=$1
if [ ! -e "$dst/zabbix_agentd.conf" ]; then
echo "ERROR: no such file as $dst/zabbix_agentd.conf"
exit 1
fi
mkdir -p "$dst/scripts" "$dst/zabbix_agentd.d"
cp -v scripts/* "$dst/scripts/"
cp -v zabbix_agentd.d/* "$dst/zabbix_agentd.d/"
cp -v sudoers.d/* /etc/sudoers.d/
line='Include=/etc/zabbix/zabbix_agentd.d/*.conf'
file=/etc/zabbix_agentd.conf
if ! grep -q "$line" "$file"; then
echo "Adding confguration file"
echo "$line" >> "$file"
fi
|
@page
@using DidacticalEnigma.Mem.Areas.Identity.Pages.Account.Manage
@model PersonalDataModel
@{
ViewData["Title"] = "Personal Data";
ViewData["ActivePage"] = ManageNavPages.PersonalData;
}
|
/*---------------------------------------------------------------------------------------------
* Copyright © 2016-present Earth Computing Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//use std::sync::mpsc;
use crossbeam::crossbeam_channel as mpsc;
use crate::app_message::{SenderMsgSeqNo};
use crate::app_message_formats::{ISCONTROL, ISAIT, SNAKE};
use crate::name::{OriginatorID, TreeID};
use crate::packet::{Packet};
use crate::packet_engine::NumberOfPackets;
use crate::port::{PortStatus, PortStatusOld};
use crate::routing_table_entry::{RoutingTableEntry};
use crate::utility::{ActivityData, ByteArray, Mask, PortNo, OutbufType};
use crate::uuid_ec::Uuid;
type CATOCM = (TreeID, ISCONTROL, ISAIT, SNAKE, Mask, SenderMsgSeqNo, ByteArray);
type REROUTE = (PortNo, PortNo, NumberOfPackets);
type STATUS = (PortNo, bool, PortStatus); // bool = is_border
type STATUSOLD = (PortNo, bool, NumberOfPackets, PortStatusOld); // bool = is_border
type TUNNELPORT = (PortNo, ByteArray);
type TUNNELUP = (OriginatorID, ByteArray);
//pub type PePeError = mpsc::SendError<PeToPePacket>;
// CellAgent to Cmodel (index, tree_uuid, user_mask, direction, bytes)
#[derive(Debug, Clone, Serialize)]
pub enum CaToCmBytes {
Bytes(CATOCM),
Delete(Uuid),
Entry(RoutingTableEntry),
Reroute(REROUTE),
Status(STATUSOLD),
TunnelPort(TUNNELPORT),
TunnelUp(TUNNELUP),
}
pub type CaToCm = mpsc::Sender<CaToCmBytes>;
pub type CmFromCa = mpsc::Receiver<CaToCmBytes>;
//pub type CaCmError = mpsc::SendError<CaToCmBytes>;
// Cmodel to PacketEngine
#[derive(Debug, Clone, Serialize)]
pub enum CmToPePacket {
Delete(Uuid),
Entry(RoutingTableEntry),
Packet((Mask, Packet)),
Reroute(REROUTE),
SnakeD((PortNo, Packet))
}
pub type CmToPe = mpsc::Sender<CmToPePacket>;
pub type PeFromCm = mpsc::Receiver<CmToPePacket>;
//pub type CmPeError = mpsc::SendError<CmToPePacket>;
// PacketEngine to Port
pub type PeToPortPacketOld = Packet;
pub type PeToPortOld = mpsc::Sender<PeToPortPacketOld>;
pub type PortFromPeOld = mpsc::Receiver<PeToPortPacketOld>;
#[derive(Debug, Clone, Serialize)]
pub enum PeToPortPacket {
Activity(ActivityData),
Packet((OutbufType, Packet)),
Ready
}
pub type PeToPort = mpsc::Sender<PeToPortPacket>;
pub type PortFromPe = mpsc::Receiver<PeToPortPacket>;
// Port to PacketEngine
#[derive(Debug, Clone, Serialize)]
pub enum PortToPePacket {
Activity((PortNo, ActivityData)),
Increment((PortNo, OutbufType)),
Packet((PortNo, Packet)),
Status(STATUS)
}
pub type PortToPe = mpsc::Sender<PortToPePacket>;
pub type PeFromPort = mpsc::Receiver<PortToPePacket>;
#[derive(Debug, Clone, Serialize)]
pub enum PortToPePacketOld {
Status((PortNo, bool, PortStatusOld)), // bool = is_border
Packet((PortNo, Packet))
}
pub type PortToPeOld = mpsc::Sender<PortToPePacketOld>;
pub type PeFromPortOld = mpsc::Receiver<PortToPePacketOld>;
//pub type PortPeError = mpsc::SendError<PortToPePacket>;
// PacketEngine to Cmodel
#[derive(Debug, Clone, Serialize)]
pub enum PeToCmPacketOld {
Status(STATUSOLD),
Packet((PortNo, Packet)),
Snake((PortNo, usize, Packet))
}
pub type PeToCm = mpsc::Sender<PeToCmPacketOld>;
pub type CmFromPe = mpsc::Receiver<PeToCmPacketOld>;
//pub type PeCmError = mpsc::SendError<PeToCmPacket>;
// Cmodel to CellAgent
#[derive(Debug, Clone, Serialize)]
pub enum CmToCaBytesOld {
Status(STATUSOLD),
Bytes((PortNo, bool, Uuid, ByteArray)),
TunnelPort(TUNNELPORT),
TunnelUp(TUNNELUP),
}
pub type CmToCa = mpsc::Sender<CmToCaBytesOld>;
pub type CaFromCm = mpsc::Receiver<CmToCaBytesOld>;
//pub type CmCaError = mpsc::SendError<CmToCaBytes>;
|
'use strict';
/**
* Home Controller
*/
var Asset = require('../models/Asset.js');
module.exports.controller = function (app) {
app.get('/', function (req, res) {
// Okay, okay, use the original video
var url = "hMOlNwzqBIk";
res.render('home/home', {
url: req.url,
showcaseVideo: url
});
});
};
|
<?php
namespace App\Http\Controllers\Client;
use App\AnswerSheet;
use App\Http\Controllers\Controller;
use App\Kid;
use App\Level;
use App\TestEvaluate;
use App\TestResult;
use App\Part;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
class TestController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$kidId = $request->get('kid_id');
$userId = \Auth::user()->id;
$kid = Kid::findOrFail($kidId);
if ($kid->user_id !== $userId) {
return response()->json([
'message' => 'This kid not belong to User !',
]);
}
$bD = $kid->birth_day;
$timeOffset = $bD->diff(Carbon::now());
$yearTime = $timeOffset->y !== 0 ? $timeOffset->y * 12 : 0;
$monthTime = $timeOffset->m;
$totalMonth = $yearTime + $monthTime;
$days = $timeOffset->d;
if ($days > 15) $totalMonth += 1;
if ($totalMonth == 0 && $days < 16) {
return response()->json([
'message' => 'No Test data for this kid !',
]);
}
$level = Level::with(['questions'])
->where('from', '=', $totalMonth)
->where('to', '>', $totalMonth)
->get();
return $this->success($level);
}
private function findEvaluate($item)
{
return TestEvaluate::where([
['min_score', '<=', $item['total_scores']],
['max_score', '>=', $item['total_scores']],
['level_id', '=', $item['level_id']],
['part_id', '=', $item['part_id']],
])->first();
}
private function createResult($item, $testEvaluate)
{
$kidId = \request()->get('kid_id');
$testResult = TestResult::create([
'total_scores' => $item['total_scores'],
'user_id' => \request()->user()->id,
'kid_id' => $kidId,
'level_id' => $item['level_id'],
'part_id' => $item['part_id'],
'comments' => $item['comments'],
'test_evaluate_id' => $testEvaluate ? $testEvaluate->id : 0,
]);
return $testResult;
}
private function createAnswers($item, $testResult)
{
$answers = [];
foreach ($item['answers'] as $ans) {
$answers[] = new AnswerSheet([
'question_id' => $ans['question_id'],
'answer_id' => $ans['question_id'],
'test_result_id' => $testResult->id,
]);
}
$testResult->answersheets()->saveMany($answers);
}
/**
* @param Request $request
* @return mixed
*/
public function store(Request $request)
{
$success = false;
$data = $request->get('data');
DB::beginTransaction();
$rs = [];
foreach ($data as $item) {
$partObj = new \stdClass;
$testEvaluate = $this->findEvaluate($item);
$partObj->name = Part::findOrFail($item['part_id'])->name;
$partObj->scores = $item['total_scores'];
$partObj->mainCmt = $testEvaluate->content;
$partObj->subCmt = $item['comments'];
$rs[] = $partObj;
}
try {
foreach ($data as $item) {
$testEvaluate = $this->findEvaluate($item);
$testResult = $this->createResult($item, $testEvaluate);
$partObj = new \stdClass;
$this->createAnswers($item, $testResult);
DB::commit();
$success = true;
}
} catch (\Exception $e) {
throw $e;
$success = false;
DB::rollback();
}
if ($success) {
return $this->success($rs, Response::HTTP_CREATED);
}
return $this->fail('Some error happen!');
}
}
|
USE employeetrackerDB;
INSERT INTO department (name)
VALUES ("Accounting"),
("Human Resources"),
("Sales"),
("Administrative"),
("IT"),
("Legal");
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ('Abraham', 'Lincoln', 1, 20),
('George', 'Washington', 5, 40),
('John F.', 'Kennedy', 3, 20),
('Theodore', 'Roosevelt', 2, 10),
('Thomas', 'Jefferson', 4, 30);
INSERT INTO role (title, salary, department_id)
VALUES ('President', 450000, 1),
('Executive Assistant', 50000, 5),
('CTO', 300000, 3),
('Inside Sales', 75000, 2),
('Lawyer', 200000, 4);
|
<?php
namespace Freeman\LaravelMacros\Macros\CarbonPeriod;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
/**
* Count natural weeks in a period, just same as calculate the sundays count.
* Assume monday is a week start while sunday is a week end.
*
* @return string
*/
class CountWeeks
{
public function __invoke()
{
return function () : int {
/** @var CarbonPeriod $this */
$start = $this->getStartDate()->startOfDay();
$end = $this->getEndDate()->startOfDay();
$countSundays = $start->diffInDaysFiltered(function (Carbon $date) {
return $date->isSunday();
}, $end);
return $countSundays + 1;
};
}
}
|
---
layout: haiku
title: Fur
author: crricks
---
How did hair get there?<br>
An ever present quandry<br>
For the wagging tail<br>
|
package org.pratik;
import twitter4j.Status;
import java.util.HashMap;
import java.util.Map;
public class Result {
private final int sentimentValue;
private final Status status;
private String sentimentString;
public Result(Status status, int sentimentValue) {
this.status = status;
this.sentimentValue = sentimentValue;
Map<Integer, String> sentimentMap = new HashMap<Integer, String>() {{
put(0, "Very Negative");
put(1, "Negative");
put(2, "Neutral");
put(3, "Positive");
put(4, "Very Positive");
}};
this.sentimentString = sentimentMap.get(sentimentValue);
}
public int getSentimentValue() {
return sentimentValue;
}
public Status getStatus() {
return status;
}
public String getSentimentString() {
return sentimentString;
}
}
|
<?php
require_once 'RequestValidate.php';
require_once 'AES.php';
/**
* Version 1.0
*/
class TransactionResponseBean
{
protected $responsePayload = "";
protected $key;
protected $iv;
protected $logPath = "";
protected $blocksize = 128;
protected $mode = "cbc";
/**
* @return the $key
*/
public function getKey()
{
return $this->key;
}
/**
* @return the $iv
*/
public function getIv()
{
return $this->iv;
}
/**
* @return the $logPath
*/
public function getLogPath()
{
return $this->logPath;
}
/**
* @return the $blocksize
*/
public function getBlocksize()
{
return $this->blocksize;
}
/**
* @return the $mode
*/
public function getMode()
{
return $this->mode;
}
/**
* @param number $responsePayload
*/
public function setResponsePayload($responsePayload)
{
$this->responsePayload = $responsePayload;
}
/**
* @param number $key
*/
public function setKey($key)
{
$this->key = $key;
}
/**
* @param long $iv
*/
public function setIv($iv)
{
$this->iv = $iv;
}
/**
* @param string $logPath
*/
public function setLogPath($logPath)
{
$this->logPath = $logPath;
}
/**
* @param number $blocksize
*/
public function setBlocksize($blocksize)
{
$this->blocksize = $blocksize;
}
/**
* @param string $mode
*/
public function setMode($mode)
{
$this->mode = $mode;
}
/**
* This function decrypts the final response and returns it to the merchant.
* @return string $decryptResponse
*/
public function getResponsePayload()
{
try {
$responseParams = array(
'pRes' => $this->responsePayload,
'pEncKey' => $this->key,
'pEncIv' => $this->iv
);
$requestValidateObj = new RequestValidate();
$errorResponse = $requestValidateObj->validateResponseParam($responseParams);
if ($errorResponse) {
return $errorResponse;
}
$aesObj = new AES($this->responsePayload, $this->key, $this->blocksize, $this->mode, $this->iv);
$aesObj->require_pkcs5();
$decryptResponse = trim(preg_replace('/[\x00-\x1F\x7F]/', '', $aesObj->decrypt()));
$implodedResp = explode("|", $decryptResponse);
$hashCodeString = end($implodedResp);
array_pop($implodedResp);
$explodedHashValue = explode("=", $hashCodeString);
$hashValue = trim($explodedHashValue[1]);
$responseDataString = implode("|", $implodedResp);
$generatedHash = sha1($responseDataString);
if ($generatedHash == $hashValue) {
return $decryptResponse;
} else {
return 'ERROR064';
}
} catch (Exception $ex) {
echo "Exception In TransactionResposeBean :" . $ex->getMessage();
return;
}
return "ERROR037";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using X.Core.Utility;
namespace X.App.Com
{
/// <summary>
/// 常规配置
/// </summary>
public class Config
{
/// <summary>
/// 域名
/// </summary>
public string domain { get; set; }
/// <summary>
/// 系统名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 百度key
/// </summary>
public string bdkey { get; set; }
/// <summary>
/// 缓存设置
/// 1、Memcached
/// 2、WebCached
/// </summary>
public int cache { get; set; }
public string wx_appid { get; set; }
public string wx_scr { get; set; }
public string wx_mch_id { get; set; }
/// <summary>
/// 微信证书路径
/// </summary>
public string wx_certpath { get; set; }
public string wx_paykey { get; set; }
private static string file = HttpContext.Current.Server.MapPath("/dat/cfg.x");
private static Config cfg = null;
/// <summary>
/// 获取配置
/// </summary>
/// <returns></returns>
public static Config LoadConfig()
{
if (cfg == null)
{
var json = Tools.ReadFile(file);
if (string.IsNullOrEmpty(json)) return new Config();
cfg = Serialize.FromJson<Config>(json);
}
return cfg;
}
/// <summary>
/// 保存配置
/// </summary>
/// <param name="cfg"></param>
public static void SaveConfig(Config cfg)
{
Tools.SaveFile(HttpContext.Current.Server.MapPath("/dat/cfg.x"), Serialize.ToJson(cfg));
}
}
}
|
#!/usr/bin/env bash
result="$(df "$1"|tail -1)"
used="$(echo "$result"|awk '{print $(NF-3)}')"
total="$(echo "$result"|awk '{print $(NF-2)}')"
free="$((total - used))"
echo "$total $free"
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.vinayaksproject.simpleelasticproject.entity;
import com.vinayaksproject.simpleelasticproject.services.EntityListenerServiceImpl;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Objects;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/**
* This is abstract class to update created and last modified date for all
* entities inheriting this class class will date audit fields and will
* automatically updated when these entities are persisted into the database.
*
* @author vinayak
*/
@MappedSuperclass
@EntityListeners({AuditingEntityListener.class, EntityListenerServiceImpl.class})
public abstract class EntityAudit implements Serializable, Cloneable {
@CreationTimestamp
protected Timestamp creationDate;
@UpdateTimestamp
protected Timestamp lastUpdateDate;
protected boolean deleted;
@Version
protected Integer version;
/**
* @return the creationDate
*/
public Timestamp getCreationDate() {
return creationDate;
}
/**
* @param creationDate the creationDate to set
*/
public void setCreationDate(Timestamp creationDate) {
this.creationDate = creationDate;
}
/**
* @return the lastUpdateDate
*/
public Timestamp getLastUpdateDate() {
return lastUpdateDate;
}
/**
* @param lastUpdateDate the lastUpdateDate to set
*/
public void setLastUpdateDate(Timestamp lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
/**
* @return the deleted
*/
public boolean isDeleted() {
return deleted;
}
/**
* @param deleted the deleted to set
*/
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
/**
* @return the version
*/
public Integer getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(Integer version) {
this.version = version;
}
@Override
public Object clone() throws CloneNotSupportedException {
EntityAudit cloned = (EntityAudit) super.clone();
if (creationDate != null) {
cloned.creationDate = new Timestamp(creationDate.getTime());
}
if (lastUpdateDate != null) {
cloned.lastUpdateDate = new Timestamp(lastUpdateDate.getTime());
}
return cloned;
}
@Override
public int hashCode() {
int hash = 5;
hash = 41 * hash + Objects.hashCode(this.creationDate);
hash = 41 * hash + Objects.hashCode(this.lastUpdateDate);
hash = 41 * hash + (this.deleted ? 1 : 0);
hash = 41 * hash + Objects.hashCode(this.version);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final EntityAudit other = (EntityAudit) obj;
if (this.deleted != other.deleted) {
return false;
}
if (!Objects.equals(this.creationDate, other.creationDate)) {
return false;
}
if (!Objects.equals(this.lastUpdateDate, other.lastUpdateDate)) {
return false;
}
if (!Objects.equals(this.version, other.version)) {
return false;
}
return true;
}
}
|
package models
import (
"database/sql"
"errors"
"fmt"
"strings"
)
type ClientsRepo struct{}
func NewClientsRepo() ClientsRepo {
return ClientsRepo{}
}
func (repo ClientsRepo) Find(conn ConnectionInterface, id string) (Client, error) {
client := Client{}
err := conn.SelectOne(&client, "SELECT * FROM `clients` WHERE `id` = ?", id)
if err != nil {
if err == sql.ErrNoRows {
err = NotFoundError{fmt.Errorf("Client with ID %q could not be found", id)}
}
return client, err
}
return client, nil
}
func (repo ClientsRepo) FindAll(conn ConnectionInterface) ([]Client, error) {
clients := []Client{}
_, err := conn.Select(&clients, "SELECT * FROM `clients`")
if err != nil {
return []Client{}, err
}
return clients, nil
}
func (repo ClientsRepo) Update(conn ConnectionInterface, client Client) (Client, error) {
if client.TemplateID == DoNotSetTemplateID {
existingClient, err := repo.Find(conn, client.ID)
if err != nil {
return client, err
}
client.TemplateID = existingClient.TemplateID
}
_, err := conn.Update(&client)
if err != nil {
return client, err
}
return repo.Find(conn, client.ID)
}
func (repo ClientsRepo) Upsert(conn ConnectionInterface, client Client) (Client, error) {
existingClient, err := repo.Find(conn, client.ID)
client.Primary = existingClient.Primary
client.CreatedAt = existingClient.CreatedAt
switch err.(type) {
case NotFoundError:
client, err := repo.create(conn, client)
if _, ok := err.(DuplicateError); ok {
return repo.Update(conn, client)
}
return client, err
case nil:
return repo.Update(conn, client)
default:
return client, err
}
}
func (repo ClientsRepo) FindAllByTemplateID(conn ConnectionInterface, templateID string) ([]Client, error) {
clients := []Client{}
_, err := conn.Select(&clients, "SELECT * FROM `clients` WHERE `template_id` = ?", templateID)
if err != nil {
return clients, err
}
return clients, nil
}
func (repo ClientsRepo) create(conn ConnectionInterface, client Client) (Client, error) {
err := conn.Insert(&client)
if err != nil {
if strings.Contains(err.Error(), "Duplicate entry") {
err = DuplicateError{errors.New("duplicate record")}
}
return client, err
}
return client, nil
}
|
(ns darkexchange.controller.main.main-menu-bar
(:require [clojure.contrib.logging :as logging]
[darkexchange.controller.actions.utils :as actions-utils]
[seesaw.core :as seesaw-core])
(:import [javax.swing JMenuItem JMenu]))
(defn attach-main-menu-actions [main-frame]
(actions-utils/attach-window-close-and-exit-listener main-frame "#exit-menu-item"))
(defn init [main-frame]
(attach-main-menu-actions main-frame)) |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using WpfMath.Platforms;
using WpfMath.Rendering;
namespace WpfMath.Boxes
{
// Represents graphical box that is part of math expression, and can itself contain child boxes.
public abstract class Box
{
private List<Box> children;
private ReadOnlyCollection<Box> childrenReadOnly;
internal Box(TexEnvironment environment)
: this(environment.Foreground, environment.Background)
{
}
protected Box()
: this(null, null)
{
}
protected Box(Brush foreground, Brush background)
{
this.children = new List<Box>();
this.childrenReadOnly = new ReadOnlyCollection<Box>(this.children);
this.Foreground = foreground;
this.Background = background;
}
public ReadOnlyCollection<Box> Children
{
get { return this.childrenReadOnly; }
}
public SourceSpan Source
{
get;
set;
}
public Brush Foreground
{
get;
set;
}
public Brush Background
{
get;
set;
}
public double TotalHeight
{
get { return this.Height + this.Depth; }
}
public double TotalWidth
{
get { return this.Width + this.Italic; }
}
public double Italic
{
get;
set;
}
public double Width
{
get;
set;
}
public double Height
{
get;
set;
}
public double Depth
{
get;
set;
}
public double Shift
{
get;
set;
}
public abstract void RenderTo(IElementRenderer renderer, double x, double y);
public virtual void Add(Box box)
{
this.children.Add(box);
}
public virtual void Add(int position, Box box)
{
this.children.Insert(position, box);
}
public abstract int GetLastFontId();
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Prime.Models.HealthAuthorities
{
[Table("HealthAuthorityCareType")]
public class HealthAuthorityCareType : BaseAuditable
{
[Key]
public int Id { get; set; }
public int HealthAuthorityOrganizationId { get; set; }
[Required]
public HealthAuthorityOrganization HealthAuthorityOrganization { get; set; }
[Required]
public string CareType { get; set; }
}
}
|
package org.nwnx.nwnx2.jvm.constants;
/**
* This class contains all unique constants beginning with "EVENT_SCRIPT_AREA".
* Non-distinct keys are filtered; only the LAST appearing was
* kept.
*/
public final class EventScriptArea {
private EventScriptArea() {}
public final static int ON_ENTER = 4002;
public final static int ON_EXIT = 4003;
public final static int ON_HEARTBEAT = 4000;
public final static int ON_USER_DEFINED_EVENT = 4001;
public static String nameOf(int value) {
if (value == 4002) return "EventScriptArea.ON_ENTER";
if (value == 4003) return "EventScriptArea.ON_EXIT";
if (value == 4000) return "EventScriptArea.ON_HEARTBEAT";
if (value == 4001) return "EventScriptArea.ON_USER_DEFINED_EVENT";
return "EventScriptArea.(not found: " + value + ")";
}
public static String nameOf(float value) {
return "EventScriptArea.(not found: " + value + ")";
}
public static String nameOf(String value) {
return "EventScriptArea.(not found: " + value + ")";
}
}
|
using System;
// Console.WriteLine("Enter two words you might think is are anagrams of one another.");
// string s1 = Console.ReadLine();
// string s2 = Console.ReadLine();
// static bool Anagram (string s1, string s2){
// if(s1.Length == s2.Length){
// return true;
// }
// else{
// return false;
// }
// }
static bool Palindrome (string s){
return true;
}
// find a way to read the char from the first index and compare it to the last char at the last index.
// if true, continue the loop, if not, exit the loop
//palindrome program
Console.WriteLine("Enter a word you might think could be a palindrome:");
string pali = Console.ReadLine();
pali = pali.ToLower(); // <- turning input to all lowercase if there's any capitals anywhere
string reverse = ""; // <- empty string
for (int i = pali.Length - 1; i >= 0; i--) // <- for loop to get all the letters from right to left
{
reverse += pali[i]; // <- storing the reversed word into a string var: reverse
}
if (pali == reverse)
{
Console.WriteLine("This is a palindrome"); // <- if it matches
}
else
{
Console.WriteLine("That's not a palindrome"); // <- if it doesn't match
}
|
/*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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.*/
#include "stdafx.h"
#include "DumpStream.h"
#include "matrix.h"
//-----------------------------------------------------------------------------
DumpStream::DumpStream(FEModel& fem) : m_fem(fem)
{
m_bsave = false;
m_bshallow = false;
m_bytes_serialized = 0;
m_ptr_lock = false;
}
//-----------------------------------------------------------------------------
//! See if the stream is used for input or output
bool DumpStream::IsSaving() const { return m_bsave; }
//-----------------------------------------------------------------------------
//! See if the stream is used for input
bool DumpStream::IsLoading() const { return !m_bsave; }
//-----------------------------------------------------------------------------
//! See if shallow flag is set
bool DumpStream::IsShallow() const { return m_bshallow; }
//-----------------------------------------------------------------------------
DumpStream::~DumpStream()
{
m_ptr.clear();
m_bytes_serialized = 0;
}
//-----------------------------------------------------------------------------
void DumpStream::Open(bool bsave, bool bshallow)
{
m_bsave = bsave;
m_bshallow = bshallow;
m_bytes_serialized = 0;
m_ptr_lock = false;
// add the "null" pointer
m_ptr.clear();
Pointer p = { 0, 0 };
m_ptr.push_back(p);
}
//-----------------------------------------------------------------------------
void DumpStream::check()
{
if (IsSaving())
{
write(&m_bytes_serialized, sizeof(m_bytes_serialized), 1);
}
else
{
size_t nsize;
read(&nsize, sizeof(m_bytes_serialized), 1);
assert(m_bytes_serialized == nsize);
if (m_bytes_serialized != nsize) throw DumpStream::ReadError();
}
}
//-----------------------------------------------------------------------------
void DumpStream::LockPointerTable()
{
m_ptr_lock = true;
}
//-----------------------------------------------------------------------------
void DumpStream::UnlockPointerTable()
{
m_ptr_lock = false;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator << (const char* sz)
{
int n = (sz ? (int)strlen(sz) : 0);
m_bytes_serialized += write(&n, sizeof(int), 1);
if (sz) m_bytes_serialized += write(sz, sizeof(char), n);
return (*this);
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator << (char* sz)
{
int n = (sz ? (int)strlen(sz) : 0);
m_bytes_serialized += write(&n, sizeof(int), 1);
if (sz) m_bytes_serialized += write(sz, sizeof(char), n);
return (*this);
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator<<(std::string& s)
{
const char* sz = s.c_str();
this->operator<<(sz);
return *this;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator<<(const std::string& s)
{
const char* sz = s.c_str();
this->operator<<(sz);
return *this;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator << (bool b)
{
int n = (b ? 1 : 0);
m_bytes_serialized += write(&n, sizeof(n), 1);
return *this;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator << (int n)
{
m_bytes_serialized += write(&n, sizeof(int), 1);
return *this;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator << (const double a[3][3])
{
m_bytes_serialized += write(a, sizeof(double), 9);
return (*this);
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator >> (char* sz)
{
int n;
m_bytes_serialized += read(&n, sizeof(int), 1);
if (n>0) m_bytes_serialized += read(sz, sizeof(char), n);
sz[n] = 0;
return (*this);
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator >> (std::string& s)
{
int n;
m_bytes_serialized += read(&n, sizeof(int), 1);
char* tmp = new char[n + 1];
if (n > 0) m_bytes_serialized += read(tmp, sizeof(char), n);
tmp[n] = 0;
s = std::string(tmp);
delete [] tmp;
return *this;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator >> (bool& b)
{
int n;
m_bytes_serialized += read(&n, sizeof(int), 1);
b = (n == 1);
return *this;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::operator >> (double a[3][3])
{
m_bytes_serialized += read(a, sizeof(double), 9);
return (*this);
}
//-----------------------------------------------------------------------------
int DumpStream::FindPointer(void* p)
{
for (int i = 0; i < (int)m_ptr.size(); ++i)
{
if (m_ptr[i].pd == p) return i;
}
return -1;
}
//-----------------------------------------------------------------------------
int DumpStream::FindPointer(int id)
{
for (int i = 0; i < (int)m_ptr.size(); ++i)
{
if (m_ptr[i].id == id) return i;
}
return -1;
}
//-----------------------------------------------------------------------------
void DumpStream::AddPointer(void* p)
{
if (m_ptr_lock) return;
if (p == nullptr) { assert(false); return; }
assert(FindPointer(p) == -1);
Pointer ptr;
ptr.pd = p;
ptr.id = (int)m_ptr.size();
m_ptr.push_back(ptr);
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::write_matrix(matrix& o)
{
DumpStream& ar = *this;
int nr = o.rows();
int nc = o.columns();
ar << nr << nc;
int nsize = nr*nc;
if (nsize > 0)
{
vector<double> data;
data.reserve(nr*nc);
for (int i = 0; i < nr; ++i)
for (int j = 0; j < nc; ++j) data.push_back(o(i, j));
ar << data;
}
return *this;
}
//-----------------------------------------------------------------------------
DumpStream& DumpStream::read_matrix(matrix& o)
{
DumpStream& ar = *this;
int nr = 0, nc = 0;
ar >> nr >> nc;
int nsize = nr*nc;
if (nsize > 0)
{
o.resize(nr, nc);
vector<double> data;
ar >> data;
int n = 0;
for (int i = 0; i < nr; ++i)
for (int j = 0; j < nc; ++j) o(i, j) = data[n++];
}
return *this;
}
|
require 'music_ids/grid'
module MusicIds
RSpec.describe GRid do
context "parsing" do
context "well-formed inputs" do
let(:expected) { GRid.new('A12425GABC1234002M') }
specify { expect(GRid.parse('A1-2425G-ABC1234002-M')).to eq(expected) }
specify { expect(GRid.parse('A12425GABC1234002M')).to eq(expected) }
specify { expect(GRid.parse('GRID:A1-2425G-ABC1234002-M')).to eq(expected) }
specify { expect(GRid.parse('GRID:A12425GABC1234002M')).to eq(expected) }
specify { expect(GRid.parse('grid:A12425GABC1234002M')).to eq(expected) }
specify { expect(GRid.parse('a12425gabc1234002m')).to eq(expected) }
specify { expect(GRid.parse('A12425GABC1234002M').ok?).to be(true) }
end
it "parses an existing instance" do
grid = GRid.new('A12425GABC1234002M')
expect(GRid.parse(grid)).to eq(grid)
end
context "strict parsing" do
it "will not parse a string that's not long enough" do
expect { GRid.parse('A12425G') }.to raise_error(ArgumentError)
end
it "will not parse a non-A1 identifer scheme element" do
expect { GRid.parse('B1-2425G-ABC1234002-M') }.to raise_error(ArgumentError)
end
it "will not parse a string with only some hyphens" do
expect { GRid.parse('A1-2425G-ABC1234002M') }.to raise_error(ArgumentError)
end
it "will not parse non A-Z 0-9 anywwhere" do
expect { GRid.parse('A1~425GABC1234002M') }.to raise_error(ArgumentError)
expect { GRid.parse('A12425GA_C1234002M') }.to raise_error(ArgumentError)
expect { GRid.parse('A12425GABC1234002*') }.to raise_error(ArgumentError)
end
it "will not pass through a bad instance" do
bad_grid = GRid.parse('A12425G', relaxed: true)
expect { GRid.parse(bad_grid) }.to raise_error(ArgumentError)
end
it "will not pass through nil" do
expect { GRid.parse(nil) }.to raise_error(ArgumentError)
end
end
context "relaxed parsing" do
it "marks a bad input string instead of raising" do
expect(GRid.parse('A12425G', relaxed: true).ok?).to be(false)
end
it "does no normalisation on a bad input string" do
expect(GRid.parse('a12425g', relaxed: true).to_s).to eq('a12425g')
end
it "passes through nil" do
expect(GRid.parse(nil, relaxed: true)).to be_nil
end
it "handles good inputs exactly as strict does" do
expect(GRid.parse('A12425GABC1234002M', relaxed: true).ok?).to be(true)
end
it "provides .relaxed as a convenience method" do
grid = GRid.new('A12425GABC1234002M')
expect(GRid.relaxed('A12425GABC1234002M')).to eq(grid)
end
end
end
context "an instance" do
let(:grid) { GRid.new('A12425GABC1234002M') }
it "reports the identifier scheme" do
expect(grid.scheme).to eq('A1')
end
it "reports the issuer code element" do
expect(grid.issuer).to eq('2425G')
end
it "reports the release number element" do
expect(grid.release).to eq('ABC1234002')
end
it "reports the check character element" do
expect(grid.check).to eq('M')
end
context "returning a string" do
it "reports the full grid string" do
expect(grid.to_s).to eq('A12425GABC1234002M')
end
it "returns a copy of the string so it remains immutable" do
mutated = grid.to_s << 'mutated'
expect(mutated).to_not eq(grid.to_s)
end
end
context "a bad GRid instance" do
let(:grid) { GRid.new('A12425G', ok: false) }
it "will not report the identifier scheme" do
expect(grid.scheme).to be_nil
end
it "will not report the issuer code element" do
expect(grid.issuer).to be_nil
end
it "will not report the release number element" do
expect(grid.release).to be_nil
end
it "will not report the check character" do
expect(grid.check).to be_nil
end
it "returns the bad GRid string as usual" do
expect(grid.to_s).to eq('A12425G')
end
end
it "returns itself when to_grid called" do
expect(grid.to_grid).to be(grid)
end
it "compares equal with itself" do
expect(grid).to eq(grid)
end
it "compares equal with another GRid instance of the same GRid string" do
expect(grid).to eq(GRid.new(grid.to_s))
end
end
context "string representation" do
let(:grid) { GRid.new('A12425GABC1234002M') }
it "can generate a full (hyphenated) string representation for presentation uses" do
expect(grid.as(:full)).to eq('A1-2425G-ABC1234002-M')
end
it "can generate a (non-hyphenated) string representation for data uses" do
expect(grid.as(:data)).to eq('A12425GABC1234002M')
end
it "can generate a prefixed full version of the string" do
expect(grid.as(:prefixed)).to eq('GRID:A1-2425G-ABC1234002-M')
end
it "requesting another format raises an ArgumentError" do
expect { grid.as(:other) }.to raise_error(ArgumentError)
end
it "the data format is identical to the to_s format" do
expect(grid.as(:data)).to eq(grid.to_s)
end
context "a bad GRid" do
let(:grid) { GRid.new('A1-2425G', ok: false) }
it "the :full format just returns the to_s format" do
expect(grid.as(:full)).to eq('A1-2425G')
end
end
end
context "JSON generation" do
let(:grid) { GRid.new('A12425GABC1234002M') }
it "uses the to_s rep for as_json" do
expect(grid.as_json).to eq(grid.to_s)
end
end
end
end
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RoyLab.QData.Demo.Data;
using RoyLab.QData.Demo.Model;
namespace RoyLab.QData.Demo.Controllers
{
[Route("api/[controller]")]
public class UserController : Controller
{
private readonly DbContext dbContext;
public UserController(UserDbContext dbContext)
{
this.dbContext = dbContext;
}
[HttpGet]
public IActionResult Query([FromQuery] string selector, [FromQuery] string filter, [FromQuery] string orderBy)
{
var result = dbContext.Set<UserModel>()
.QueryDynamic(selector, filter, orderBy);
return Ok(result);
}
}
} |
use crate::codegen::{OptimizationLevel, TargetProperties};
use inkwell::attribute::AttrKind;
use inkwell::builder::Builder;
use inkwell::context::Context;
use inkwell::module::Module;
use inkwell::values::FunctionValue;
pub struct BuilderContext<'a> {
pub context: &'a Context,
pub module: &'a Module,
pub func: FunctionValue,
pub allocb: &'a mut Builder,
pub b: &'a mut Builder,
pub target: &'a TargetProperties,
}
pub fn build_context_function(
module: &Module,
function: FunctionValue,
target: &TargetProperties,
cb: &Fn(BuilderContext),
) {
let context = module.get_context();
// assign some useful attributes to the function
function
.add_attribute(context.get_string_attr("correctly-rounded-divide-sqrt-fp-math", "false"));
function.add_attribute(context.get_string_attr("disable-tail-calls", "false"));
function.add_attribute(context.get_string_attr("less-precise-fpmad", "false"));
function.add_attribute(context.get_string_attr("no-frame-pointer-elim", "false"));
function.add_attribute(context.get_string_attr("no-infs-fp-math", "true"));
function.add_attribute(context.get_string_attr("no-jump-tables", "false"));
function.add_attribute(context.get_string_attr("no-nans-fp-math", "true"));
function.add_attribute(context.get_string_attr("no-signed-zeros-fp-math", "true"));
function.add_attribute(context.get_string_attr("no-trapping-math", "true"));
function.add_attribute(context.get_string_attr("denorms-are-zero", "true"));
function.add_attribute(context.get_string_attr("denormal-fp-math", "positive-zero"));
function.add_attribute(context.get_string_attr(
"target-features",
target.machine.get_feature_string().to_str().unwrap(),
));
function.add_attribute(context.get_string_attr("unsafe-fp-math", "true"));
function.add_attribute(context.get_string_attr("use-soft-float", "false"));
function.add_attribute(context.get_enum_attr(AttrKind::NoRecurse, 0));
function.add_attribute(context.get_enum_attr(AttrKind::NoUnwind, 0));
if target.optimization_level == OptimizationLevel::MinSize {
function.add_attribute(context.get_enum_attr(AttrKind::OptimizeForSize, 0));
}
if target.optimization_level == OptimizationLevel::AggressiveSize {
function.add_attribute(context.get_enum_attr(AttrKind::MinSize, 0));
}
let alloca_block = context.append_basic_block(&function, "alloca");
let mut alloca_builder = context.create_builder();
alloca_builder.set_fast_math_all();
alloca_builder.position_at_end(&alloca_block);
let main_block = context.append_basic_block(&function, "main");
let mut builder = context.create_builder();
builder.set_fast_math_all();
builder.position_at_end(&main_block);
cb(BuilderContext {
context: &context,
module,
func: function,
allocb: &mut alloca_builder,
b: &mut builder,
target,
});
// ensure the alloca block jumps to the main block
alloca_builder.build_unconditional_branch(&main_block);
}
|
import 'dart:convert';
import 'package:meta/meta.dart';
import '../../../core.dart';
import '../../core/errors.dart';
import '../../model/frappe/interfaces.dart';
import '../log.manager.dart';
import 'errors.dart';
/// Class for handling Frappe-specific Logs
class FrappeLogManager extends RenovationController implements LogManager {
FrappeLogManager(RenovationConfig config) : super(config);
/// The private def. tags
final List<String> _defaultTags = [];
@override
void clearCache() => _defaultTags.clear();
/// Use this function to set the basic set of tags to be set for the logs raised from the client side
void setDefaultTags(List<String> tags) => _defaultTags.setAll(0, tags);
@override
ErrorDetail handleError(String errorId, ErrorDetail error) =>
RenovationController.genericError(error);
@override
Future<RequestResponse<FrappeLog>> error(
{@required String content, String title, List<String> tags}) {
if (content == null || content.isEmpty) {
throw EmptyContentError();
}
return invokeLogger(
cmd: 'renovation_core.utils.logging.log_error',
content: content,
title: title,
tags: tags);
}
@override
Future<RequestResponse<FrappeLog>> info(
{@required String content, String title, List<String> tags}) {
if (content == null || content.isEmpty) {
throw EmptyContentError();
}
return invokeLogger(
cmd: 'renovation_core.utils.logging.log_info',
content: content,
title: title,
tags: tags);
}
@override
Future<RequestResponse<FrappeLog>> warning(
{@required String content, String title, List<String> tags}) {
if (content == null || content.isEmpty) {
throw EmptyContentError();
}
return invokeLogger(
cmd: 'renovation_core.utils.logging.log_warning',
content: content,
title: title,
tags: tags);
}
@override
Future<RequestResponse<FrappeLog>> logRequest(
{@required RequestResponse<dynamic> r, List<String> tags}) {
if (r == null) {
throw EmptyResponseError();
}
final _tags = ['frontend-request'];
if (tags != null) {
_tags.addAll(tags);
}
final req = r.rawResponse.request;
final requestInfo =
'Headers:\n${req.headers}\nParams:\n${json.encode(req.data)}';
final headersInfo = <List<String>>[];
r.rawResponse.headers.map.forEach((String k, List<String> value) {
headersInfo.add([k, ...value]);
});
var header = '';
headersInfo.forEach((List<String> headerInfo) {
header += '${headerInfo[0]}: ${headerInfo[1]}\n';
});
final responseInfo =
'Status: ${r.rawResponse.statusCode}\nHeaders:\n$header\n\nBody:\n${json.encode(r.rawResponse.data)}';
return invokeLogger(
cmd: 'renovation_core.utils.logging.log_client_request',
request: requestInfo,
response: responseInfo,
tags: _tags);
}
@override
Future<RequestResponse<FrappeLog>> invokeLogger(
{@required String cmd,
String content,
String title,
List<String> tags,
String request,
String response}) async {
await getFrappe().checkAppInstalled(features: ['Logger']);
tags ?? _defaultTags;
final logResponse = await config.coreInstance.call(<String, dynamic>{
'cmd': cmd,
'content': content,
'title': title,
'tags': tags != null ? json.encode(tags) : null,
'request': request,
'response': response
});
if (logResponse.isSuccess) {
List<dynamic> tagsDoc = logResponse.data.message['tags'];
if (logResponse.data.message != null && tagsDoc != null) {
final tags = tagsDoc.map<String>((dynamic x) => x['tag']).toList();
logResponse.data.message.addAll({'tags_list': tags});
}
return RequestResponse.success<FrappeLog>(
FrappeLog.fromJson(logResponse.data.message),
rawResponse: logResponse.rawResponse);
} else {
return RequestResponse.fail(handleError(null, logResponse.error));
}
}
}
|
## Start with SCM task
Hint:
Use the [`git`](https://jenkins.io/doc/pipeline/steps/git/#git-git) step to clone this repository. |
package org.jctools.maps;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NBHMReplaceTest {
@Test
public void replaceOnEmptyMap() {
assertEquals(null, new NonBlockingHashMap<String,String>().replace("k", "v"));
}
@Test
public void replaceOnEmptyIdentityMap() {
assertEquals(null, new NonBlockingIdentityHashMap<String,String>().replace("k", "v"));
}
@Test
public void replaceOnEmptyLongMap() {
assertEquals(null, new NonBlockingHashMapLong<String>().replace(1, "v"));
}
}
|
/*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { posix as path } from 'path';
export { isValidRelpath } from 'analyticsdx-template-lint';
const whitespaceRe = /^\s$/;
export function isWhitespaceChar(ch: string) {
return whitespaceRe.test(ch);
}
export function isUriPathUnder(parent: string, file: string): boolean {
const rel = path.relative(parent, file);
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
}
export function isSameUriPath(path1: string, path2: string): boolean {
return path.relative(path1, path2) === '';
}
/** Match a filepath's extension.
* @param filepath the filepath
* @param exts the set of file extensions that match, case-insensitive, do not include the leading '.'
*/
export function matchesFileExtension(filepath: string, ...exts: string[]): boolean {
const i = filepath.lastIndexOf('.');
const found = i >= 0 ? filepath.substring(i + 1).toLocaleLowerCase() : '';
return exts.some(ext => ext.toLocaleLowerCase() === found);
}
/** Generate a function that matches a filepath's extension.
* @param exts the set of file extensions that match, case-insensitive, do not include the leading '.'
*/
export function newFileExtensionFilter(...exts: string[]): (s: string) => boolean {
return s => matchesFileExtension(s, ...exts);
}
|
require 'find'
require 'fileutils'
module Cubist
class SourceFilesFinder
def initialize(conf:)
@conf = conf
end
def run(relative: false)
files = get_files
if relative
files = files.map { |x| x.gsub(/^#{@conf.cubist_folder_full_path}\//, '') }
end
files
end
def get_angles
get_files.select { |x| x =~ /\.cubist_angle$/ }.map { |x| x.gsub(/\/.cubist_angle$/, '') }
end
private def get_files
dir = @conf.cubist_folder_full_path
results = []
Find.find(dir) do |path|
if FileTest.directory?(path)
if File.basename(path)[0] == '.' && File.basename(path) != '.'
Find.prune
else
next
end
else
results << path if File.basename(path) != '.DS_Store'
end
end
results
end
end
end
|
package com.crazylegend.datastructuresandalgorithms.sort.quickSort
/**
* The naive partitioning creates a new list on every filter function; this is inefficient.
* @receiver List<T>
* @return List<T>
*/
fun <T : Comparable<T>> List<T>.quicksortNaive(): List<T> {
if (this.size < 2) return this
val pivot = this[this.size / 2]
val less = this.filter { it < pivot }
val equal = this.filter { it == pivot }
val greater = this.filter { it > pivot }
return less.quicksortNaive() + equal + greater.quicksortNaive()
} |
# frozen_string_literal: true
module PicoRubeme
def self.evaluator
Evaluator.new
end
class Evaluator < Component
def eval(obj, env)
obj
end
end
end
|
*+ spi_put_header
subroutine spi_put_header( id, info, items, values, status )
C ------------------------------------------------------------
C
C Put header information into an internal spectrum file
C
implicit NONE
C
C Given:
C spectrum identifier
integer id
C info header block
integer info(*)
C character items list
character*(*) items(*)
C character values associated with the items list
character*(*) values(*)
C Updated:
C status return code
integer status
C
C The supplied header information is put into / associated with the
C specified internal spectrum file id
C-
include 'spec_global.inc'
include 'spec_data.inc'
include 'spec_control.inc'
include 'spec_errors.inc'
C Local variables
integer i
character*80 string
C check status on entry
if (status.ne.0) return
C check allocation
call spi_check_id(id,status)
if (status.ne.0) goto 999
if (control_records(alloc,id).eq.alloc_none) then
status = ill_alloc
write(string,'(A,I3)') 'Spectrum not allocated ID = ',ID
call spi_err(status,'SPI_PUT_HEADER',string)
goto 999
end if
C put header information
do i=1,max_standard_info
spec_hdi(i,id) = info(i)
end do
do i=1,info(3)
spec_hdc(i,id)(1:len_item_name) = items(i)
spec_hdc(i,id)(1+len_item_name:len_item_name+len_item_data)
* = values(i)
end do
999 if (status.ne.0) then
call spi_err(status,'SPI_PUT_HEADER',' ')
end if
end
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class woodPackerTargetMove : MonoBehaviour
{
private void Update() {
if(woodPacker.transform.position.x - transform.position.x <= 0)
transform.position = Vector3.Slerp(transform.position, target.position, 1.5f * Time.deltaTime);
}
public Transform target;
public Transform woodPacker;
}
|
package functions
import config.paramconf.PreprocessParams
import functions.clean.Cleaner
import functions.segment.Segmenter
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.feature.{CountVectorizer, IDF, StopWordsRemover, StringIndexer}
import org.apache.spark.sql.DataFrame
/**
* Created by yhao on 2017/3/15.
*/
class Preprocessor extends Serializable {
/**
* 预处理过程,包括数据清洗、标签索引化、分词、去除停用词、向量化、转换tf-idf
*
* @param data 输入数据,注意必须包含content列,作为预处理的对象
* @return pipeline
*/
def preprocess(data: DataFrame): Pipeline = {
val spark = data.sparkSession
val params = new PreprocessParams
val indexModel = new StringIndexer()
.setHandleInvalid(params.handleInvalid)
.setInputCol("label")
.setOutputCol("indexedLabel")
.fit(data)
val cleaner = new Cleaner()
.setFanJian(params.fanjian)
.setQuanBan(params.quanban)
.setMinLineLen(params.minLineLen)
.setInputCol("content")
.setOutputCol("cleand")
val segmenter = new Segmenter()
.isAddNature(params.addNature)
.isDelEn(params.delEn)
.isDelNum(params.delNum)
.isNatureFilter(params.natureFilter)
.setMinTermLen(params.minTermLen)
.setMinTermNum(params.minTermNum)
.setSegType(params.segmentType)
.setInputCol(cleaner.getOutputCol)
.setOutputCol("segmented")
val stopwords = spark.sparkContext.textFile(params.stopwordFilePath).collect()
val remover = new StopWordsRemover()
.setStopWords(stopwords)
.setInputCol(segmenter.getOutputCol)
.setOutputCol("removed")
val vectorizer = new CountVectorizer()
.setMinTF(params.minTF)
.setVocabSize(params.vocabSize)
.setInputCol(remover.getOutputCol)
.setOutputCol("vectorized")
val idf = new IDF()
.setMinDocFreq(params.minDocFreq)
.setInputCol(vectorizer.getOutputCol)
.setOutputCol("features")
val stages = Array(cleaner, indexModel, segmenter, remover, vectorizer, idf)
new Pipeline().setStages(stages)
}
}
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.feature 'Header Links' do
scenario 'When the user is not signed in' do
visit root_path
within '.navbar' do
expect(page).to have_link(I18n.t('devise.shared.links.sign_up'), href: new_user_registration_path, count: 1)
expect(page).to have_link(I18n.t('devise.shared.links.sign_in'), href: new_user_session_path, count: 1)
expect(page).not_to have_link(nil, href: destroy_user_session_path, visible: false)
expect(page).not_to have_link(nil, href: new_question_path)
end
end
scenario 'When the user is signed in' do
user = FactoryGirl.create(:confirmed_user)
login_as user
visit root_path
within '.navbar' do
expect(page).to have_text(user.username)
find('.user-menu').click # Toggle dropdown
expect(page).to have_link(I18n.t('shared.links.new_question'), href: new_question_path, count: 1)
expect(page).to have_link(I18n.t('shared.links.sign_out'), href: destroy_user_session_path, count: 1)
expect(page).not_to have_link(nil, href: new_user_registration_path)
expect(page).not_to have_link(nil, href: new_user_session_path)
end
end
end
|
Ingredienser
---
* 1kg kycklingbröstfilé (meh) eller kycklinglårfilé (bäst)
* 2st gula lökar
* 5dl chili creme fraiche
* 3-6 vitlöksklyftor efter egen smak
* Olivolja
* Curry (högst en hel burk, om du är tokig nog)
* Salt
* Sweet Chili sås
* Chiliflakes
* Honung
Instruktioner
---
1. Skär upp kycklingen i ätbara bitar
2. Börja koka ris (referera till hur man kokar ris på bästa sätt)
2. Tärna och fräs gullöken i olivolja
3. Bryn kycklingen i samma traktörpanna
4. Häll på vatten tills det täcker-ish kycklingen
5. Medans det reduceras, tillsätt din egna lagom mängd curry, vitlök, salt, sweet chili sås och chiliflakes
6. Häv i creme fraichen när det knappt är vatten kvar i såsen, rör sedan runt och beundra den fina gula nyansen
7. Slå av värmen och tillsätt nog med honung att väga upp mot chilihettan
8. Servera nån skopa gryta på riset i en djuptallrik
|
package com.alexvanyo.sportsfeed.ui
import androidx.recyclerview.widget.DiffUtil
import com.alexvanyo.sportsfeed.R
import com.alexvanyo.sportsfeed.api.Competition
import com.alexvanyo.sportsfeed.databinding.StatisticItemBinding
import com.alexvanyo.sportsfeed.util.DataBoundListAdapter
class StatisticAdapter : DataBoundListAdapter<Competition.PairedStatistic, StatisticItemBinding>(
R.layout.statistic_item,
object : DiffUtil.ItemCallback<Competition.PairedStatistic>() {
override fun areItemsTheSame(
oldItem: Competition.PairedStatistic,
newItem: Competition.PairedStatistic
): Boolean = oldItem.name == newItem.name
override fun areContentsTheSame(
oldItem: Competition.PairedStatistic,
newItem: Competition.PairedStatistic
): Boolean = oldItem == newItem
}
) {
override fun bind(binding: StatisticItemBinding, item: Competition.PairedStatistic) {
binding.pairedStatistic = item
}
} |
import 'package:flutter/material.dart';
import 'package:sc_credenciamento/pages/cred.page.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'pres.page.dart';
import 'package:splashscreen/splashscreen.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _exibirDialogo() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Sincronização Concluída"),
content: new Text("Pressione ok para continuar"),
actions: <Widget>[
// define os botões na base do dialogo
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void _sync() async{
await Firestore.instance.collection("Atividades").document("Sync").setData({
});
_exibirDialogo();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[200],
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const SizedBox(height: 0),
RaisedButton(
color: Colors.white,
textColor: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CredPage()),
);
},
child: const Text('CREDENCIAMENTO',
style: TextStyle(fontSize: 30, fontStyle: FontStyle.italic)),
),
const SizedBox(height: 100),
RaisedButton(
color: Colors.white,
textColor: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PresPage()),
);
},
child: const Text(' PRESENÇA\n EM\nATIVIDADES',
style: TextStyle(fontSize: 30, fontStyle: FontStyle.italic)),
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sync,
tooltip: 'Sincronizar',
child: Icon(Icons.autorenew),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
|
class ProcPeriodWorker
include Sidekiq::Worker
sidekiq_options throttle: { threshold: 10, period: Proc.new { |user_id, period| period } }
def perform(user_id, period)
puts user_id
puts period
end
end
|
#!/bin/sh
echo "Stopping previous session"
sh stop.sh > /dev/null
mkdir -p data # Creates data folder, if it doesn't exist
mkdir -p public/tracks
mkdir -p public/thumbnails
# Starts a tmux session named "spotyourmusic" and detaches
# Starts Redis instance, worker and webserver
# (DISABLED) Evenly distributes the window sizes, vertically
echo "Starting new session"
tmux \
new-session -d -s "spotyourmusic" \
"cd data && redis-server ; read" \; \
split-window "node worker.js ; read" \; \
split-window ". ~/.profile && node index.js ; read" \; \
#select-layout even-vertical
|
#!/bin/bash
echo "Installing ProtonMail Bridge..."
brew install protonmail-bridge
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.