content
stringlengths
10
4.9M
<gh_stars>0 import { useEffect, useRef, useState } from "react"; import { useIntersection } from "react-use"; type Props = { slug: string; // "owner/name" date: string; // "owner/name" width: number | string; height?: number | string; }; export function RepositoryStats(props: Props) { const { slug, date, width, height = 160 } = props; const [initialized, setInitialized] = useState(false); const intersectionRef = useRef(null); const chartRef = useRef(null); const intersection = useIntersection(intersectionRef, { root: null, rootMargin: "0px", threshold: 1, }); useEffect(() => { setInitialized((prev) => !!(prev || intersection?.isIntersecting)); }, [setInitialized, intersection?.isIntersecting]); useEffect(() => { if (!initialized) { return; } Promise.all([ import("apexcharts").then((mod) => mod.default), fetch(`/api/stats?slug=${slug}&date=${date}`, {}).then((res) => res.json() ), ] as const).then(([ApexCharts, data]) => { const formatter = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", }); const chart = new ApexCharts(chartRef.current, { chart: { type: "line", width, height, animations: { enabled: false }, toolbar: { show: false }, }, stroke: { curve: "smooth" }, series: [ { type: "line", data: data.map((d: { date: string; value: number }) => d.value), }, ], xaxis: { categories: data.map((d: { date: string; value: number }) => { const date = new Date(d.date); if (date.getHours() === 0) { return formatter.format(date).slice(0, -6); } return ""; }), }, tooltip: { enabled: false }, }); chart.render(); }); }, [initialized, slug, date]); return ( <div style={{ padding: 1 }}> <div ref={intersectionRef} style={{ width, height }}> <div ref={chartRef} /> </div> </div> ); }
/** * Starts fetching daily strips once per day at the given number of minutes * past midnight local time. * * @param settings a configuration object that specifies the user's preferred * download settings. * * @throws NullPointerException if <code>settings</code> is null. */ public void startPeriodicFetching(final UnattendedDownloadSettings settings) { Objects.requireNonNull(settings); if (timer != null) { timer.cancel(); } if (settings.isFetchStripAutomatically()) { final long delay = getDelayBeforeNextDownload(settings.getLocalDownloadTime()); final int fetchInterval = settings.getFetchInterval(); final int maxFetchAttempts = settings.getMaxFetchAttempts(); timer = new Timer(true); LOGGER.info( MessageFormat.format("The next download is scheduled to occur in {0}ms", delay)); timer.scheduleAtFixedRate(new TimerTask() { public void run() { LOGGER.info("It's time to see if there's a new Dilbert strip available..."); timer.schedule(new SelfCancellingStripFetcherTask(maxFetchAttempts), 0, new Integer(TimeUtils.MILLIS_PER_MINUTE * fetchInterval).longValue()); } }, delay, TimeUtils.MILLIS_PER_DAY); } }
<gh_stars>1-10 import { Service, Inject } from 'typedi'; import { Repository, SelectQueryBuilder } from 'typeorm'; import { InjectRepository } from 'typeorm-typedi-extensions'; import { WhereInput, HydraBaseService } from '@subsquid/warthog'; import { Account } from './account.model'; import { AccountWhereArgs, AccountWhereInput } from '../../warthog'; import { HistoricalBalance } from '../historical-balance/historical-balance.model'; import { HistoricalBalanceService } from '../historical-balance/historical-balance.service'; import { getConnection, getRepository, In, Not } from 'typeorm'; import _ from 'lodash'; @Service('AccountService') export class AccountService extends HydraBaseService<Account> { @Inject('HistoricalBalanceService') public readonly historicalBalancesService!: HistoricalBalanceService; constructor(@InjectRepository(Account) protected readonly repository: Repository<Account>) { super(Account, repository); } async find<W extends WhereInput>( where?: any, orderBy?: string | string[], limit?: number, offset?: number, fields?: string[] ): Promise<Account[]> { return this.findWithRelations<W>(where, orderBy, limit, offset, fields); } findWithRelations<W extends WhereInput>( _where?: any, orderBy?: string | string[], limit?: number, offset?: number, fields?: string[] ): Promise<Account[]> { return this.buildFindWithRelationsQuery(_where, orderBy, limit, offset, fields).getMany(); } buildFindWithRelationsQuery<W extends WhereInput>( _where?: any, orderBy?: string | string[], limit?: number, offset?: number, fields?: string[] ): SelectQueryBuilder<Account> { const where = <AccountWhereInput>(_where || {}); // remove relation filters to enable warthog query builders const { historicalBalances_some, historicalBalances_none, historicalBalances_every } = where; if (+!!historicalBalances_some + +!!historicalBalances_none + +!!historicalBalances_every > 1) { throw new Error(`A query can have at most one of none, some, every clauses on a relation field`); } delete where.historicalBalances_some; delete where.historicalBalances_none; delete where.historicalBalances_every; let mainQuery = this.buildFindQueryWithParams(<any>where, orderBy, undefined, fields, 'main').take(undefined); // remove LIMIT let parameters = mainQuery.getParameters(); const historicalBalancesFilter = historicalBalances_some || historicalBalances_none || historicalBalances_every; if (historicalBalancesFilter) { const historicalBalancesQuery = this.historicalBalancesService .buildFindQueryWithParams(<any>historicalBalancesFilter, undefined, undefined, ['id'], 'historicalBalances') .take(undefined); //remove the default LIMIT parameters = { ...parameters, ...historicalBalancesQuery.getParameters() }; const subQueryFiltered = this.getQueryBuilder() .select([]) .leftJoin( 'account.historicalBalances', 'historicalBalances_filtered', `historicalBalances_filtered.id IN (${historicalBalancesQuery.getQuery()})` ) .groupBy('account_id') .addSelect('count(historicalBalances_filtered.id)', 'cnt_filtered') .addSelect('account.id', 'account_id'); const subQueryTotal = this.getQueryBuilder() .select([]) .leftJoin('account.historicalBalances', 'historicalBalances_total') .groupBy('account_id') .addSelect('count(historicalBalances_total.id)', 'cnt_total') .addSelect('account.id', 'account_id'); const subQuery = ` SELECT f.account_id account_id, f.cnt_filtered cnt_filtered, t.cnt_total cnt_total FROM (${subQueryTotal.getQuery()}) t, (${subQueryFiltered.getQuery()}) f WHERE t.account_id = f.account_id`; if (historicalBalances_none) { mainQuery = mainQuery.andWhere(`account.id IN (SELECT historicalBalances_subq.account_id FROM (${subQuery}) historicalBalances_subq WHERE historicalBalances_subq.cnt_filtered = 0 )`); } if (historicalBalances_some) { mainQuery = mainQuery.andWhere(`account.id IN (SELECT historicalBalances_subq.account_id FROM (${subQuery}) historicalBalances_subq WHERE historicalBalances_subq.cnt_filtered > 0 )`); } if (historicalBalances_every) { mainQuery = mainQuery.andWhere(`account.id IN (SELECT historicalBalances_subq.account_id FROM (${subQuery}) historicalBalances_subq WHERE historicalBalances_subq.cnt_filtered > 0 AND historicalBalances_subq.cnt_filtered = historicalBalances_subq.cnt_total )`); } } mainQuery = mainQuery.setParameters(parameters); return mainQuery.take(limit || 50).skip(offset || 0); } }
def sent_ent_counter(tokens, tags, pid): text = " ".join(tokens) sents = list(nlp(text).sents) sents = [str(s) for s in sents] sent_list = [] s_count = 0 tag_idx = 0 for s in sents: s_tokens = s.split(' ') s_tags = tags[tag_idx: (tag_idx+len(s_tokens))] count = dict(Counter(s_tags)) keys = count.keys() freq_int = count['B-Intervention'] if 'B-Intervention' in keys else 0 freq_com = count['B-Comparator'] if 'B-Comparator' in keys else 0 freq_out = count['B-Outcome'] if 'B-Outcome' in keys else 0 freq_ind = count['B-Induction'] if 'B-Induction' in keys else 0 freq_spe = count['B-Species'] if 'B-Species' in keys else 0 freq_str = count['B-Strain'] if 'B-Strain' in keys else 0 freq_ent = freq_int + freq_com + freq_out + freq_ind + freq_spe + freq_str freq_ent_tokens = len(s_tags) - count['O'] sent_list.append({'pid': pid, 'sid': pid + '_' + str(s_count), 'sent': s_tokens, 'sent_tags': s_tags, 'freq_ent': freq_ent, 'freq_ent_tokens': freq_ent_tokens, 'freq_int': freq_int, 'freq_com': freq_com, 'freq_out': freq_out, 'freq_ind': freq_ind, 'freq_spe': freq_spe, 'freq_str': freq_str}) s_count += 1 tag_idx += len(s_tokens) return sent_list
<reponame>P-man2976/Musicdex import { useInterval, useBoolean, HStack, Box, AspectRatio, Skeleton, } from "@chakra-ui/react"; import styled from "@emotion/styled"; import { useRef, useState, useEffect, useMemo } from "react"; import { useVisibleElements, useScroll, SnapList, SnapItem, } from "react-snaplist-carousel"; import { useStoreState } from "../../store"; import { VideoPlaylistCard } from "./VideoPlaylistCard"; export function VideoPlaylistCarousel({ videoPlaylists, }: { videoPlaylists?: { playlist: PlaylistFull; video: any }[]; }) { const snapList = useRef(null); const visible = useVisibleElements( { debounce: 10, ref: snapList }, ([element]) => element ); const goToSnapItem = useScroll({ ref: snapList }); const [currentItemAuto, setCurrentItemAuto] = useState(0); const currentlyPlayingPlaylistId = useStoreState( (store) => store.playback.currentPlaylist?.id ); const playingFromIdx = useMemo(() => { return ( videoPlaylists?.findIndex( (x) => x?.playlist?.id === currentlyPlayingPlaylistId ) || -1 ); }, [currentlyPlayingPlaylistId, videoPlaylists]); useInterval(() => { // Dont change if hovering on an item, or playing from an item if ( !hovering && (playingFromIdx < 0 || playingFromIdx !== currentItemAuto) ) { goToSnapItem((currentItemAuto + 1) % (videoPlaylists?.length || 1)); setCurrentItemAuto(currentItemAuto + (1 % (videoPlaylists?.length || 1))); } }, 12000); useEffect(() => { setCurrentItemAuto(visible); }, [visible]); const [hovering, { on, off }] = useBoolean(false); // placeholder for CLS if (!videoPlaylists) return ( <AspectRatio ratio={34 / 9} maxH="auto" overflow="hidden" boxSizing="border-box" mb="45px" rounded="lg" > <Skeleton /> </AspectRatio> ); return ( <HStack spacing={0} onMouseEnter={on} onMouseLeave={off}> <CarouselNav> {videoPlaylists && videoPlaylists.map((x, idx) => ( <Box key={"kbxn" + x?.video.id} className={ currentItemAuto === idx ? "cnav-button cnav-active" : "cnav-button" } onClick={() => { goToSnapItem(idx); setCurrentItemAuto(idx); }} cursor="pointer" _hover={{ backgroundColor: "#999" }} ></Box> ))} </CarouselNav> <SnapList ref={snapList} direction="horizontal"> {videoPlaylists && videoPlaylists.map((x: any) => ( <SnapItem key={"kxs" + x?.video.id} snapAlign="center" height="100%" width="100%" margin={{ right: "1.5rem" }} > <VideoPlaylistCard video={x?.video} playlist={x?.playlist} /> </SnapItem> ))} </SnapList> </HStack> ); } const CarouselNav = styled.aside` position: relative; margin-left: -24px; top: 0px; bottom: 0px; width: 20px; margin-right: 4px; display: flex; flex-direction: column; text-align: center; z-index: 4; .cnav { display: block; } .cnav-button { display: block; width: 1.5rem; height: 1.5rem; background-color: #333; background-clip: content-box; border: 0.25rem solid transparent; border-radius: 0.75rem; font-size: 0; transition: all 0.4s; } .cnav-button.cnav-active { background-color: var(--chakra-colors-n2-400); height: 2rem; } `;
mod uri; extern crate httparse; use httparse::{Error, Request, Response, Status, EMPTY_HEADER, parse_chunk_size, ParserConfig, InvalidChunkSize}; use core::slice; pub fn tests_httparse() { print!("Testing iter::tests::test_next_8_extra()..."); iter::tests::test_next_8_extra(); print!("Success.\n"); print!("Testing iter::tests::test_next_8_too_short()..."); iter::tests::test_next_8_too_short(); print!("Success.\n"); print!("Testing iter::tests::test_next_8_just_right()..."); iter::tests::test_next_8_just_right(); print!("Success.\n"); print!("Testing tests::test_allow_response_with_whitespace_between_header_name_and_colon()..."); tests::test_allow_response_with_whitespace_between_header_name_and_colon(); print!("Success.\n"); print!("Testing simd::sse42::sse_code_matches_uri_chars_table()..."); //simd::sse42::sse_code_matches_uri_chars_table(); print!("Not tested.\n"); print!("Testing simd::avx2::avx2_code_matches_uri_chars_table()..."); //simd::avx2::avx2_code_matches_uri_chars_table(); print!("Not tested.\n"); print!("Testing tests::test_chunk_size()..."); tests::test_chunk_size(); print!("Success.\n"); print!("Testing tests::test_forbid_request_with_whitespace_between_header_name_and_colon()..."); tests::test_forbid_request_with_whitespace_between_header_name_and_colon(); print!("Success.\n"); print!("Testing tests::test_request_empty_lines_prefix()..."); tests::test_request_empty_lines_prefix(); print!("Success.\n"); print!("Testing tests::test_request_empty_lines_prefix_lf_only()..."); tests::test_request_empty_lines_prefix_lf_only(); print!("Success.\n"); print!("Testing tests::test_request_header_value_htab_long()..."); tests::test_request_header_value_htab_long(); print!("Success.\n"); print!("Testing tests::test_request_header_value_htab_med()..."); tests::test_request_header_value_htab_med(); print!("Success.\n"); print!("Testing tests::test_request_header_value_htab_short()..."); tests::test_request_header_value_htab_short(); print!("Success.\n"); print!("Testing tests::test_request_headers()..."); tests::test_request_headers(); print!("Success.\n"); print!("Testing tests::test_request_headers_max()..."); tests::test_request_headers_max(); print!("Success.\n"); print!("Testing tests::test_request_multibyte()..."); tests::test_request_multibyte(); print!("Success.\n"); print!("Testing tests::test_request_headers_optional_whitespace()..."); tests::test_request_headers_optional_whitespace(); print!("Success.\n"); print!("Testing tests::test_request_partial_version()..."); tests::test_request_partial_version(); print!("Success.\n"); print!("Testing tests::test_request_partial()..."); tests::test_request_partial(); print!("Success.\n"); print!("Testing tests::test_request_newlines()..."); tests::test_request_newlines(); print!("Success.\n"); print!("Testing tests::test_forbid_response_with_whitespace_between_header_name_and_colon()..."); tests::test_forbid_response_with_whitespace_between_header_name_and_colon(); print!("Success.\n"); print!("Testing tests::test_request_path_backslash()..."); tests::test_request_path_backslash(); print!("Success.\n"); print!("Testing tests::test_request_simple()..."); tests::test_request_simple(); print!("Success.\n"); print!("Testing tests::test_request_simple_with_whatwg_query_params()..."); tests::test_request_simple_with_whatwg_query_params(); print!("Success.\n"); print!("Testing tests::test_request_with_invalid_token_delimiter()..."); tests::test_request_with_invalid_token_delimiter(); print!("Success.\n"); print!("Testing tests::test_request_simple_with_query_params()..."); tests::test_request_simple_with_query_params(); print!("Success.\n"); print!("Testing tests::test_response_code_missing_space()..."); tests::test_response_code_missing_space(); print!("Success.\n"); print!("Testing tests::test_response_empty_lines_prefix_lf_only()..."); tests::test_response_empty_lines_prefix_lf_only(); print!("Success.\n"); print!("Testing tests::test_response_newlines()..."); tests::test_response_newlines(); print!("Success.\n"); print!("Testing tests::test_response_no_cr()..."); tests::test_response_no_cr(); print!("Success.\n"); print!("Testing tests::test_response_reason_missing()..."); tests::test_response_reason_missing(); print!("Success.\n"); print!("Testing tests::test_response_reason_missing_no_space()..."); tests::test_response_reason_missing_no_space(); print!("Success.\n"); print!("Testing tests::test_response_reason_missing_no_space_with_headers()..."); tests::test_response_reason_missing_no_space_with_headers(); print!("Success.\n"); print!("Testing tests::test_response_reason_with_nul_byte()..."); tests::test_response_reason_with_nul_byte(); print!("Success.\n"); print!("Testing tests::test_response_reason_with_obsolete_text_byte()..."); tests::test_response_reason_with_obsolete_text_byte(); print!("Success.\n"); print!("Testing tests::test_response_simple()..."); tests::test_response_simple(); print!("Success.\n"); print!("Testing tests::test_response_reason_with_space_and_tab()..."); tests::test_response_reason_with_space_and_tab(); print!("Success.\n"); print!("Testing tests::test_response_version_missing_space()..."); tests::test_response_version_missing_space(); print!("Success.\n"); print!("Testing tests::test_shrink()..."); tests::test_shrink(); print!("Success.\n"); print!("Testing tests::test_std_error()..."); tests::test_std_error(); print!("Success.\n"); print!("Testing tests::test_request_with_invalid_but_short_version()..."); tests::test_request_with_invalid_but_short_version(); print!("Success.\n"); } pub fn urltests() { print!("Testing urltest_001()..."); uri::urltest_001(); print!("Success.\n"); print!("Testing urltest_002()..."); uri::urltest_002(); print!("Success.\n"); print!("Testing urltest_003()..."); uri::urltest_003(); print!("Success.\n"); print!("Testing urltest_004()..."); uri::urltest_004(); print!("Success.\n"); print!("Testing urltest_005()..."); uri::urltest_005(); print!("Success.\n"); print!("Testing urltest_006()..."); uri::urltest_006(); print!("Success.\n"); print!("Testing urltest_007()..."); uri::urltest_007(); print!("Success.\n"); print!("Testing urltest_008()..."); uri::urltest_008(); print!("Success.\n"); print!("Testing urltest_009()..."); uri::urltest_009(); print!("Success.\n"); print!("Testing urltest_010..."); uri::urltest_010(); print!("Success.\n"); print!("Testing urltest_011..."); uri::urltest_011(); print!("Success.\n"); print!("Testing urltest_012..."); uri::urltest_012(); print!("Success.\n"); print!("Testing urltest_013..."); uri::urltest_013(); print!("Success.\n"); print!("Testing urltest_014..."); uri::urltest_014(); print!("Success.\n"); print!("Testing urltest_015..."); uri::urltest_015(); print!("Success.\n"); print!("Testing urltest_016..."); uri::urltest_016(); print!("Success.\n"); print!("Testing urltest_017..."); uri::urltest_017(); print!("Success.\n"); print!("Testing urltest_018..."); uri::urltest_018(); print!("Success.\n"); print!("Testing urltest_019..."); uri::urltest_019(); print!("Success.\n"); print!("Testing urltest_020..."); uri::urltest_020(); print!("Success.\n"); print!("Testing urltest_021..."); uri::urltest_021(); print!("Success.\n"); print!("Testing urltest_022..."); uri::urltest_022(); print!("Success.\n"); print!("Testing urltest_023..."); uri::urltest_023(); print!("Success.\n"); print!("Testing urltest_024..."); uri::urltest_024(); print!("Success.\n"); print!("Testing urltest_025..."); uri::urltest_025(); print!("Success.\n"); print!("Testing urltest_026..."); uri::urltest_026(); print!("Success.\n"); print!("Testing urltest_027..."); uri::urltest_027(); print!("Success.\n"); print!("Testing urltest_028..."); uri::urltest_028(); print!("Success.\n"); print!("Testing urltest_029..."); uri::urltest_029(); print!("Success.\n"); print!("Testing urltest_030..."); uri::urltest_030(); print!("Success.\n"); print!("Testing urltest_031..."); uri::urltest_031(); print!("Success.\n"); print!("Testing urltest_032..."); uri::urltest_032(); print!("Success.\n"); print!("Testing urltest_033..."); uri::urltest_033(); print!("Success.\n"); print!("Testing urltest_034..."); uri::urltest_034(); print!("Success.\n"); print!("Testing urltest_035..."); uri::urltest_035(); print!("Success.\n"); print!("Testing urltest_036..."); uri::urltest_036(); print!("Success.\n"); print!("Testing urltest_037..."); uri::urltest_037(); print!("Success.\n"); print!("Testing urltest_038..."); uri::urltest_038(); print!("Success.\n"); print!("Testing urltest_039..."); uri::urltest_039(); print!("Success.\n"); print!("Testing urltest_040..."); uri::urltest_040(); print!("Success.\n"); print!("Testing urltest_041..."); uri::urltest_041(); print!("Success.\n"); print!("Testing urltest_042..."); uri::urltest_042(); print!("Success.\n"); print!("Testing urltest_043..."); uri::urltest_043(); print!("Success.\n"); print!("Testing urltest_044..."); uri::urltest_044(); print!("Success.\n"); print!("Testing urltest_045..."); uri::urltest_045(); print!("Success.\n"); print!("Testing urltest_046..."); uri::urltest_046(); print!("Success.\n"); print!("Testing urltest_047..."); uri::urltest_047(); print!("Success.\n"); print!("Testing urltest_048..."); uri::urltest_048(); print!("Success.\n"); print!("Testing urltest_049..."); uri::urltest_049(); print!("Success.\n"); print!("Testing urltest_050..."); uri::urltest_050(); print!("Success.\n"); print!("Testing urltest_051..."); uri::urltest_051(); print!("Success.\n"); print!("Testing urltest_052..."); uri::urltest_052(); print!("Success.\n"); print!("Testing urltest_053..."); uri::urltest_053(); print!("Success.\n"); print!("Testing urltest_054..."); uri::urltest_054(); print!("Success.\n"); print!("Testing urltest_055..."); uri::urltest_055(); print!("Success.\n"); print!("Testing urltest_056..."); uri::urltest_056(); print!("Success.\n"); print!("Testing urltest_057..."); uri::urltest_057(); print!("Success.\n"); print!("Testing urltest_058..."); uri::urltest_058(); print!("Success.\n"); print!("Testing urltest_059..."); uri::urltest_059(); print!("Success.\n"); print!("Testing urltest_060..."); uri::urltest_060(); print!("Success.\n"); print!("Testing urltest_061..."); uri::urltest_061(); print!("Success.\n"); print!("Testing urltest_062..."); uri::urltest_062(); print!("Success.\n"); print!("Testing urltest_063..."); uri::urltest_063(); print!("Success.\n"); print!("Testing urltest_064..."); uri::urltest_064(); print!("Success.\n"); print!("Testing urltest_065..."); uri::urltest_065(); print!("Success.\n"); print!("Testing urltest_066..."); uri::urltest_066(); print!("Success.\n"); print!("Testing urltest_067..."); uri::urltest_067(); print!("Success.\n"); print!("Testing urltest_068..."); uri::urltest_068(); print!("Success.\n"); print!("Testing urltest_069..."); uri::urltest_069(); print!("Success.\n"); print!("Testing urltest_070..."); uri::urltest_070(); print!("Success.\n"); print!("Testing urltest_071..."); uri::urltest_071(); print!("Success.\n"); print!("Testing urltest_072..."); uri::urltest_072(); print!("Success.\n"); print!("Testing urltest_073..."); uri::urltest_073(); print!("Success.\n"); print!("Testing urltest_074..."); uri::urltest_074(); print!("Success.\n"); print!("Testing urltest_075..."); uri::urltest_075(); print!("Success.\n"); print!("Testing urltest_076..."); uri::urltest_076(); print!("Success.\n"); print!("Testing urltest_077..."); uri::urltest_077(); print!("Success.\n"); print!("Testing urltest_078..."); uri::urltest_078(); print!("Success.\n"); print!("Testing urltest_079..."); uri::urltest_079(); print!("Success.\n"); print!("Testing urltest_080..."); uri::urltest_080(); print!("Success.\n"); print!("Testing urltest_081..."); uri::urltest_081(); print!("Success.\n"); print!("Testing urltest_082..."); uri::urltest_082(); print!("Success.\n"); print!("Testing urltest_083..."); uri::urltest_083(); print!("Success.\n"); print!("Testing urltest_084..."); uri::urltest_084(); print!("Success.\n"); print!("Testing urltest_085..."); uri::urltest_085(); print!("Success.\n"); print!("Testing urltest_086..."); uri::urltest_086(); print!("Success.\n"); print!("Testing urltest_087..."); uri::urltest_087(); print!("Success.\n"); print!("Testing urltest_088..."); uri::urltest_088(); print!("Success.\n"); print!("Testing urltest_089..."); uri::urltest_089(); print!("Success.\n"); print!("Testing urltest_090..."); uri::urltest_090(); print!("Success.\n"); print!("Testing urltest_091..."); uri::urltest_091(); print!("Success.\n"); print!("Testing urltest_092..."); uri::urltest_092(); print!("Success.\n"); print!("Testing urltest_093..."); uri::urltest_093(); print!("Success.\n"); print!("Testing urltest_094..."); uri::urltest_094(); print!("Success.\n"); print!("Testing urltest_095..."); uri::urltest_095(); print!("Success.\n"); print!("Testing urltest_096..."); uri::urltest_096(); print!("Success.\n"); print!("Testing urltest_097..."); uri::urltest_097(); print!("Success.\n"); print!("Testing urltest_098..."); uri::urltest_098(); print!("Success.\n"); print!("Testing urltest_099..."); uri::urltest_099(); print!("Success.\n"); print!("Testing urltest_100()..."); uri::urltest_100(); print!("Success.\n"); print!("Testing urltest_101()..."); uri::urltest_101(); print!("Success.\n"); print!("Testing urltest_102()..."); uri::urltest_102(); print!("Success.\n"); print!("Testing urltest_103()..."); uri::urltest_103(); print!("Success.\n"); print!("Testing urltest_104()..."); uri::urltest_104(); print!("Success.\n"); print!("Testing urltest_105()..."); uri::urltest_105(); print!("Success.\n"); print!("Testing urltest_106()..."); uri::urltest_106(); print!("Success.\n"); print!("Testing urltest_107()..."); uri::urltest_107(); print!("Success.\n"); print!("Testing urltest_108()..."); uri::urltest_108(); print!("Success.\n"); print!("Testing urltest_109()..."); uri::urltest_109(); print!("Success.\n"); print!("Testing urltest_110()..."); uri::urltest_110(); print!("Success.\n"); print!("Testing urltest_111()..."); uri::urltest_111(); print!("Success.\n"); print!("Testing urltest_112()..."); uri::urltest_112(); print!("Success.\n"); print!("Testing urltest_113()..."); uri::urltest_113(); print!("Success.\n"); print!("Testing urltest_114()..."); uri::urltest_114(); print!("Success.\n"); print!("Testing urltest_115()..."); uri::urltest_115(); print!("Success.\n"); print!("Testing urltest_116()..."); uri::urltest_116(); print!("Success.\n"); print!("Testing urltest_117()..."); uri::urltest_117(); print!("Success.\n"); print!("Testing urltest_118()..."); uri::urltest_118(); print!("Success.\n"); print!("Testing urltest_119()..."); uri::urltest_119(); print!("Success.\n"); print!("Testing urltest_120()..."); uri::urltest_120(); print!("Success.\n"); print!("Testing urltest_121()..."); uri::urltest_121(); print!("Success.\n"); print!("Testing urltest_122()..."); uri::urltest_122(); print!("Success.\n"); print!("Testing urltest_123()..."); uri::urltest_123(); print!("Success.\n"); print!("Testing urltest_124()..."); uri::urltest_124(); print!("Success.\n"); print!("Testing urltest_125()..."); uri::urltest_125(); print!("Success.\n"); print!("Testing urltest_126()..."); uri::urltest_126(); print!("Success.\n"); print!("Testing urltest_127()..."); uri::urltest_127(); print!("Success.\n"); print!("Testing urltest_128()..."); uri::urltest_128(); print!("Success.\n"); print!("Testing urltest_129()..."); uri::urltest_129(); print!("Success.\n"); print!("Testing urltest_130()..."); uri::urltest_130(); print!("Success.\n"); print!("Testing urltest_131()..."); uri::urltest_131(); print!("Success.\n"); print!("Testing urltest_132()..."); uri::urltest_132(); print!("Success.\n"); print!("Testing urltest_133()..."); uri::urltest_133(); print!("Success.\n"); print!("Testing urltest_134()..."); uri::urltest_134(); print!("Success.\n"); print!("Testing urltest_135()..."); uri::urltest_135(); print!("Success.\n"); print!("Testing urltest_136()..."); uri::urltest_136(); print!("Success.\n"); print!("Testing urltest_137()..."); uri::urltest_137(); print!("Success.\n"); print!("Testing urltest_138()..."); uri::urltest_138(); print!("Success.\n"); print!("Testing urltest_139()..."); uri::urltest_139(); print!("Success.\n"); print!("Testing urltest_140()..."); uri::urltest_140(); print!("Success.\n"); print!("Testing urltest_141()..."); uri::urltest_141(); print!("Success.\n"); print!("Testing urltest_142()..."); uri::urltest_142(); print!("Success.\n"); print!("Testing urltest_143()..."); uri::urltest_143(); print!("Success.\n"); print!("Testing urltest_144()..."); uri::urltest_144(); print!("Success.\n"); print!("Testing urltest_145()..."); uri::urltest_145(); print!("Success.\n"); print!("Testing urltest_146()..."); uri::urltest_146(); print!("Success.\n"); print!("Testing urltest_147()..."); uri::urltest_147(); print!("Success.\n"); print!("Testing urltest_148()..."); uri::urltest_148(); print!("Success.\n"); print!("Testing urltest_149()..."); uri::urltest_149(); print!("Success.\n"); print!("Testing urltest_150()..."); uri::urltest_150(); print!("Success.\n"); print!("Testing urltest_151()..."); uri::urltest_151(); print!("Success.\n"); print!("Testing urltest_152()..."); uri::urltest_152(); print!("Success.\n"); print!("Testing urltest_153()..."); uri::urltest_153(); print!("Success.\n"); print!("Testing urltest_154()..."); uri::urltest_154(); print!("Success.\n"); print!("Testing urltest_155()..."); uri::urltest_155(); print!("Success.\n"); print!("Testing urltest_156()..."); uri::urltest_156(); print!("Success.\n"); print!("Testing urltest_157()..."); uri::urltest_157(); print!("Success.\n"); print!("Testing urltest_158()..."); uri::urltest_158(); print!("Success.\n"); print!("Testing urltest_159()..."); uri::urltest_159(); print!("Success.\n"); print!("Testing urltest_160()..."); uri::urltest_160(); print!("Success.\n"); print!("Testing urltest_161()..."); uri::urltest_161(); print!("Success.\n"); print!("Testing urltest_162()..."); uri::urltest_162(); print!("Success.\n"); print!("Testing urltest_163()..."); uri::urltest_163(); print!("Success.\n"); print!("Testing urltest_164()..."); uri::urltest_164(); print!("Success.\n"); print!("Testing urltest_165()..."); uri::urltest_165(); print!("Success.\n"); print!("Testing urltest_166()..."); uri::urltest_166(); print!("Success.\n"); print!("Testing urltest_167()..."); uri::urltest_167(); print!("Success.\n"); print!("Testing urltest_168()..."); uri::urltest_168(); print!("Success.\n"); print!("Testing urltest_169()..."); uri::urltest_169(); print!("Success.\n"); print!("Testing urltest_170()..."); uri::urltest_170(); print!("Success.\n"); print!("Testing urltest_171()..."); uri::urltest_171(); print!("Success.\n"); print!("Testing urltest_172()..."); uri::urltest_172(); print!("Success.\n"); print!("Testing urltest_173()..."); uri::urltest_173(); print!("Success.\n"); print!("Testing urltest_174()..."); uri::urltest_174(); print!("Success.\n"); print!("Testing urltest_175()..."); uri::urltest_175(); print!("Success.\n"); print!("Testing urltest_176()..."); uri::urltest_176(); print!("Success.\n"); print!("Testing urltest_177()..."); uri::urltest_177(); print!("Success.\n"); print!("Testing urltest_178()..."); uri::urltest_178(); print!("Success.\n"); print!("Testing urltest_179()..."); uri::urltest_179(); print!("Success.\n"); print!("Testing urltest_180()..."); uri::urltest_180(); print!("Success.\n"); print!("Testing urltest_181()..."); uri::urltest_181(); print!("Success.\n"); print!("Testing urltest_182()..."); uri::urltest_182(); print!("Success.\n"); print!("Testing urltest_183()..."); uri::urltest_183(); print!("Success.\n"); print!("Testing urltest_184()..."); uri::urltest_184(); print!("Success.\n"); print!("Testing urltest_185()..."); uri::urltest_185(); print!("Success.\n"); print!("Testing urltest_186()..."); uri::urltest_186(); print!("Success.\n"); print!("Testing urltest_187()..."); uri::urltest_187(); print!("Success.\n"); print!("Testing urltest_188()..."); uri::urltest_188(); print!("Success.\n"); print!("Testing urltest_189()..."); uri::urltest_189(); print!("Success.\n"); print!("Testing urltest_190()..."); uri::urltest_190(); print!("Success.\n"); print!("Testing urltest_191()..."); uri::urltest_191(); print!("Success.\n"); print!("Testing urltest_192()..."); uri::urltest_192(); print!("Success.\n"); print!("Testing urltest_193()..."); uri::urltest_193(); print!("Success.\n"); print!("Testing urltest_194()..."); uri::urltest_194(); print!("Success.\n"); print!("Testing urltest_195()..."); uri::urltest_195(); print!("Success.\n"); print!("Testing urltest_196()..."); uri::urltest_196(); print!("Success.\n"); print!("Testing urltest_197()..."); uri::urltest_197(); print!("Success.\n"); print!("Testing urltest_198()..."); uri::urltest_198(); print!("Success.\n"); print!("Testing urltest_199()..."); uri::urltest_199(); print!("Success.\n"); print!("Testing urltest_200()..."); uri::urltest_200(); print!("Success.\n"); print!("Testing urltest_201()..."); uri::urltest_201(); print!("Success.\n"); print!("Testing urltest_202()..."); uri::urltest_202(); print!("Success.\n"); print!("Testing urltest_203()..."); uri::urltest_203(); print!("Success.\n"); print!("Testing urltest_204()..."); uri::urltest_204(); print!("Success.\n"); print!("Testing urltest_205()..."); uri::urltest_205(); print!("Success.\n"); print!("Testing urltest_206()..."); uri::urltest_206(); print!("Success.\n"); print!("Testing urltest_207()..."); uri::urltest_207(); print!("Success.\n"); print!("Testing urltest_208()..."); uri::urltest_208(); print!("Success.\n"); print!("Testing urltest_209()..."); uri::urltest_209(); print!("Success.\n"); print!("Testing urltest_210()..."); uri::urltest_210(); print!("Success.\n"); print!("Testing urltest_211()..."); uri::urltest_211(); print!("Success.\n"); print!("Testing urltest_212()..."); uri::urltest_212(); print!("Success.\n"); print!("Testing urltest_213()..."); uri::urltest_213(); print!("Success.\n"); print!("Testing urltest_214()..."); uri::urltest_214(); print!("Success.\n"); print!("Testing urltest_215()..."); uri::urltest_215(); print!("Success.\n"); print!("Testing urltest_216()..."); uri::urltest_216(); print!("Success.\n"); print!("Testing urltest_217()..."); uri::urltest_217(); print!("Success.\n"); print!("Testing urltest_218()..."); uri::urltest_218(); print!("Success.\n"); print!("Testing urltest_219()..."); uri::urltest_219(); print!("Success.\n"); print!("Testing urltest_220()..."); uri::urltest_220(); print!("Success.\n"); print!("Testing urltest_221()..."); uri::urltest_221(); print!("Success.\n"); print!("Testing urltest_222()..."); uri::urltest_222(); print!("Success.\n"); print!("Testing urltest_223()..."); uri::urltest_223(); print!("Success.\n"); print!("Testing urltest_224()..."); uri::urltest_224(); print!("Success.\n"); print!("Testing urltest_225()..."); uri::urltest_225(); print!("Success.\n"); print!("Testing urltest_226()..."); uri::urltest_226(); print!("Success.\n"); print!("Testing urltest_227()..."); uri::urltest_227(); print!("Success.\n"); print!("Testing urltest_228()..."); uri::urltest_228(); print!("Success.\n"); print!("Testing urltest_229()..."); uri::urltest_229(); print!("Success.\n"); print!("Testing urltest_230()..."); uri::urltest_230(); print!("Success.\n"); print!("Testing urltest_231()..."); uri::urltest_231(); print!("Success.\n"); print!("Testing urltest_232()..."); uri::urltest_232(); print!("Success.\n"); print!("Testing urltest_233()..."); uri::urltest_233(); print!("Success.\n"); print!("Testing urltest_234()..."); uri::urltest_234(); print!("Success.\n"); print!("Testing urltest_235()..."); uri::urltest_235(); print!("Success.\n"); print!("Testing urltest_236()..."); uri::urltest_236(); print!("Success.\n"); print!("Testing urltest_237()..."); uri::urltest_237(); print!("Success.\n"); print!("Testing urltest_238()..."); uri::urltest_238(); print!("Success.\n"); print!("Testing urltest_239()..."); uri::urltest_239(); print!("Success.\n"); print!("Testing urltest_240()..."); uri::urltest_240(); print!("Success.\n"); print!("Testing urltest_241()..."); uri::urltest_241(); print!("Success.\n"); print!("Testing urltest_242()..."); uri::urltest_242(); print!("Success.\n"); print!("Testing urltest_243()..."); uri::urltest_243(); print!("Success.\n"); print!("Testing urltest_244()..."); uri::urltest_244(); print!("Success.\n"); print!("Testing urltest_245()..."); uri::urltest_245(); print!("Success.\n"); print!("Testing urltest_246()..."); uri::urltest_246(); print!("Success.\n"); print!("Testing urltest_247()..."); uri::urltest_247(); print!("Success.\n"); print!("Testing urltest_248()..."); uri::urltest_248(); print!("Success.\n"); print!("Testing urltest_249()..."); uri::urltest_249(); print!("Success.\n"); print!("Testing urltest_250()..."); uri::urltest_250(); print!("Success.\n"); print!("Testing urltest_251()..."); uri::urltest_251(); print!("Success.\n"); print!("Testing urltest_252()..."); uri::urltest_252(); print!("Success.\n"); print!("Testing urltest_253()..."); uri::urltest_253(); print!("Success.\n"); print!("Testing urltest_254()..."); uri::urltest_254(); print!("Success.\n"); print!("Testing urltest_255()..."); uri::urltest_255(); print!("Success.\n"); print!("Testing urltest_256()..."); uri::urltest_256(); print!("Success.\n"); print!("Testing urltest_257()..."); uri::urltest_257(); print!("Success.\n"); print!("Testing urltest_258()..."); uri::urltest_258(); print!("Success.\n"); print!("Testing urltest_259()..."); uri::urltest_259(); print!("Success.\n"); print!("Testing urltest_260()..."); uri::urltest_260(); print!("Success.\n"); print!("Testing urltest_261()..."); uri::urltest_261(); print!("Success.\n"); print!("Testing urltest_262()..."); uri::urltest_262(); print!("Success.\n"); print!("Testing urltest_nvidia()..."); uri::urltest_nvidia(); print!("Success.\n"); } fn shrink<T>(slice: &mut &mut [T], len: usize) { debug_assert!(slice.len() >= len); let ptr = slice.as_mut_ptr(); *slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; } mod tests { use super::{Error, Request, Response, Status, EMPTY_HEADER, shrink, parse_chunk_size, ParserConfig, InvalidChunkSize}; const NUM_OF_HEADERS: usize = 4; //#[test] pub fn test_shrink() { let mut arr = [EMPTY_HEADER; 16]; { let slice = &mut &mut arr[..]; assert_eq!(slice.len(), 16); shrink(slice, 4); assert_eq!(slice.len(), 4); } assert_eq!(arr.len(), 16); } macro_rules! req { ($name:ident, $buf:expr, |$arg:ident| $body:expr) => ( req! {$name, $buf, Ok(Status::Complete($buf.len())), |$arg| $body } ); ($name:ident, $buf:expr, $len:expr, |$arg:ident| $body:expr) => ( //#[test] pub fn $name() { let mut headers = [EMPTY_HEADER; NUM_OF_HEADERS]; let mut req = Request::new(&mut headers[..]); let status = req.parse($buf.as_ref()); assert_eq!(status, $len); closure(req); fn closure($arg: Request) { $body } } ) } req! { test_request_simple, b"GET / HTTP/1.1\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 0); } } req! { test_request_simple_with_query_params, b"GET /thing?data=a HTTP/1.1\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/thing?data=a"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 0); } } req! { test_request_simple_with_whatwg_query_params, b"GET /thing?data=a^ HTTP/1.1\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/thing?data=a^"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 0); } } req! { test_request_headers, b"GET / HTTP/1.1\r\nHost: foo.com\r\nCookie: \r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 2); assert_eq!(req.headers[0].name, "Host"); assert_eq!(req.headers[0].value, b"foo.com"); assert_eq!(req.headers[1].name, "Cookie"); assert_eq!(req.headers[1].value, b""); } } req! { test_request_headers_optional_whitespace, b"GET / HTTP/1.1\r\nHost: \tfoo.com\t \r\nCookie: \t \r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 2); assert_eq!(req.headers[0].name, "Host"); assert_eq!(req.headers[0].value, b"foo.com"); assert_eq!(req.headers[1].name, "Cookie"); assert_eq!(req.headers[1].value, b""); } } req! { // test the scalar parsing test_request_header_value_htab_short, b"GET / HTTP/1.1\r\nUser-Agent: some\tagent\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 1); assert_eq!(req.headers[0].name, "User-Agent"); assert_eq!(req.headers[0].value, b"some\tagent"); } } req! { // test the sse42 parsing test_request_header_value_htab_med, b"GET / HTTP/1.1\r\nUser-Agent: 1234567890some\tagent\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 1); assert_eq!(req.headers[0].name, "User-Agent"); assert_eq!(req.headers[0].value, b"1234567890some\tagent"); } } req! { // test the avx2 parsing test_request_header_value_htab_long, b"GET / HTTP/1.1\r\nUser-Agent: 1234567890some\t1234567890agent1234567890\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 1); assert_eq!(req.headers[0].name, "User-Agent"); assert_eq!(req.headers[0].value, &b"1234567890some\t1234567890agent1234567890"[..]); } } req! { test_request_headers_max, b"GET / HTTP/1.1\r\nA: A\r\nB: B\r\nC: C\r\nD: D\r\n\r\n", |req| { assert_eq!(req.headers.len(), NUM_OF_HEADERS); } } req! { test_request_multibyte, b"GET / HTTP/1.1\r\nHost: foo.com\r\nUser-Agent: \xe3\x81\xb2\xe3/1.0\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers[0].name, "Host"); assert_eq!(req.headers[0].value, b"foo.com"); assert_eq!(req.headers[1].name, "User-Agent"); assert_eq!(req.headers[1].value, b"\xe3\x81\xb2\xe3/1.0"); } } req! { test_request_partial, b"GET / HTTP/1.1\r\n\r", Ok(Status::Partial), |_req| {} } req! { test_request_partial_version, b"GET / HTTP/1.", Ok(Status::Partial), |_req| {} } req! { test_request_newlines, b"GET / HTTP/1.1\nHost: foo.bar\n\n", |_r| {} } req! { test_request_empty_lines_prefix, b"\r\n\r\nGET / HTTP/1.1\r\n\r\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 0); } } req! { test_request_empty_lines_prefix_lf_only, b"\n\nGET / HTTP/1.1\n\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 0); } } req! { test_request_path_backslash, b"\n\nGET /\\?wayne\\=5 HTTP/1.1\n\n", |req| { assert_eq!(req.method.unwrap(), "GET"); assert_eq!(req.path.unwrap(), "/\\?wayne\\=5"); assert_eq!(req.version.unwrap(), 1); assert_eq!(req.headers.len(), 0); } } req! { test_request_with_invalid_token_delimiter, b"GET\n/ HTTP/1.1\r\nHost: foo.bar\r\n\r\n", Err(Error::Token), |_r| {} } req! { test_request_with_invalid_but_short_version, b"GET / HTTP/1!", Err(Error::Version), |_r| {} } macro_rules! res { ($name:ident, $buf:expr, |$arg:ident| $body:expr) => ( res! {$name, $buf, Ok(Status::Complete($buf.len())), |$arg| $body } ); ($name:ident, $buf:expr, $len:expr, |$arg:ident| $body:expr) => ( //#[test] pub fn $name() { let mut headers = [EMPTY_HEADER; NUM_OF_HEADERS]; let mut res = Response::new(&mut headers[..]); let status = res.parse($buf.as_ref()); assert_eq!(status, $len); closure(res); fn closure($arg: Response) { $body } } ) } res! { test_response_simple, b"HTTP/1.1 200 OK\r\n\r\n", |res| { assert_eq!(res.version.unwrap(), 1); assert_eq!(res.code.unwrap(), 200); assert_eq!(res.reason.unwrap(), "OK"); } } res! { test_response_newlines, b"HTTP/1.0 403 Forbidden\nServer: foo.bar\n\n", |_r| {} } res! { test_response_reason_missing, b"HTTP/1.1 200 \r\n\r\n", |res| { assert_eq!(res.version.unwrap(), 1); assert_eq!(res.code.unwrap(), 200); assert_eq!(res.reason.unwrap(), ""); } } res! { test_response_reason_missing_no_space, b"HTTP/1.1 200\r\n\r\n", |res| { assert_eq!(res.version.unwrap(), 1); assert_eq!(res.code.unwrap(), 200); assert_eq!(res.reason.unwrap(), ""); } } res! { test_response_reason_missing_no_space_with_headers, b"HTTP/1.1 200\r\nFoo: bar\r\n\r\n", |res| { assert_eq!(res.version.unwrap(), 1); assert_eq!(res.code.unwrap(), 200); assert_eq!(res.reason.unwrap(), ""); assert_eq!(res.headers.len(), 1); assert_eq!(res.headers[0].name, "Foo"); assert_eq!(res.headers[0].value, b"bar"); } } res! { test_response_reason_with_space_and_tab, b"HTTP/1.1 101 Switching Protocols\t\r\n\r\n", |res| { assert_eq!(res.version.unwrap(), 1); assert_eq!(res.code.unwrap(), 101); assert_eq!(res.reason.unwrap(), "Switching Protocols\t"); } } static RESPONSE_REASON_WITH_OBS_TEXT_BYTE: &'static [u8] = b"HTTP/1.1 200 X\xFFZ\r\n\r\n"; res! { test_response_reason_with_obsolete_text_byte, RESPONSE_REASON_WITH_OBS_TEXT_BYTE, |res| { assert_eq!(res.version.unwrap(), 1); assert_eq!(res.code.unwrap(), 200); // Empty string fallback in case of obs-text assert_eq!(res.reason.unwrap(), ""); } } res! { test_response_reason_with_nul_byte, b"HTTP/1.1 200 \x00\r\n\r\n", Err(Error::Status), |_res| {} } res! { test_response_version_missing_space, b"HTTP/1.1", Ok(Status::Partial), |_res| {} } res! { test_response_code_missing_space, b"HTTP/1.1 200", Ok(Status::Partial), |_res| {} } res! { test_response_empty_lines_prefix_lf_only, b"\n\nHTTP/1.1 200 OK\n\n", |_res| {} } res! { test_response_no_cr, b"HTTP/1.0 200\nContent-type: text/html\n\n", |res| { assert_eq!(res.version.unwrap(), 0); assert_eq!(res.code.unwrap(), 200); assert_eq!(res.reason.unwrap(), ""); assert_eq!(res.headers.len(), 1); assert_eq!(res.headers[0].name, "Content-type"); assert_eq!(res.headers[0].value, b"text/html"); } } static RESPONSE_WITH_WHITESPACE_BETWEEN_HEADER_NAME_AND_COLON: &'static [u8] = b"HTTP/1.1 200 OK\r\nAccess-Control-Allow-Credentials : true\r\n\r\n"; //#[test] pub fn test_forbid_response_with_whitespace_between_header_name_and_colon() { let mut headers = [EMPTY_HEADER; 1]; let mut response = Response::new(&mut headers[..]); let result = response.parse(RESPONSE_WITH_WHITESPACE_BETWEEN_HEADER_NAME_AND_COLON); assert_eq!(result, Err(Error::HeaderName)); } //#[test] pub fn test_allow_response_with_whitespace_between_header_name_and_colon() { let mut headers = [EMPTY_HEADER; 1]; let mut response = Response::new(&mut headers[..]); let result = ParserConfig::default() .allow_spaces_after_header_name_in_responses(true) .parse_response(&mut response, RESPONSE_WITH_WHITESPACE_BETWEEN_HEADER_NAME_AND_COLON); assert_eq!(result, Ok(Status::Complete(60))); assert_eq!(response.version.unwrap(), 1); assert_eq!(response.code.unwrap(), 200); assert_eq!(response.reason.unwrap(), "OK"); assert_eq!(response.headers.len(), 1); assert_eq!(response.headers[0].name, "Access-Control-Allow-Credentials"); assert_eq!(response.headers[0].value, &b"true"[..]); } static REQUEST_WITH_WHITESPACE_BETWEEN_HEADER_NAME_AND_COLON: &'static [u8] = b"GET / HTTP/1.1\r\nHost : localhost\r\n\r\n"; //#[test] pub fn test_forbid_request_with_whitespace_between_header_name_and_colon() { let mut headers = [EMPTY_HEADER; 1]; let mut request = Request::new(&mut headers[..]); let result = request.parse(REQUEST_WITH_WHITESPACE_BETWEEN_HEADER_NAME_AND_COLON); assert_eq!(result, Err(Error::HeaderName)); } //#[test] pub fn test_chunk_size() { assert_eq!(parse_chunk_size(b"0\r\n"), Ok(Status::Complete((3, 0)))); assert_eq!(parse_chunk_size(b"12\r\nchunk"), Ok(Status::Complete((4, 18)))); assert_eq!(parse_chunk_size(b"3086d\r\n"), Ok(Status::Complete((7, 198765)))); assert_eq!(parse_chunk_size(b"3735AB1;foo bar*\r\n"), Ok(Status::Complete((18, 57891505)))); assert_eq!(parse_chunk_size(b"3735ab1 ; baz \r\n"), Ok(Status::Complete((16, 57891505)))); assert_eq!(parse_chunk_size(b"77a65\r"), Ok(Status::Partial)); assert_eq!(parse_chunk_size(b"ab"), Ok(Status::Partial)); assert_eq!(parse_chunk_size(b"567f8a\rfoo"), Err(InvalidChunkSize)); assert_eq!(parse_chunk_size(b"567f8a\rfoo"), Err(InvalidChunkSize)); assert_eq!(parse_chunk_size(b"567xf8a\r\n"), Err(InvalidChunkSize)); assert_eq!(parse_chunk_size(b"ffffffffffffffff\r\n"), Ok(Status::Complete((18, ::core::u64::MAX)))); assert_eq!(parse_chunk_size(b"1ffffffffffffffff\r\n"), Err(InvalidChunkSize)); assert_eq!(parse_chunk_size(b"Affffffffffffffff\r\n"), Err(InvalidChunkSize)); assert_eq!(parse_chunk_size(b"fffffffffffffffff\r\n"), Err(InvalidChunkSize)); } #[cfg(feature = "std")] //#[test] pub fn test_std_error() { use std::error::Error as StdError; let err = Error::HeaderName; assert_eq!(err.to_string(), err.description()); } } mod iter { //The module is private, so we just copy the entire source code. use core::slice; pub struct Bytes<'a> { slice: &'a [u8], pos: usize } impl<'a> Bytes<'a> { #[inline] pub fn new(slice: &'a [u8]) -> Bytes<'a> { Bytes { slice: slice, pos: 0 } } #[allow(unused)] #[inline] pub unsafe fn advance(&mut self, n: usize) { debug_assert!(self.pos + n <= self.slice.len(), "overflow"); self.pos += n; } #[inline] pub fn next_8<'b>(&'b mut self) -> Option<Bytes8<'b, 'a>> { if self.slice.len() >= self.pos + 8 { Some(Bytes8::new(self)) } else { None } } } impl<'a> AsRef<[u8]> for Bytes<'a> { #[inline] fn as_ref(&self) -> &[u8] { &self.slice[self.pos..] } } impl<'a> Iterator for Bytes<'a> { type Item = u8; #[inline] fn next(&mut self) -> Option<u8> { if self.slice.len() > self.pos { let b = unsafe { *self.slice.get_unchecked(self.pos) }; self.pos += 1; Some(b) } else { None } } } pub struct Bytes8<'a, 'b: 'a> { bytes: &'a mut Bytes<'b>, #[cfg(debug_assertions)] pos: usize } macro_rules! bytes8_methods { ($f:ident, $pos:expr) => { #[inline] pub fn $f(&mut self) -> u8 { self.assert_pos($pos); let b = unsafe { *self.bytes.slice.get_unchecked(self.bytes.pos) }; self.bytes.pos += 1; b } }; () => { bytes8_methods!(_0, 0); bytes8_methods!(_1, 1); bytes8_methods!(_2, 2); bytes8_methods!(_3, 3); bytes8_methods!(_4, 4); bytes8_methods!(_5, 5); bytes8_methods!(_6, 6); bytes8_methods!(_7, 7); } } impl<'a, 'b: 'a> Bytes8<'a, 'b> { bytes8_methods! {} #[cfg(not(debug_assertions))] #[inline] fn new(bytes: &'a mut Bytes<'b>) -> Bytes8<'a, 'b> { Bytes8 { bytes: bytes, } } #[cfg(debug_assertions)] #[inline] fn new(bytes: &'a mut Bytes<'b>) -> Bytes8<'a, 'b> { Bytes8 { bytes: bytes, pos: 0, } } #[cfg(not(debug_assertions))] #[inline] fn assert_pos(&mut self, _pos: usize) { } #[cfg(debug_assertions)] #[inline] fn assert_pos(&mut self, pos: usize) { assert!(self.pos == pos); self.pos += 1; } } //#[cfg(test)] pub mod tests { use super::Bytes; //#[test] pub fn test_next_8_too_short() { // Start with 10 bytes. let slice = [0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8]; let mut bytes = Bytes::new(&slice); // Skip 3 of them. unsafe { bytes.advance(3); } // There should be 7 left, not enough to call next_8. assert!(bytes.next_8().is_none()); } //#[test] pub fn test_next_8_just_right() { // Start with 10 bytes. let slice = [0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8]; let mut bytes = Bytes::new(&slice); // Skip 2 of them. unsafe { bytes.advance(2); } // There should be 8 left, just enough to call next_8. let ret = bytes.next_8(); assert!(ret.is_some()); let mut ret = ret.unwrap(); // They should be the bytes starting with 2. assert_eq!(ret._0(), 2u8); assert_eq!(ret._1(), 3u8); assert_eq!(ret._2(), 4u8); assert_eq!(ret._3(), 5u8); assert_eq!(ret._4(), 6u8); assert_eq!(ret._5(), 7u8); assert_eq!(ret._6(), 8u8); assert_eq!(ret._7(), 9u8); } //#[test] pub fn test_next_8_extra() { // Start with 10 bytes. let slice = [0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8]; let mut bytes = Bytes::new(&slice); // Skip 1 of them. unsafe { bytes.advance(1); } // There should be 9 left, more than enough to call next_8. let ret = bytes.next_8(); assert!(ret.is_some()); let mut ret = ret.unwrap(); // They should be the bytes starting with 1. assert_eq!(ret._0(), 1u8); assert_eq!(ret._1(), 2u8); assert_eq!(ret._2(), 3u8); assert_eq!(ret._3(), 4u8); assert_eq!(ret._4(), 5u8); assert_eq!(ret._5(), 6u8); assert_eq!(ret._6(), 7u8); assert_eq!(ret._7(), 8u8); } } }
#include "NpcInteractions.h" #include "Player.h" #include "Npc.h" #include "Item.h" #include "Globals.h" #include "Battle.h" #include "Exit.h" #include "Room.h" using namespace std; bool checkGiven = false; bool capsuleGiven = false; void AttackNPC(const string &name, Player* player) { if (name == "MOTHER") { cout << "Just before you can act, your mother sends one of her trademarked icy stares at you." << endl; cout << "-And what, pray tell, are you plotting exactly?- she asks in what seems like a mix " << endl << "between a growl and a whisper." << endl; cout << "You KNOW she's onto you. Your survival incstinct is telling you to avoid any " << endl << "aggressive course of action towards your mother, or else you could actually DIE." << endl; } else if (name == "LARRY") { cout << "Larry simply laughs at you and throws a pack of bills at your face. The impact throws you " << endl << "off-track and makes you fall over." << endl; cout << "-Serves you right! I have far too much money for you to ever dream of hitting me anyway!" << endl; } else if (name == "PROFESSOR") { cout << "Right as you try to punch Stump, you feel an electrical discharge rock through your " << endl << "body." << endl; cout << "-My, oh, my!- The Professor exclaims. -Typical of your kind to try and resort to " << endl << "violence! You're probably asking yourself what would happen if you attacked poor " << endl << "little old me, but unfortunately for you I foresaw this in advance!" << endl; cout << "That's when you notice the Professor has a force field protecting her body. This " << endl << "feels strangely unfair, for some reason." << endl; player->Hurt(); player->AssessHP(); } } void TalkNPC(const string &name, Player * player) { if (name == "MOTHER") { if (player->GetCurrentHP() < player->GetMaxHP()) { cout << "Your mother raises an eyebrow when she sees you. -Geez, how do you always manage to get yourself into " << endl << "so much trouble?- She then offers you a piece of cake." << endl; cout << "As you eat, you feel your wounds healing themselves." << endl; cout << "-Yeah, I still don't understand how you do that. Healing just by eating cake, I mean. You're a weird " << endl << "one." << endl; int newPlayerHP = player->GetMaxHP(); player->SetCurrentHP(newPlayerHP); /*player->currentHP = player->maxHP;*/ player->AssessHP(); } else { switch (CURRENT_EVENT) { case START: cout << "-So the day has finally come, hasn't it?- She says as she grabs some chips from the bag. -When I " << endl << "was your age I too went on a journey to become a Zorkemon master... whatever that means. However, " << endl << "it is illegal for adults to compete in the big leagues." << endl; cout << "She changes the channel to some kind of crappy reality show about tunning toasters." << endl; cout << "-Whatever you do, remember you're always welcome back home. Just... try to keep away for a while, ok? " << endl << "Not that I don't want to have you around, mind you, it's just... Whatever, just go." << endl; cout << "She points to the door. This is your cue to exit." << endl; break; case PROFESSOR_FOUND: cout << "-Oh, so you met Stump? Did you know we were both best pals in high-school? She was actually really " << endl << "fun to have around. I mean, I would have died of boredom without her to bully or play pranks to. " << endl << "She's got this weird obsession with squids. I don't get it...- She shrugs."; cout << "-Someone locked her in her own warehouse, you say? My, my... I wonder who could do such a childish " << endl << "thing...- She says as she opens a can of beer, and you notice her eyes fidget a bit. -Yeah... " << endl << "I wonder..." << endl; break; case GOT_MONSTER: cout << "You try to start a conversation with your mother, but she seems way too invested in her TV drama." << endl; cout << "She might just be ignoring you on purpose." << endl; break; case BEAT_LARRY: cout << "-I heard you beat that rich kid next door. I am so proud of you. I'd treat you to a beer, but you're " << endl << "way too young to drink alcohol, aren't you? So instead I'll drink it for you! Cheers!- She happily " << endl << "beams as she opens two more beer cans. It's amazing how she can drink so much and yet only end up " << endl << "with minor tipsiness." << endl; break; } } } else if (name == "LARRY") { switch (CURRENT_EVENT) { case START: if (!checkGiven) { cout << "Larry diverges his attention from his legion of fangirls and smirks as he sees you come closer." << endl; cout << "-Oh, hello, did you come to see if I had some spare change to give? Here, let me help your " << endl << "moneyless self to get a bit further away from your misery." << endl; cout << "He extends you a blank check worth a hundred dollars." << endl; cout << "-Allow me to help. You need to go to the bank in order to retrieve the money. Yeah, the bank, " << endl << "you know, that place where people with money bring the money to keep it safe. I'm sure you've " << endl << "heard of it, though I suppose plebs like you are not too accustomed to visit it." << endl; player->ContainedIn()->Find("LARRY", NPC)->Find("CHECK", ITEM)->ChangeContainer(player); //Item* check = new Item("CHECK", "This check is worth 100 dollars. Make sure to exchange it next time you go to the bank.", player); checkGiven = true; } else { cout << "-Ah, you poor, poor penniless bloke... I forgot there's no bank in this village, so you'd need " << endl << "to travel to the city in order to exchange that check. But there's no way you can afford enough " << endl << "gasoline to get there. I could give you a ride on my unnecessarily large limousine, but I'm " << endl << "supposed to wait here for the helicopter carrying the giant golden statue of myself it's going to " << endl << "be installed in this very square this afternoon." << endl; } break; case PROFESSOR_FOUND: cout << "Larry sits with a self-sufficient grin as one of his servants massages his back. -Someone locked the " << endl << "professor inside the warehouse? Peasants really do play the silliest games. - He chuckles. -You're " << endl << "not accusing me, are you? The professor is kinda amusing, even by commoner standards. What's the point " << endl << "of an entertainer if you're going to keep her locked up?" << endl; break; case GOT_MONSTER: { cout << "-You have a monster? You?- He looks actually surprised. -I must admit I didn't expect for a low-born " << endl << "such as yourself to actually have one. I do train monsters as well, see? Naturally, my list of " << endl << "achievements is just as large as the number of digits in my bank account. Allow me to show you..." << endl; Entity* larrysMonster = player->ContainedIn()->Find(MONSTER); Entity* yourMonster = player->Find("CAPSULE", ITEM)->Find(MONSTER); Entity* larry = player->ContainedIn()->Find("LARRY", NPC); BattleStart((Monster*)yourMonster, (Monster*)larrysMonster, player, (Npc*)larry); break; } case BEAT_LARRY: cout << "He throws his arms up dramatically. -Haven't you humiliated me enough? Alas, poor you, you might have " << endl << "defeated me in a monster battle, but that means nothing. The only reality is that I'm still obscenely " << endl << "rich." << endl; break; } } else if (name == "PROFESSOR") { switch (CURRENT_EVENT) { case START: { cout << "The professor greets you when you come close. -Oh! F-finally! I thought I was gonna die in here. Someone locked " << endl << "me inside when I was busy looking for some pieces to tinker around..." << endl; cout << "She adjusts her glasses and looks around. -I know! Come and see me at the lab. I might have something to give " << endl << "you for your troubles!- She stumbles and almost trips on her way to the exit." << endl; Entity* prof = player->ContainedIn()->Find("PROFESSOR", NPC); Exit* toTown = (Exit*)prof->ContainedIn()->Find("DOOR", EXIT); Room* town = toTown->GetDestination(); Exit* toLab = (Exit*)town->Find("LABORATORY", EXIT); Room* lab = toLab->GetDestination(); prof->ChangeContainer(lab); CURRENT_EVENT = PROFESSOR_FOUND; break; } case PROFESSOR_FOUND: if (!capsuleGiven) { cout << "-Ah! There you are! Here, let me give you this as thanks.- She gives a small spherical capsule to you. -It's a " << endl << "monster capsule, created by none other than me! I don't have an IQ of over 200 for nothing!- She laughs." << endl; cout << "-Just use it on a monster and you will capture it! Since it's a special capsule made by me, there's no way the " << endl << "monster will escape. Just like the squid doesn't let go of their prey. I'm hungry now.- Just like that, she goes" << endl << "back yo her work." << endl; player->ContainedIn()->Find("PROFESSOR", NPC)->Find("CAPSULE", ITEM)->ChangeContainer(player); capsuleGiven = true; } else { cout << "The professor is eating a fried squid ring sandwich." << endl; cout << "-Rememfer: ufe dee capfule on a monftah do capfure eet.- She says with her mouth full. Looks like she's busy." << endl; } break; case GOT_MONSTER: cout << "-D-did you capture a monster already? Wait, the capsule actually worked!? I mean... Of course it worked! Man, I really " << endl << "am a genius!- She laughs loudly again." << endl; cout << "-Anyway, you could try your luck battling now. I'm sure someone around the village has a monster of his own." << endl; break; case BEAT_LARRY: cout << "-I heard you had your first victory already. Must be exilarating for someone so full of youth and energy. I was never " << endl << "too fond of the whole battling thing, however. Competition is not my thing. But SCIENCE... Man, science really gets me " << endl << "all randy!" << endl; break; } } } void NPCBattleResult(Player * player, Npc * rival, bool result) { if (rival->GetName() == "LARRY") { if (result == true) { cout << "=========" << endl << "YOU WON!!" << endl << "=========" << endl << endl; cout << "Larry stands there, dumbfounded for a moment, before quickly going back to his usual smug self, though " << endl << "you can tell he doesn't look very happy." << endl; cout << "-I guess you could say... I didn't give you enough CREDIT." << endl; cout << "As the legion of fangirls leave him, you finally realize you're on your way to become a real Zorkemon " << endl << "master. You captured a monster, defeated your rival (or the person who annoyed you the most, at least) " << endl << "and demonstrated your superiority in front of the village expectators. No doubt this is a day to " << endl << "celebrate, but your adventure has only just begun!" << endl << endl; cout << "THANK YOU FOR PLAYING ZORKEMON: RUSTY PEBBLE VERSION" << endl; cout << "This is the end of the game, but you can still go around to talk to people in town if you wish." << endl; cout << "I hope you enjoyed. :)" << endl << endl; CURRENT_EVENT = BEAT_LARRY; } else { cout << "==========" << endl << "YOU LOST!!" << endl << "==========" << endl << endl; cout << "Larry's fangirls use dollar bills as confetti to celebrate his victory." << endl; cout << "-It is only natural for those who have been born in the lowest tiers of class hierarchy to lose " << endl << "against those placed rightfully on top. Do not feel ashamed, this is just nature taking it's course." << endl; cout << "He then claps his hand twice and a butler approaches, using a potion on your monster." << endl; cout << "-If you want to try again don't let me stop you.- <NAME>. -Each time I win is more positive " << endl << "feedback for the sponsors of my multibillion dollar company." << endl << endl; Creature* playerMonster = (Creature*)player->Find("CAPSULE", ITEM)->Find(MONSTER); int monsterMaxHP = playerMonster->GetMaxHP(); playerMonster->SetCurrentHP(monsterMaxHP); } } }
/*========================================================================= Program: Visualization Toolkit Module: vtkRandomAttributeGenerator.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkRandomAttributeGenerator - generate and create random data attributes // .SECTION Description // vtkRandomAttributeGenerator is a filter that creates random attributes // including scalars, vectors, normals, tensors, texture coordinates and/or // general data arrays. These attributes can be generated as point data, cell // data or general field data. The generation of each component is normalized // between a user-specified minimum and maximum value. // // This filter provides that capability to specify the data type of the // attributes, the range for each of the components, and the number of // components. Note, however, that this flexibility only goes so far because // some attributes (e.g., normals, vectors and tensors) are fixed in the // number of components, and in the case of normals and tensors, are // constrained in the values that some of the components can take (i.e., // normals have magnitude one, and tensors are symmetric). // .SECTION Caveats // In general this class is used for debugging or testing purposes. // // It is possible to generate multiple attributes simultaneously. // // By default, no data is generated. Make sure to enable the generation of // some attributes if you want this filter to affect the output. Also note // that this filter passes through input geometry, topology and attributes. // Newly created attributes may replace attribute data that would have // otherwise been passed through. // .SECTION See also // vtkBrownianPoints #ifndef vtkRandomAttributeGenerator_h #define vtkRandomAttributeGenerator_h #include "vtkFiltersGeneralModule.h" // For export macro #include "vtkPassInputTypeAlgorithm.h" class vtkDataSet; class vtkCompositeDataSet; class VTKFILTERSGENERAL_EXPORT vtkRandomAttributeGenerator : public vtkPassInputTypeAlgorithm { public: // Description: // Create instance with minimum speed 0.0, maximum speed 1.0. static vtkRandomAttributeGenerator *New(); vtkTypeMacro(vtkRandomAttributeGenerator,vtkPassInputTypeAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Specify the type of array to create (all components of this array are of this // type). This holds true for all arrays that are created. vtkSetMacro(DataType,int); void SetDataTypeToBit() {this->SetDataType(VTK_BIT);} void SetDataTypeToChar() {this->SetDataType(VTK_CHAR);} void SetDataTypeToUnsignedChar() {this->SetDataType(VTK_UNSIGNED_CHAR);} void SetDataTypeToShort() {this->SetDataType(VTK_SHORT);} void SetDataTypeToUnsignedShort() {this->SetDataType(VTK_UNSIGNED_SHORT);} void SetDataTypeToInt() {this->SetDataType(VTK_INT);} void SetDataTypeToUnsignedInt() {this->SetDataType(VTK_UNSIGNED_INT);} void SetDataTypeToLong() {this->SetDataType(VTK_LONG);} void SetDataTypeToUnsignedLong() {this->SetDataType(VTK_UNSIGNED_LONG);} void SetDataTypeToFloat() {this->SetDataType(VTK_FLOAT);} void SetDataTypeToDouble() {this->SetDataType(VTK_DOUBLE);} vtkGetMacro(DataType,int); // Description: // Specify the number of components to generate. This value only applies to those // attribute types that take a variable number of components. For example, a vector // is only three components so the number of components is not applicable; whereas // a scalar may support multiple, varying number of components. vtkSetClampMacro(NumberOfComponents,int,1,VTK_INT_MAX); vtkGetMacro(NumberOfComponents,int); // Description: // Set the minimum component value. This applies to all data that is generated, // although normals and tensors have internal constraints that must be // observed. vtkSetMacro(MinimumComponentValue,double); vtkGetMacro(MinimumComponentValue,double); void SetComponentRange (double minimumValue, double maximumValue) { this->SetMinimumComponentValue (minimumValue); this->SetMaximumComponentValue (maximumValue); } // Description: // Set the maximum component value. This applies to all data that is generated, // although normals and tensors have internal constraints that must be // observed. vtkSetMacro(MaximumComponentValue,double); vtkGetMacro(MaximumComponentValue,double); // Description: // Specify the number of tuples to generate. This value only applies when creating // general field data. In all other cases (i.e., point data or cell data), the number // of tuples is controlled by the number of points and cells, respectively. vtkSetClampMacro(NumberOfTuples,vtkIdType,0,VTK_INT_MAX); vtkGetMacro(NumberOfTuples,vtkIdType); // Description: // Indicate that point scalars are to be generated. Note that the specified // number of components is used to create the scalar. vtkSetMacro(GeneratePointScalars,int); vtkGetMacro(GeneratePointScalars,int); vtkBooleanMacro(GeneratePointScalars,int); // Description: // Indicate that point vectors are to be generated. Note that the // number of components is always equal to three. vtkSetMacro(GeneratePointVectors,int); vtkGetMacro(GeneratePointVectors,int); vtkBooleanMacro(GeneratePointVectors,int); // Description: // Indicate that point normals are to be generated. Note that the // number of components is always equal to three. vtkSetMacro(GeneratePointNormals,int); vtkGetMacro(GeneratePointNormals,int); vtkBooleanMacro(GeneratePointNormals,int); // Description: // Indicate that point tensors are to be generated. Note that the // number of components is always equal to nine. vtkSetMacro(GeneratePointTensors,int); vtkGetMacro(GeneratePointTensors,int); vtkBooleanMacro(GeneratePointTensors,int); // Description: // Indicate that point texture coordinates are to be generated. Note that // the specified number of components is used to create the texture // coordinates (but must range between one and three). vtkSetMacro(GeneratePointTCoords,int); vtkGetMacro(GeneratePointTCoords,int); vtkBooleanMacro(GeneratePointTCoords,int); // Description: // Indicate that an arbitrary point array is to be generated. Note that the // specified number of components is used to create the array. vtkSetMacro(GeneratePointArray,int); vtkGetMacro(GeneratePointArray,int); vtkBooleanMacro(GeneratePointArray,int); // Description: // Indicate that cell scalars are to be generated. Note that the specified // number of components is used to create the scalar. vtkSetMacro(GenerateCellScalars,int); vtkGetMacro(GenerateCellScalars,int); vtkBooleanMacro(GenerateCellScalars,int); // Description: // Indicate that cell vectors are to be generated. Note that the // number of components is always equal to three. vtkSetMacro(GenerateCellVectors,int); vtkGetMacro(GenerateCellVectors,int); vtkBooleanMacro(GenerateCellVectors,int); // Description: // Indicate that cell normals are to be generated. Note that the // number of components is always equal to three. vtkSetMacro(GenerateCellNormals,int); vtkGetMacro(GenerateCellNormals,int); vtkBooleanMacro(GenerateCellNormals,int); // Description: // Indicate that cell tensors are to be generated. Note that the // number of components is always equal to nine. vtkSetMacro(GenerateCellTensors,int); vtkGetMacro(GenerateCellTensors,int); vtkBooleanMacro(GenerateCellTensors,int); // Description: // Indicate that cell texture coordinates are to be generated. Note that // the specified number of components is used to create the texture // coordinates (but must range between one and three). vtkSetMacro(GenerateCellTCoords,int); vtkGetMacro(GenerateCellTCoords,int); vtkBooleanMacro(GenerateCellTCoords,int); // Description: // Indicate that an arbitrary cell array is to be generated. Note that the // specified number of components is used to create the array. vtkSetMacro(GenerateCellArray,int); vtkGetMacro(GenerateCellArray,int); vtkBooleanMacro(GenerateCellArray,int); // Description: // Indicate that an arbitrary field data array is to be generated. Note // that the specified number of components is used to create the scalar. vtkSetMacro(GenerateFieldArray,int); vtkGetMacro(GenerateFieldArray,int); vtkBooleanMacro(GenerateFieldArray,int); // Description: // Indicate that the generated attributes are // constant within a block. This can be used to highlight // blocks in a composite dataset. vtkSetMacro(AttributesConstantPerBlock,bool); vtkGetMacro(AttributesConstantPerBlock,bool); vtkBooleanMacro(AttributesConstantPerBlock,bool); // Description: // Convenience methods for generating data: all data, all point data, or all cell data. // For example, if all data is enabled, then all point, cell and field data is generated. // If all point data is enabled, then point scalars, vectors, normals, tensors, tcoords, // and a data array are produced. void GenerateAllPointDataOn() { this->GeneratePointScalarsOn(); this->GeneratePointVectorsOn(); this->GeneratePointNormalsOn(); this->GeneratePointTCoordsOn(); this->GeneratePointTensorsOn(); this->GeneratePointArrayOn(); } void GenerateAllPointDataOff() { this->GeneratePointScalarsOff(); this->GeneratePointVectorsOff(); this->GeneratePointNormalsOff(); this->GeneratePointTCoordsOff(); this->GeneratePointTensorsOff(); this->GeneratePointArrayOff(); } void GenerateAllCellDataOn() { this->GenerateCellScalarsOn(); this->GenerateCellVectorsOn(); this->GenerateCellNormalsOn(); this->GenerateCellTCoordsOn(); this->GenerateCellTensorsOn(); this->GenerateCellArrayOn(); } void GenerateAllCellDataOff() { this->GenerateCellScalarsOff(); this->GenerateCellVectorsOff(); this->GenerateCellNormalsOff(); this->GenerateCellTCoordsOff(); this->GenerateCellTensorsOff(); this->GenerateCellArrayOff(); } void GenerateAllDataOn() { this->GenerateAllPointDataOn(); this->GenerateAllCellDataOn(); this->GenerateFieldArrayOn(); } void GenerateAllDataOff() { this->GenerateAllPointDataOff(); this->GenerateAllCellDataOff(); this->GenerateFieldArrayOff(); } protected: vtkRandomAttributeGenerator(); ~vtkRandomAttributeGenerator() {} virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual int FillInputPortInformation(int port, vtkInformation* info); int DataType; int NumberOfComponents; vtkIdType NumberOfTuples; double MinimumComponentValue; double MaximumComponentValue; int GeneratePointScalars; int GeneratePointVectors; int GeneratePointNormals; int GeneratePointTCoords; int GeneratePointTensors; int GeneratePointArray; int GenerateCellScalars; int GenerateCellVectors; int GenerateCellNormals; int GenerateCellTCoords; int GenerateCellTensors; int GenerateCellArray; int GenerateFieldArray; bool AttributesConstantPerBlock; // Helper functions vtkDataArray *GenerateData(int dataType, vtkIdType numTuples, int numComp, int minComp, int maxComp, double min, double max); int RequestData(vtkDataSet *input, vtkDataSet *output); int RequestData(vtkCompositeDataSet *input, vtkCompositeDataSet *output); template <class T> void GenerateRandomTuples(T *data, vtkIdType numTuples, int numComp, int minComp, int maxComp, double min, double max); private: vtkRandomAttributeGenerator(const vtkRandomAttributeGenerator&); // Not implemented. void operator=(const vtkRandomAttributeGenerator&); // Not implemented. }; #endif
import { Component, Renderer, ViewChild, ElementRef, Input } from '@angular/core'; import { Modal } from "ng2-modal"; import {ChildComponent} from './child/child.component' @Component({ selector: 'le', template: ` <modal #myModal1 modalClass="large-Modal" > <modal-header> <h3>Modal header</h3> </modal-header> <modal-content> Hello Modal! <button class="btn btn-primary" (click)="onClick()">open my modal</button> <child [id]=id1></child> </modal-content> <modal-footer> <button class="btn btn-primary" (click)="myModal1.close()">close</button> </modal-footer> </modal> `, styles: [` :host /deep/ .large-Modal { width: 99%; margin-top: 10px; } ` ] }) export class LeComponent { name = 'Angular'; id1 = ''; @Input() id: String; @ViewChild('myModal1') myModal1:Modal; ngOnChanges(){ if(this.id !== ''){ this.myModal1.open(); this.id1 = ''; } console.log(this.id); } onClick(){ this.id1 = this.id1 + '2'; } }
Two members of the Jedforest Hunt in the Borders have been found guilty of illegal fox hunting at Selkirk Sheriff Court in what is the first successful mounted fox hunting prosecution under the law which bans hunting. Father and son, 66 year old Clive Richardson and 23 year old Johnathon Riley both denied deliberately hunting a wild mammal on land surrounding Townfoothill near Jedburgh on 18th February 2016 but today 29th June 2017 were found guilty. The guilty verdict against whipper-in, Richardson and huntsman, Riley was reached with the help of video evidence supplied by the League Against Cruel Sports Scotland which showed the pair from Abbotrule, Bonchester Bridge breaching Section 1(2) of The Protection of Wild Mammals (Scotland) Act 2002. Robbie Marsland, Director of the League Against Cruel Sports, Scotland said: “Today’s guilty verdict is the first successful prosecution for mounted fox hunting in Scotland and while we’re delighted with the outcome, and our role in this, we remain of the view that the law needs strengthening. “The Scottish Government has committed to consult on the hunt ban following a review by Lord Bonomy, who clearly stated there was evidence of lawbreaking by Scottish hunts. In finding Johnathon Riley and Clive Richardson guilty, Sheriff Patterson has confirmed this to be the case. “We look forward to working with the Scottish Government to strengthen the law and hope today sends a clear message to hunts that flouting the law will not be tolerated and those who continue to hunt illegally in Scotland will be brought to justice.” Hunting has featured on the political agenda in recent weeks with First Minister Nicola Sturgeon recently confirming the Scottish Government’s opposition to fox hunting in response to a question in FMQs. In stark contrast, the Conservative manifesto ahead of the General Election includes a pledge to give MPs at Westminster a free vote to repeal the law which bans hunting in England and Wales. - Ends- Notes to editor
package com.kaesar.algorithm4.exercise.chp2; import com.kaesar.algorithm4.base.edu.princeton.cs.algs4.StdRandom; /** * 选择排序 */ public class Selection extends Example { public static void sort(Comparable[] a) { // 将 a[] 按升序排列 int N = a.length; // 数组长度 for (int i = 0; i < N; i++) { // 将a[i]和a[i+1..N]中最小的元素交换 int min = i; // 最小元素的索引 for (int j = i + 1; j < N; j++) { if (less(a[j], a[min])) { min = j; } } exch(a, i, min); } } public static void main(String[] args) { String[] a = new String[100]; for (int i = 0; i < 100; i++) { char x = (char) ('a' + (char) StdRandom.uniform(0, 26)); char y = (char) ('a' + (char) StdRandom.uniform(0, 26)); char z = (char) ('a' + (char) StdRandom.uniform(0, 26)); a[i] = String.valueOf(x) + String.valueOf(y) + String.valueOf(z); } System.out.println("-----before sort-----"); show(a); sort(a); assert isSorted(a); System.out.println("-----after sort-----"); show(a); } }
<gh_stars>1-10 import { Modal, Table } from "antd"; import React, { useMemo } from "react"; import { EditOutlined, DeleteOutlined } from "@ant-design/icons"; import { useStyleUtils } from "../../../../hooks/use-style-utils"; import { useQuery } from "@apollo/client"; import { useModelsHelper } from "./helper"; import _ from "lodash"; import { ModalForm } from "../../../../components/modal-form"; import ALL_MODELS from "./gql/all-models.gql"; import { AllModels } from "gql/types/operation-result-types"; const { confirm } = Modal; export const DictionaryModels = React.memo(() => { const styleUtils = useStyleUtils(); const allModelsQuery = useQuery<AllModels>(ALL_MODELS); const allModels = useMemo( () => allModelsQuery.data?.models.allModels || [], [allModelsQuery.data?.models.allModels], ); const { sendDeleteModel, helperLoading, sendUpdateModel, formFields, allBrand, } = useModelsHelper(); const columns = useMemo( () => [ { title: "Модель", dataIndex: "title", }, { title: "Марка", dataIndex: "brandId", render: (brandId: string) => allBrand?.find(elem => elem.id === brandId)?.title, }, { title: "", dataIndex: "edit", render: (_edit: any, record: any) => ( <> <ModalForm edit={_.pick(record, ["id", "title", "brandId"])} formFields={formFields} onSubmit={values => { sendUpdateModel({ id: record.id, ..._.pick(values, ["title", "brandId"]), }); values.setVisible(false); }} > {setVisible => ( <EditOutlined style={styleUtils.cursorPointer} onClick={() => setVisible(true)} /> )} </ModalForm> <DeleteOutlined style={styleUtils.cursorPointer} onClick={() => { confirm({ title: `Подтвердите удаление [${record.title}]`, onOk: () => { sendDeleteModel(record.id); }, }); }} /> </> ), }, ], [ allBrand, formFields, sendDeleteModel, sendUpdateModel, styleUtils.cursorPointer, ], ); const loading = helperLoading || allModelsQuery.loading; return ( <> <Table columns={columns} dataSource={allModels} loading={loading} /> </> ); });
// wxAuiStepColour() it a utility function that simply darkens // or lightens a color, based on the specified percentage // ialpha of 0 would be completely black, 100 completely white // an ialpha of 100 returns the same colour wxColor wxAuiStepColour(const wxColor& c, int ialpha) { if (ialpha == 100) return c; unsigned char r = c.Red(), g = c.Green(), b = c.Blue(); unsigned char bg; ialpha = wxMin(ialpha, 200); ialpha = wxMax(ialpha, 0); double alpha = ((double)(ialpha - 100.0))/100.0; if (ialpha > 100) { bg = 255; alpha = 1.0 - alpha; } else { bg = 0; alpha = 1.0 + alpha; } r = wxAuiBlendColour(r, bg, alpha); g = wxAuiBlendColour(g, bg, alpha); b = wxAuiBlendColour(b, bg, alpha); return wxColour(r, g, b); }
/** * Adds an attribute {@code yt:country} to {@link MediaRating}. * * */ @ExtensionDescription.Default( nsAlias = MediaRssNamespace.PREFIX, nsUri = MediaRssNamespace.URI, localName = "rating", isRepeatable = true) public class YouTubeMediaRating extends MediaRating { /** * Default value for the tag yt:country. */ private static final String ALL_COUNTRIES = "all"; /** * State the 'country' attribute is in. */ private enum CountryState { /** The attribute is unset. */ UNSET, /** The attribute is set to {@code all}. */ ALL, /** A country set is available in {@link #countries}. */ COUNTRIES } private CountryState countryState = CountryState.UNSET; /** * Unmodifiable set of countries, never {@code null}. */ private Set<String> countries = Collections.emptySet(); /** * Describes the tag to an {@link com.google.gdata.data.ExtensionProfile}. */ public static ExtensionDescription getDefaultDescription() { return ExtensionDescription.getDefaultDescription( YouTubeMediaRating.class); } @Override protected void putAttributes(AttributeGenerator generator) { super.putAttributes(generator); String countryValue; switch (countryState) { case ALL: countryValue = ALL_COUNTRIES; break; case COUNTRIES: countryValue = join(countries); break; case UNSET: countryValue = null; break; default: throw new IllegalStateException("Unknown state " + countryState); } if (countryValue != null) { generator.put(YouTubeNamespace.PREFIX + ":country", countryValue); } } @Override protected void consumeAttributes(AttributeHelper attrsHelper) throws ParseException { super.consumeAttributes(attrsHelper); String countryValue = attrsHelper.consume("country", false); if (countryValue == null) { clearCountry(); } else if (ALL_COUNTRIES.equals(countryValue)) { setAllCountries(); } else { setCountries(split(countryValue)); } } /** * Checks whether a country set is set. * * @return {@code true} if a country set is set, false if the rating * applies to all countries */ public boolean hasCountries() { return countryState == CountryState.COUNTRIES; } /** * Explicitely sets the attribute {@code country} to {@code all}. */ public void setAllCountries() { countryState = CountryState.ALL; countries = Collections.emptySet(); } /** * Clears the attribute {@code country} of any value. */ public void clearCountry() { countryState = CountryState.UNSET; countries = Collections.emptySet(); } /** * Defines the countries to which the rating applies. * * @param countries 2-letter country code set or {@code null} to * revert to the default value */ public void setCountries(Collection<String> countries) { if (countries == null || countries.isEmpty()) { clearCountry(); } else { this.countryState = CountryState.COUNTRIES; LinkedHashSet<String> set = new LinkedHashSet<String>(); for (String country : countries) { set.add(country); } this.countries = Collections.unmodifiableSet(set); } } /** * Gets the country set. * * @return country set, which may be empty but not {@code null} */ public Set<String> getCountries() { return countries; } private static String join(Collection<String> strings) { StringBuilder builder = new StringBuilder(); boolean isFirst = true; for (String string : strings) { if (isFirst) { isFirst = false; } else { builder.append(' '); } builder.append(string); } return builder.toString(); } private static Set<String> split(String value) { StringTokenizer tokenizer = new StringTokenizer(value, " "); int count = tokenizer.countTokens(); if (count == 0) { return Collections.emptySet(); } LinkedHashSet<String> tokens = new LinkedHashSet<String>(); while (tokenizer.hasMoreTokens()) { tokens.add(tokenizer.nextToken()); } return Collections.unmodifiableSet(tokens); } }
n = int(input()) a = list(map(int,input().split(' '))) l = [x for x in range(1,max(a)+1)] k = [] for i in l: x = 0 for j in a: if abs(j-i)>1: if(j>i): x += abs((j-i-1)) else: x +=abs(i-j-1) else: x += 0 k.append(x) print(k.index(min(k))+1,min(k))
// Validate Entry Block by merkle root func validateEBlockByMR(cid *common.Hash, mr *common.Hash) error { eb, err := db.FetchEBlockByMR(mr) if err != nil { return err } if eb == nil { return errors.New("Entry block not found in db for merkle root: " + mr.String()) } keyMR, err := eb.KeyMR() if err != nil { return err } if !mr.IsSameAs(keyMR) { return errors.New("Entry block's merkle root does not match with: " + mr.String()) } for _, ebEntry := range eb.Body.EBEntries { if !bytes.Equal(ebEntry.Bytes()[:31], common.ZERO_HASH[:31]) { entry, _ := db.FetchEntryByHash(ebEntry) if entry == nil { return errors.New("Entry not found in db for entry hash: " + ebEntry.String()) } } } return nil }
<gh_stars>0 strawberries=60 its_weekend = 0 if its_weekend: if strawberries > 39: print("fun") else: print("not fun") else: if strawberries > 39 and strawberries < 61: print("fun") else : print("not fun")
//GetArtistArtworks - get artworks by artistID func (s *Storage) GetArtistArtworks(artistID int64) ([]*listing.Artwork, error){ sqlStmt := `SELECT id, title, artistID FROM Artwork WHERE artistID = ?` rows, err := s.db.Query(sqlStmt, artistID) if err != nil { return nil, err } defer rows.Close() var arworks []*listing.Artwork for rows.Next() { var arwork listing.Artwork err = rows.Scan(&arwork.ID, &arwork.Title, &arwork.ArtistID) if err != nil { return nil, err } arworks = append(arworks, &arwork) } return arworks, nil }
Some airlines say they will change rules to ensure two crew are always in cockpit after Airbus A320 pilot is locked out before crash Some airlines are to change their rules to ensure two crew members are in plane cockpits at all times, after a co-pilot appeared to deliberately crash a Germanwings plane into the French Alps this week, killing all 150 on board. Questions have been raised about the lack of a “rule of two” among European carriers after Andreas Lubitz, 27, apparently crashed the Airbus A320 on Tuesday while the captain was locked out of the flight deck. Two low-cost European carriers – easyJet and Norwegian Air Shuttle – said on Thursday that they would bring the new rule into effect almost immediately. “EasyJet can confirm that, with effect from tomorrow … it will change its procedure,” the airline said in a statement, adding that the decision had been taken in consultation with the UK’s Civil Aviation Authority. Norwegian’s flight operations director, Thomas Hesthammer, said: “We have been discussing this for a long time but this development has accelerated things. When one person leaves the cockpit, two people will now have to be there.” Air Canada and the Canadian charter airline Air Transat also said they would require two people to be in the cockpit at all times. The CAA said it had asked all UK carriers to review procedures. “Following the details that have emerged regarding the tragic Germanwings incident, we are coordinating closely with colleagues at the European Aviation Safety Agency (EASA) and have contacted all UK operators to require them to review all relevant procedures,” a spokesman said. A “rule of two” is routine among US carriers. The US Federal Aviation Authority said in a statement: “US airlines have to develop procedures that the FAA approves. Those procedures include a requirement that, when one of the pilots exits the cockpit for any reason, another qualified crew member must lock the door and remain on the flight deck until the pilot returns to his or her station. A qualified crew member could be a flight attendant or a relief pilot serving as part of the crew.” According to rules set out by the European Aviation Safety Agency, pilots must remain at their “assigned station” throughout the flight, “unless absence is necessary for the performance of duties in connection with the operation or for physiological needs”. At this point, one pilot can leave the cockpit provided “at least one suitably qualified pilot remains at the controls of the aircraft at all times”. The last minutes of Germanwings flight 4U9525 Read more French officials said Lubitz appeared to have locked his fellow pilot out of the cockpit before he deliberately crashed the plane. Emergency codes allow crew to enter a locked cockpit in the event of incapacitated pilots, but Lubitz would have been able to override it – a post-9/11 security measure intended to prevent hijack. In a press conference after the tragedy, Lufthansa’s chief executive, Carsten Spohr, said the company had full trust in its pilots and those flying for its low-cost division, Germanwings. “In a company like ours where we are so proud of our selection criteria, our safety criteria, this is even more of a shock for us than it is for the general public,” said Spohr. “We can only speculate on what might have been the motivation of the co-pilot.” He defended the company’s policy of allowing one pilot to operate alone in the cockpit, saying that rival operators used the same system. US airlines have different systems for minimising the risk to pilots while flying, which often involve using food carts as makeshift barricades. “Every airline in the United States has procedures designed to ensure that there is never a situation where a pilot is left alone in the cockpit,” said a representative for the Air Line Pilots Association.
def help_command(update, context): update.message.reply_text('Read the instructions carefully before starting the hunt\n1. Use your laptop to hunt ' 'the treasure\n2. While typing your answer you have to follow certain rules\na) There ' 'must not be any space in between the answer\nb) Start your answer with a forward slash ' '(/) ' ', no other symbols to be used\nc) All letters should be in lower case for ' 'example: /answerriddle\n' '3. you will be getting some special codes while solving the riddles ,collect them to ' 'use at the final step of the game ** Codes are in Bebas Nueue Font**')
The Los Angeles Department of Water and Power works on a major construction project, but the results will be hard to see. Construction of a 55-million-gallon water tank is underway west of the 134 Freeway. Patrick Healy reports from Griffith Park for the NBC4 News at 6 p.m. Wednesday, Nov. 13, 2013. (Published Wednesday, Nov. 13, 2013) Take a look while it's still visible. A new concept for safeguarding the water supply in Los Angeles is taking shape in full view of travelers on the 134 Freeway passing by Griffith Park. "What you're seeing is construction of a 55-million-gallon tank," said Susan Rowghani, Director of Water Engineering for the Los Angeles Department of Water and Power (LADWP). The massive enclosure, 35 feet deep and sitting on 7 acres, is being made of reinforced concrete, and unlike surface reservoirs, will be fully enclosed. As soon as what's called the "Headworks" project is completed, it will disappear from sight, covered with three feet of soil, with a new park to be landscaped on top. The project is part of the LADWP's response to federal EPA water quality requirements that effectively make open reservoirs obsolete, according to Martin Adams, LADWP's director of Water Operations. Construction began early in 2012. "I didn't realize how big it was going to be when they started," said Noel de Paz of Van Nuys, a frequent visitor to Griffith Park who was been watching the construction progress. Completion of the first Headworks reservoir is targeted for next vember. A sister reservoir is expected to be finished in 2017. Together, the Headworks reservoirs will replace Silver Lake and its companion Ivanhoe Reservoir. At the urging of the community, water will remain in the reservoirs, but not as part of the city's drinking water supply. The feasibility of using recycled water, or perhaps Los Angeles River runoff will be explored, Adams said. As a stopgap covering measure, the Ivanhoe Reservoir currently is covered with thousands of "shade balls" to block UV radiation to discourage the growth of algae and other biological contaminants. Silver Lake has already been removed from the water supply. The combined 110-million-gallon capacity of the Headworks reservoirs amounts to only a day's supply for the 4 million Angelenos supplied by the LADWP. But in conjunction with other reservoirs and new pipelines, the Headworks serves as a "buffer" that will better enable the DWP to distribute water and respond to temporary disruptions of supply, Adams said. Early on, the DWP considered upgrading and covering the Silver Lake Reservoirs, but ultimately concluded it would be better, and likely less expensive, to build at a new location, Adams said. "We couldn't put bandaids on the system," Adams said. More than a century ago, the Headworks location had been one of the first locations where city officials tapped the Los Angeles River into a municipal water system. Later, it served as a spreading basin, with water diverted from the river allowed to percolate through the soil to recharge natural underground aquifers. That role ended in the early 1980s when the water in the LA River was deemed no longer suitable for spreading basin use. Industrial comtaminants, including the carcinogen hexavalent chromium, have been detected in much of the groundwater beneath the San Fernando Valley, and the possibility had to be explored that soil at the Headworks site might also have been contaminated, and samples were tested. "There were a lot of concerns that we may have spread water that had contaminants, but we did not find any evidence of that in the soil. We were very fortunate," Adams said. Had contaminated soil been found, the challenge of dealing with it might have made the Headworks Project impractical. Building a system to decontaminate the tainted groundwater and be able to use it for the water supply is a major initiative the LADWP intends to pursue. It is expected to take years and cost half a billion dollars, Adams said. The Headworks will draw on existing LADWP water sources, including aqueduct water from the Eastern Sierra, and wells that draw on uncontaminated groundwater. In addition to the park envisioned atop the Headworks reservoirs, there are also plans to create a wetlands at the west end of the property, using runoff diverted from the LA River. The wetlands will be underlain with a water resistant barrier to keep the river water from percolating through the soil, and it will be diverted back to the concrete riverbed downstream. More Southern California Stories:
Candice Miller could be the only woman atop a committee is she gets Homeland Security. Election causes angst for House GOP Last week’s Republican bloodbath is causing angst in a series of House leadership elections. The GOP’s problems with women — laid bare by last week’s elections — is the main undertone in the battle for head of the Homeland Security Committee between Reps. Mike Rogers of Alabama and Candice Miller of Michigan. That race, combined with the contest for head of the Republican Conference, is becoming a proxy for a larger discussion about a dearth of Republican women in power in the House. Story Continued Below (Also on POLITICO: Full coverage of the war over the future of the GOP) To a person, key Republicans privately concede that Rogers has done everything right to become chairman. The same people also say Miller is likely to get the gavel. If so, she would be the only woman to chair a committee. “They don’t have to pick me just because I’m a woman,” Miller said in an interview with POLITICO. “I would tell you this, if my name was Bob Miller, we wouldn’t even be having this conversation.” She said she thinks she would have it locked up already. Another complication for leaders is Rep. Paul Ryan’s return to the House. Leaders are expected to reappoint the Wisconsin Republican as head of the Budget Committee even though he’s reached the term limit for committee heads. That has others wondering why the party’s golden boy is getting special treatment. ( Also on POLITICO: 2016 hangs over Paul Ryan's return) “I have told John Boehner that I will abide by what John wants,” Homeland Security Chairman Pete King (R-N.Y.) told POLITICO. “I was told that nobody would be getting waivers, including Paul Ryan. Obviously, if Paul is going to get a waiver, I will discuss it with the speaker.” House leadership elections and the selection of committee heads are always unseemly affairs. They pit friends against friends and force leadership to work back channels to boost the candidates of their choice. This year is not the worst by any means. But the tensions speak to larger questions being asked in Republican politics — like about the lack of minorities in top positions. For example, there are no Hispanics in leadership and one African-American — Rep. Tim Scott of South Carolina, who will be the only African-American Republican in Congress after the defeat of Florida Rep. Allen West, who has yet to concede. In the race for the head of the Republican Conference, Rep. Cathy McMorris Rodgers of Washington state is trying to fend off Georgia Rep. Tom Price to remain the only woman in a top leadership spot. Republican leaders are confident McMorris Rodgers will win —they haven’t endorsed her, but some are quietly working to keep apprised of the race. McMorris Rodgers’s allies, both inside and outside leadership, want to see her battle it out with Price to show her internal strength.
def proximity(self): x, y = np.round(self.pos).astype(int) proximity = self.world.state[y - self.prox_range : y + self.prox_range + 1, x - self.prox_range : x + self.prox_range + 1] if self.prox_range > 1: proximity = np.multiply(proximity, self._mask).clip(0, 1) else: proximity = proximity.clip(0, 1) return proximity
<reponame>jakedageek/ftc-2013 #ifndef BLOCK_LOADER_H #define BLOCK_LOADER_H #define BLOCK_LOADER_OUT 170 #define BLOCK_LOADER_IN 78 #endif //HEADER FILE FROM 2013-2014
def collection_names(): return [ 'camera_board', 'control_board', 'camera_env_board', 'control_env_board', 'config', 'current', 'drift_align', 'environment', 'mount', 'observations', 'offset_info', 'power', 'safety', 'state', 'telemetry_board', 'weather', ]
<reponame>collingreen/hot-ts-react-redux<filename>src/store/index.tsx<gh_stars>0 import { createStore, combineReducers, applyMiddleware } from 'redux' import createSagaMiddleware from '@redux-saga/core' import { composeWithDevTools } from 'redux-devtools-extension' import { lettersReducer } from './letters/reducers' import rootSaga from './sagas' const rootReducer = combineReducers({ letters: lettersReducer, }) export type AppState = ReturnType<typeof rootReducer> export default function configureStore() { const sagaMiddleware = createSagaMiddleware() const middleWareEnhancer = applyMiddleware(sagaMiddleware) var win = window as any if (!win.store) { win.store = createStore( rootReducer, composeWithDevTools(middleWareEnhancer) ) win.__sagaTask = sagaMiddleware.run(rootSaga) win.__sagaMiddleware = sagaMiddleware } else { win.store.replaceReducer(rootReducer) // re-import the saga list const newRootSaga = require('./sagas').default // cancel any current sagas and attach new ones win.__sagaTask.cancel() win.__sagaTask.toPromise().then(() => { win.__sagaTask = win.__sagaMiddleware.run(newRootSaga) }) } return win.store }
def do_user_search(data, num_results=None): query = data.get('q') if (not query) or len(query) > MAX_QUERY_LENGTH: return (None, []) try: user = User.objects.get(username=query) except User.DoesNotExist: user = None try: auto_results = SearchQuerySet()\ .filter_or(username_auto=query)\ .filter_or(first_name_auto=query)\ .filter_or(last_name_auto=query)\ .filter_or(full_name_auto=query) suggestions = [result.object for result in auto_results] if num_results: suggestions = suggestions[:num_results] except KeyError: suggestions = [] return (user, suggestions)
package ru.job4j.list; class Node<T> { T value; Node<T> next; public boolean hasCycle(Node first) { boolean result = false; Node<T> indexI = first; Node<T> indexJ = first; while (indexJ.next != null) { indexI = indexI.next; indexJ = indexJ.next.next; if (indexI == indexJ) { result = true; } } return result; } }
package wendergalan.github.io.webflux.domain; import lombok.*; import org.springframework.data.annotation.Id; import org.springframework.data.relational.core.mapping.Table; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Data @NoArgsConstructor @AllArgsConstructor @With @Builder @Table("anime") public class Anime { @Id private Integer id; @NotNull @NotEmpty(message = "The name of this anime cannot is empty.") private String name; }
def create_source(configuration: SdrVariables, factory) -> DataSource: data_source = factory.create(configuration.input_source, configuration.input_params, configuration.sample_type, configuration.sample_rate, configuration.centre_frequency_hz, configuration.input_bw_hz) return data_source
def _non_framed_body_length(header, plaintext_length): body_length = header.algorithm.iv_len body_length += 8 body_length += plaintext_length body_length += header.algorithm.auth_len return body_length
def Args(parser): flags.AddPrivatecloudArgToParser(parser, positional=True) parser.add_argument( '--description', help="""\ Text describing the private cloud """) parser.add_argument( '--external-ip-access', action='store_true', default=None, help="""\ Enable public ips for management vms. Use --no-external-ip-access to disable """) labels_util.AddCreateLabelsFlags(parser)
<reponame>enesonmez/data-science-tutorial-turkish """ Genelde verilerimizi değişkenlerde saklarız. Ancak verilerdeki değişimler program sonlandığında bellekten silinir. Bu verileri saklamak için dosya işlemlerine ihityaç duyarız. Dosya okumak çoğu proje için olmazsa olmazdır. Bu dosyalarda işlemeniz gereken veriler olabilir ya da işlediğiniz verileri saklamak için kullanabileceğinz bir ortam olarak düşünebilirsiniz. Dosyalar binary dosyalar (resim,ses,vb.) ve metin dosyaları (.txt,.xlxs(excel).vb) olarak ikiye ayrılır. Bu partta size metin dosyalarında okuma modlarını, dosya okumayı, yazmayı öğreteceğiz. """ #Dosya Okuma Yazma Modları """ 'r' modu: Dosyayı sadece okumak için açar. Bu mod varsayılan moddur. 'r+' modu: Dosyayı hem okumak hem de yazmak için açar. Eğer çağrılan dosya bulunamadıysa yeni bir dosya oluşturulmaz. 'w' modu: Dosyayı sadece yazmak için açar. Varolan dosyanın üzerine (içeriği silip) yazma işlemini yapar. Eğer çağrılan dosya bulunamadıysa yeni bir dosya oluşturur. 'w+' modu: Dosyayı hem okumak hem de yazmak için açar. Varolan dosyanın üzerine yazma işlemini yapar. Eğer çağrılan dosya bulunamadıysa yeni bir dosya oluşturur. 'a' modu: Dosyayı ekleme işlemi için açar. Eğer çağrılan dosya bulunursa, en sonundan eklemeye devam eder. Eğer dosya yoksa sadece yazma işlemi yapacak yeni bir dosya oluşturur. 'a+' modu: Dosyayı hem ekleme hem de okuma işlemi için açar. Eğer çağrılan dosya bulunursa, en sonundan eklemeye devam eder. Eğer dosya yoksa yazma ve okuma işlemleri yapacak yeni bir dosya oluşturur. 'x' modu: Dosya yoksa dosya oluşturur. """ import os #Dosya Açma İşlemi ve Dosya Var mı Kontrolü if not os.path.isfile("files/veri.txt"):#Kontrol files = open("files/veri.txt","a+") #Dosya yoksa oluşturulur. else: files = open("files/veri.txt","r") #Dosya varsa okuma modunda açılır. # Pratik Dosya Açma Yöntemi """ Bu yöntem ile dosyanızı kapatmak zorunda kalmıyorsunuz. Bu işlem bloğu tamamlandığında dosyanız otomatik olarak kapanıyor.""" with open('files/veri.txt', 'r') as file: file.read() #Dosya Okuma Yolları #print(files.read())#Dosyanın tümünü okur. Genelde dosyadaki karakter sayısını öğrenmek için kullanırız. #print(files.read(20))#Belirtilen sayıda karakter okur. #print(files.readline())#Tek bir satır okur. #print(files.readlines())#Tüm satırları okur listeye atar. Dosyadaki satır sayısını öğrenmek için kullanırız. """ Eğer dosyayı açıp dönen nesneyi eşitlediğimiz değişkeni bir döngü içinde çalıştırırsak readlines metodu gibi bize satır satır veri döndürür. """ for l in files: # Dosyadaki satırları döngü yardımıyla okur. print(l) """ Evinizin kapısını nasıl kapatıyorsanız dosyalarınızı da kapatmanız gerekiyor. Aşağıda :)""" files.close() #Dosyaya Yazma files = open("files/veri.txt","w") files.write("Enes Sönmez") files.write("\n") #Listeyi Dosyaya Yazma files.writelines(["Kamil Duran\n","Sadık Çiftçi\n"]) files.close() #Dosya Silme """ os modülü ile dosayayı silebiliriz.""" #os.remove("files/veri.txt") #Dosya Metotları """ seek(): Dosya imlecini istenilen noktaya koyar. teel(): İmlecin konumunu gösterir. name(): Dosya ismini söyler. mode(): Dosya modunu söyler. closed(): Dosya kapalı mı sorugusunu yapar. writable(): Dosya yazma modunda mı kontrolü yapar. readable(): Dosya okuma modunda mı kontrolü yapar. """ files = open("files/veri.txt","r") files.seek(3) print(files.read()) print(files.tell()) print(files.name) print(files.mode) print(files.closed) print(files.writable()) print(files.readable()) files.close()
/// Creates an iterator over `CrossLink` instances in the direction specified. /// /// ## Cycles /// /// The links in a dependency cycle will be returned in non-dev order. When the direction is /// forward, if feature Foo has a dependency on Bar, and Bar has a cyclic dev-dependency on Foo, /// then the link Foo -> Bar is returned before the link Bar -> Foo. pub fn cross_links<'a>( &'a self, direction: DependencyDirection, ) -> impl Iterator<Item = CrossLink<'g>> + 'a { let graph = self.graph; self.core .links(graph.dep_graph(), graph.sccs(), direction) .filter_map(move |(source_ix, target_ix, edge_ix)| { graph.edge_to_cross_link(source_ix, target_ix, edge_ix, None) }) }
Structural, Mechanical and Flammability Characterization of Crosslinked Talc Composites with Different Particle Sizes The influence of filler particle size on selected physicochemical and functional properties of polymer composites was analyzed. The following test was carried out for the system: the bisphenol A glycerolate (1 glycerol/phenol) di-methacrylate (BPA.DM) was subjected to UV-polymerization in bulk with N-vinyl-2-pyrrolidone (NVP) as a polymer matrix and talc with particle sizes ranging from ≤8 to 710 µm as a non-toxic and cheap mineral filler. An effective method of preparing cross-linked polymeric composites with talc was developed. The obtained samples were subjected to structural analysis and the thermal, mechanical and flammability properties were assessed. It has been empirically confirmed that the talc particles are incorporated into the composite structure. However, with increasing particle size, the composite heterogeneity increases. In the case of the developed method of sample production, homogeneous systems were obtained for particles in the ≤8–250 µm range. The surface roughness of the samples correlates directly with the size of talc particles. The value of Young’s modulus during the axial stretching of samples decreases with the increasing size of talc particles. For the composites containing ≤15 and ≤35 µm talc particles, the highest values were obtained under bending conditions. There was no equivocal effect of particle size on the composites’ swelling in water. The addition of talc reduces the flame height and intensity slightly. The biggest difference was obtained for the composites containing relatively large talc particles. It was proved that the selected properties of polymer composites can be controlled depending on the size of the talc particles. Introduction Minerals are widely employed as fillers in the plastic industry. As the most commonly applied minerals one can include: calcium carbonate, clay, silica, talc, kaolin, mica, wollastonite and alumina trihydrate . Besides the reduction in production costs, mineral fillers affect the final mechanical features of polymers or polymeric composites. They induce changes in the morphology of the polymeric chains and modify the volumetric properties of composites . Additionally, the filler morphology, particle size, shape and distribution or crystalline degree have a major influence on the action, processing and properties of polymer composites . The properties of polymer-inorganic composites are largely related to the interfacial adhesion between the polymeric matrix and the filler. The non-polar and chemically inert polyolefins (e.g., polyethylene-PE, polypropylene-PP) are the most common polymers. They do not interact with most inorganic fillers, which results in poor dispersion and weak interfacial adhesion. In consequence, reduced physical properties are observed . To overcome the limitations associated with the preparation of non-polar composites with different fillers, various coupling agents such as phosphate silanes, titanium esters, aluminates and zirconates have been used . Another way to enhance the compatibility of bulk polymers with inorganic fillers is by functionalization of polymer composites. The typical way to functionalize polyolefins is by grafting polar monomers, e.g., acrylic or methacrylic monomers or styrene, onto the polymer backbone. The functional polymeric compounds can interact strongly with fillers and polymeric chains. However, this technique has some limitations (e.g., crosslinking effect, degradation of polymeric chains or high degree of volatilization). A better effect can be achieved by using reactive polar monomers . Talc (Mg 3 Si 4 O 10 (OH) 2 ) is a clay mineral generally applied as an additive in polymeric composites, especially in the context of flame retardancy . Wang et al. reported the methodology of composite fabrication based on polypropylene and talc fillers obtained by grinding pulverization. The properties of the materials made by the new method and by using pulverized talc methods were compared. Composite morphology studies show particle orientation and homogeneous dispersion of pulverized talc in the polypropylene matrix . Wawrzyn et al. described four different inorganic additives, investigated for bisphenol A derivatives to improve flame retardancy. The pyrolysis, small flame response and fire behaviour of the blends were examined and the structure-property interactions were taken into consideration. Among the applied layered materials, talc was found to be a neutral additive while the modified montmorillonite improved decomposition . Polymeric blends which are derivatives of bisphenol A polycarbonate with acrylonitrile/butadiene/styrene (PC/ABS) were investigated by Schartel et al. in terms of their fire behaviour, pyrolysis and flammability. It was established that the presence of talc had an impact on the pyrolysis and flammability results, since it contributed to a reduction of gas diffusion and increased the flow limit at small shear rates. Furthermore, the use of talc allowed enhancement of the protective properties of fire residues and also to partially suppress the flame inhibition and charring effect caused by bisphenol A bis(diphenyl phosphate) . Qiu et al. studied the effects of talc size on structure and properties of composites based on poly(vinyl alcohol) (PVA). The results showed that reducing the talc particles increased the number of -OH groups at the edges of the talc layers, which improved the compatibility between talc and PVA. Additionally, the smaller talc particles were more uniformly dispersed in the PVA matrix . The effect of particle size on the dimensional stability, morphology and mechanical properties of composites based on polycarbonate, poly(butylene terephthalate) and talc was investigated by DePolo and Barais . It was found that the use of talc nanoparticles (instead of fine talc) brought about an increase in flexural and tensile strength, and a decrease in the density of talc composites. Compatibility of the polymer matrix and filler is a key issue from the point of view of the technology of producing composites. A properly selected system allows the elimination of additional substances from the structure of the composite responsible for reducing the interfacial tension. Moreover, proper compatibility eliminates the need to chemically modify the filler surface. Talc is commonly used as an inexpensive filler for thermoplastic polymers but its application for bisphenol A derivatives has not been extensively studied. Due to many studies confirming the carcinogenic effect of bisphenol A, its use in food packaging has been restricted in a number of countries. On the other hand, its application in industrial chemistry has not diminished and it still finds many applications. Bisphenol A derivatives (epoxy resins, acrylates) are widely used in powder paints, varnishes (chemical-resistant, insulating, electro-insulating), and adhesives for metals, glass, ceramics, thermosetting plastics. They are also found in the construction industry e.g., as sealing and flooring materials. Because bisphenol A products are largely employed in the direct human environment, the study of flammability and degradation of the prepared composites is interesting and purposeful . Herein, the effective method for the preparation of cross-linked polymeric composites with different particle sizes of talc is presented and their thermal, mechanical and flammability properties are discussed in detail. Our goal is to show how the use of a raw material with different particle sizes affects the properties of composites. As a main crosslinking monomer the bisphenol A glycerolate (1 glycerol/phenol) di-methacrylate (BPA.DM) was used. The UV-polymerization of BPA.DM monomer with N-vinyl-2-pyrrolidone via the bulk polymerization technique is investigated. Talc with different particle sizes was used as a nontoxic and cheap filler. Various fractions of ground talc were applied in the research, and in scope covered particles with sizes from ≤8 to 710 µm. The influence of talc particle size on the quality and properties of the composites was evaluated. The spectroscopic studies of the obtained composites were characterized by means of the attenuated total reflection-Fourier transform infrared (ATR-FTIR) spectroscopy. The influence of the filler addition on the structural, mechanical and thermal properties was evaluated. Materials Bisphenol A glycerolate (1 glycerol/phenol) di-methacrylate (BPA.DM), N-vinyl-2pyrrolidone (NVP) and 2,2-dimethoxy-2-phenylacetophenone (Irgacure 651, IQ) were purchased from Merck, Darmstadt, Germany. The talc particles were obtained from Elementis Minerals (East Windsor, NJ, USA). The following talc products were used: The values given next to the name mean that 98% of the talc particles are of an equal or smaller size (d98%) in µm. All chemicals were used as received. Analytical Methods Assessment of morphological properties was carried out using the FEI Quanta 250 FEG Scanning Electron Microscope (SEM) (FEI Inc., Eindhoven, The Netherlands). Untreated samples were fixed on the aluminum stubs using double-sided carbon tape and analyzed in the low vacuum mode with an atmospheric pressure of 130 Pa, avoiding typical coating of the artefacts. A dispersive X-ray (EDX) spectrometer (Octane Elect Silicon Drift Detector, EDAX, AMETEK Inc., Berwyn, PA, USA) was used for elemental identification and quantitative compositional analysis of the energy. Visual inspection of solid composites was carried out using the optical microscope Morphology G3 (Malvern Panalytical, Malvern, UK). A Bruker Tensor 27 FTIR spectrometer (Bruker Optics GmbH & Co. KG, Ettlingen, Germany) was used to record FTIR spectra based on the attenuated total reflectance (ATR) technique for samples in the form of thin films. All measurements were conducted at room temperature in the range of 4000-600 cm −1 . The presented spectra are based on averaging 32 scans with a resolution of 4 cm −1 in the absorbance mode. Netzsch Differential Scanning Calorimetry (DSC) 204 F1 Phoenix calorimeter (NET-ZSCH GmbH & Co. Holding KG, Selb, Germany) operating in a dynamic mode was employed to conduct the calorimetric measurements, using the following experimental set-up: a heating rate of 10 • C/min, from room temperature to a maximum of 550 • C, with nitrogen as the inert gas (30 mL/min). The mass of the samples was equal to approx. 10 mg and an empty aluminum crucible was used as a reference. The reported transitions came from the first heating scans. An optical profilometer (Contour GT-K1, Veeco, Aschheim/Dornach Munich, Germany) was used to investigate the morphological images and surface roughness of the samples. This device is characterized by high accuracy in the size range from the sub-nanometer to 10 mm; nevertheless, the imaging was repeated 3 times for each sample in order to determine the average roughness (R a ) parameter. A Zwick7206/H04 durometer (Zwick Roell Group, Ulm, Germany), type D, was employed to carry out the Shore hardness tests (measurements were taken after 15 s at a temperature of 21 • C). The equilibrium swelling in selected organic solvents and distilled water were used to determine the swelling coefficients (B) based on the following equation : where m s is the mass after swelling and m d is the mass of the dry sample. A Zwick/Roell Z010 universal tensile-testing machine (Ulm, Germany) was used to carry out strength tests for samples in the form of a pressed sheet. Uniaxial tensile strength tests were performed using 4 mm × 10 mm × 60 mm samples at a test speed of 50 mm/min and at 23 • C, in accordance with EN-ISO 527. The analysis of bending strength was conducted based on three-point bending tests, in accordance with EN-ISO 170 and ASTM D-790. Subsequent testing of flammability was based on the horizontal burning test carried out in a device that included a combustion chamber, ventilation system and thermal imaging camera. The procedure is in accordance with the PN-EN 60695-11-10-method A. The samples were placed on a tripod and moved near a methane burner at an angle of 45 • . After 10 s, the samples were left to burn freely for 30 s. The measurement included collection of thermal images of the samples (after every 5 s), measurement the total burning time and examining of the length of the sample after burning. The images of samples were collected using a V-20 thermo-vision camera model ER005-25 (Vigo System, Ożarów Mazowiecki, Poland), which operates in the temperature measurement range from −10 to 250 • C with a measurement accuracy of ±2 • C. Synthesis of Composites In order to obtain the composites tested in this study, BPA.DM and NVP were introduced into a glass vessel at a ratio of 70:30 wt%. After subsequent mixing to ensure proper homogenization, the vessel was transferred to a heating chamber (60 • C) and the UV initiator (IQ) was added (at an amount equal to 2 wt% of the initial polymer mixture). An appropriate (20 wt%) amount of talc particles (8,15,35,50,250, 500 or 710 µm) was added in the last step. Then, the vessel was subjected to gentle stirring and placed in the heating chamber again (60 • C) for approx. 20 min. Afterwards, the mixture was poured into 100 mm × 80 mm glass moulds equipped with Teflon spacers. Finally, the mixture was exposed to UV light (15 min) inside the irradiation chamber with four mercury lamps of 40 W . All the relevant parameters of the experimental set-up are presented in Table 1, whereas the assumed structure of the obtained composite is presented in Figure 1. Results and Discussion As a result of the UV polymerization reaction, eight composites, differing in particle size, of talc additive ranging from ≤8 to 710 µm were obtained (see Table 1). Raw materia without any modification was used for the synthesis of compositions. The stated particle sizes shown in the talc data were provided by the producer, and the figure states the max imum particle size. In the case of six composites the material with the uniform filler dis persion was obtained. On the other hand, the talc particle sizes of ≤500 and ≤710 µm were found be too heavy, and talc falling to the bottom of the mold was observed. Therefore the samples BPA.DM-NVP-0 to BPA.DM-NVP-5, uniform in their volume, were selected for thermal, swelling, profilometer, mechanical and flammability tests. Visualization of the Studied Materials In Figure 2 the images of talc (with different sizes, used as a filler in the composites by means of scanning electron microscope (SEM) analysis are presented. Due to the thick ness of the samples, a better quality of polymerized composites image was obtained using an optical microscope. Results and Discussion As a result of the UV polymerization reaction, eight composites, differing in particle size, of talc additive ranging from ≤8 to 710 µm were obtained (see Table 1). Raw material without any modification was used for the synthesis of compositions. The stated particle sizes shown in the talc data were provided by the producer, and the figure states the maximum particle size. In the case of six composites the material with the uniform filler dispersion was obtained. On the other hand, the talc particle sizes of ≤500 and ≤710 µm were found be too heavy, and talc falling to the bottom of the mold was observed. Therefore, the samples BPA.DM-NVP-0 to BPA.DM-NVP-5, uniform in their volume, were selected for thermal, swelling, profilometer, mechanical and flammability tests. Visualization of the Studied Materials In Figure 2 the images of talc (with different sizes, used as a filler in the composites) by means of scanning electron microscope (SEM) analysis are presented. Due to the thickness of the samples, a better quality of polymerized composites image was obtained using an optical microscope. ATR/FTIR Spectra of the Obtained Composites The ATR/FT-IR spectra for the BPA.DM-NVP copolymers with various talc content are presented in Figure 4a,b. Comparison of spectra of the starting material and that of modified composites revealed the most notable changes (which are marked in Figure 4). The main differences are associated with the presence of a strong signal (at approx. 3400 cm −1 ) which corresponds to the -OH groups, bands assigned with the C-H stretching vibrations (asymmetric at approx. 2968 cm −1 and symmetric at 2850 cm −1 ) and bending vibrations of the -CH3 group (at 1460 and 1435 cm −1 ). Furthermore, there are two distinct signals, which should be highlighted. The first is a sharp band (at 1716 cm −1 ) that can be attributed to the stretching and out-of-plane-bending vibrations of the carbonyl (C=O) group. The second (at 1667 cm −1 ) is associated with the N-C=O stretching vibration originating from the amide group (NVP). The presence of talc contributed to visible changes in the spectra, namely, the presence of two new signals (at 3675 and 668 cm −1 ). It is also worth noticing that a characteristic band (at 1010 cm −1 ) which can be attributed to the asymmetrical stretching vibrations of Si-O-C and Si-O-Si groups can be observed in the spectrum. The presence of this signal is a direct confirmation that talc has been incorporated into the composite structure. ATR/FTIR Spectra of the Obtained Composites The ATR/FT-IR spectra for the BPA.DM-NVP copolymers with various talc content are presented in Figure 4a,b. Comparison of spectra of the starting material and that of modified composites revealed the most notable changes (which are marked in Figure 4). The main differences are associated with the presence of a strong signal (at approx. 3400 cm −1 ) which corresponds to the -OH groups, bands assigned with the C-H stretching vibrations (asymmetric at approx. 2968 cm −1 and symmetric at 2850 cm −1 ) and bending vibrations of the -CH 3 group (at 1460 and 1435 cm −1 ). Furthermore, there are two distinct signals, which should be highlighted. The first is a sharp band (at 1716 cm −1 ) that can be attributed to the stretching and out-of-plane-bending vibrations of the carbonyl (C=O) group. The second (at 1667 cm −1 ) is associated with the N-C=O stretching vibration originating from the amide group (NVP). The presence of talc contributed to visible changes in the spectra, namely, the presence of two new signals (at 3675 and 668 cm −1 ). It is also worth noticing that a characteristic band (at 1010 cm −1 ) which can be attributed to the asymmetrical stretching vibrations of Si-O-C and Si-O-Si groups can be observed in the spectrum. The presence of this signal is a direct confirmation that talc has been incorporated into the composite structure. SEM-EDX Analysis SEM images of the sample surfaces and the corresponding results of the EDX microanalysis are presented in Figure 5. The area of the tested surface was the same for all samples. The SEM images were obtained using the backscattered electron (BSE) mode. In this mode the images of the sample containing elements with a higher atomic number are mapped to the BSE images as SEM-EDX Analysis SEM images of the sample surfaces and the corresponding results of the EDX microanalysis are presented in Figure 5. SEM-EDX Analysis SEM images of the sample surfaces and the corresponding results of the EDX microanalysis are presented in Figure 5. The area of the tested surface was the same for all samples. The SEM images were obtained using the backscattered electron (BSE) mode. In this mode the images of the sample containing elements with a higher atomic number are mapped to the BSE images as The area of the tested surface was the same for all samples. The SEM images were obtained using the backscattered electron (BSE) mode. In this mode the images of the sample containing elements with a higher atomic number are mapped to the BSE images as brighter. Hence, the talc particles that contain Mg and Si are visible as bright spots in the picture. The presence of talc in the polymer structure is also confirmed by the EDX microanalysis. It can be seen that, apart from the elements C, N and O, Mg and Si are also present in the talc structure. The SEM images and the EDX analysis show that the talc particle size corresponds to the frequency of its appearance on the surface. The greatest number of talc particles is located in the surface layer of the polymer containing the smallest sized talc particles. DSC Analysis In Figure 6 the curves for the samples in the range from 25 to 500 • C are visible. brighter. Hence, the talc particles that contain Mg and Si are visible as bright spots in the picture. The presence of talc in the polymer structure is also confirmed by the EDX microanalysis. It can be seen that, apart from the elements C, N and O, Mg and Si are also present in the talc structure. The SEM images and the EDX analysis show that the talc particle size corresponds to the frequency of its appearance on the surface. The greatest number of talc particles is located in the surface layer of the polymer containing the smallest sized talc particles. DSC Analysis In Figure 6 the curves for the samples in the range from 25 to 500 °C are visible. As one can see for samples BPA.DM-NVP-0-BPA.DM-NVP-2 (see Figure 6a), two small endothermic effects are visible. The first at about 90 • C is associated with evaporation of unreacted NVP, and the second at about 390 • C corresponds to the degradation of the linear part of aliphatic NVP. On the analyzed curves, there is also a large endothermic effect in the range 431-442 • C associated with the total thermal degradation of the samples. For all composites at ca. 150 • C, the exothermic effect, probably related to the crosslinking reaction, is visible. For samples BPA.DM-NVP-3-BPA.DM-NVP-5 (see Figure 6b), two endothermic and one exothermic effects are noticeable. The main endothermic effect at about 445 • C was due to the total thermal degradation of the samples . The addition of talc affects the thermal resistance of the obtained materials positively. The temperature of composites' maximum degradation increases slightly (3-7 • C) but greater homogeneity of the samples is observed (decrease in the endothermic signal at 390 • C). Swelling Studies in Water The samples with talc particle sizes ranging from 8-250 µm were selected for the evaluation of physical and mechanical properties. In order to determine the swelling coefficients (B), samples of the tested material (approx. 0.26 g) were immersed in distilled water for a specific time period (two weeks, as well as with short-term contact i.e., after 15, 60 and 720 min). The corresponding swelling coefficients are listed in Table 2, whereas the initial and final state of the samples are presented in Figure 7. As one can see for samples BPA.DM-NVP-0-BPA .DM-NVP-2 (see Figure 6a), two small endothermic effects are visible. The first at about 90 °C is associated with evaporation of unreacted NVP, and the second at about 390 °C corresponds to the degradation of the linear part of aliphatic NVP. On the analyzed curves, there is also a large endothermic effect in the range 431-442 °C associated with the total thermal degradation of the samples. For all composites at ca. 150 °C, the exothermic effect, probably related to the crosslinking reaction, is visible. For samples BPA.DM-NVP-3-BPA.DM-NVP-5 (see Figure 6b), two endothermic and one exothermic effects are noticeable. The main endothermic effect at about 445 °C was due to the total thermal degradation of the samples . The addition of talc affects the thermal resistance of the obtained materials positively. The temperature of composites' maximum degradation increases slightly (3-7 °C) but greater homogeneity of the samples is observed (decrease in the endothermic signal at 390 °C). Swelling Studies in Water The samples with talc particle sizes ranging from 8-250 µm were selected for the evaluation of physical and mechanical properties. In order to determine the swelling coefficients (B), samples of the tested material (approx. 0.26 g) were immersed in distilled water for a specific time period (two weeks, as well as with short-term contact i.e., after 15, 60 and 720 min). The corresponding swelling coefficients are listed in Table 2, whereas the initial and final state of the samples are presented in Figure 7. Based on the obtained results, it can be concluded that the composites with talc are stable in water. The samples, as presented in Figure 7b, do not change their shape. Moreover, the changes on the composites' surface are visible. After 2 weeks in the environment of water, their swelling coefficients are in the range of 4.2-5.3%. Due to the cross-linking structure the composites' immersion in water does not result in their dissolution. However, these bonds do not inhibit swelling of the cross-linked composites. Figure 7. Photos of the samples after cutting (10 mm × 10 mm) for the swelling measurements: before swelling (a) and after swelling (b) in water (numbers of the sample according to Table 1). Figure 7. Photos of the samples after cutting (10 mm × 10 mm) for the swelling measurements: before swelling (a) and after swelling (b) in water (numbers of the sample according to Table 1). Based on the obtained results, it can be concluded that the composites with talc are stable in water. The samples, as presented in Figure 7b, do not change their shape. Moreover, the changes on the composites' surface are visible. After 2 weeks in the environment of water, their swelling coefficients are in the range of 4.2-5.3%. Due to the cross-linking structure the composites' immersion in water does not result in their dissolution. However, these bonds do not inhibit swelling of the cross-linked composites. Profilometer Analysis The profilometric analyses of the composites shows the significant changes in the surface of the studied materials. The analysis of the arithmetic average roughness R a values confirms the significant differences in the surface structure of the tested material. An increase in roughness directly proportional to the talc size (increase R a from 71.3 to 341.5 nm) is evident (see Figure 8). Profilometer Analysis The profilometric analyses of the composites shows the significant changes in the surface of the studied materials. The analysis of the arithmetic average roughness Ra values confirms the significant differences in the surface structure of the tested material. An increase in roughness directly proportional to the talc size (increase Ra from 71.3 to 341.5 nm) is evident (see Figure 8). Mechanical Properties of Composites The investigations of mechanical properties showed how the filler size affects the strength properties of the tested samples depending on the direction of external excitations. The summary results of the mechanical properties tests are presented in Table 3. The values of stress determined by the uniaxial tension and bending tests as well as that of the Young's modulus describe the elastic properties . Depending on the structure of the composite and the type of external forcing during the tests under uniaxial tension, the value of Young's modulus decreases proportionally to the increasing size of talc particles added into the polymer matrix. However, when tested under bending conditions (see Figure 9b) two clear maxima of the highest values were observed for the samples BPA.DM-NVP-2 and BPA.DM-NVP-3. During bending a complex stress state is induced in the tested sample. At the polymer-filler interface the external forces act with higher intensity in the case of the talc sizes in the range of 15 to 35 µm (BPA.DM-NVP-2 and BPA.DM-NVP-3 samples). For the smallest filler particles (8 µm), due to their aeration effect (e.g., when mixing the filler with monomers), there are weaker filler-polymer interactions in the polymer matrix. In the case of very large talc particles, despite the lack of aeration effect, the mechanical properties decrease along with weakening the polymer network at the mineral-polymer interface (BPA.DM-NVP-5). Mechanical Properties of Composites The investigations of mechanical properties showed how the filler size affects the strength properties of the tested samples depending on the direction of external excitations. The summary results of the mechanical properties tests are presented in Table 3. The values of stress determined by the uniaxial tension and bending tests as well as that of the Young's modulus describe the elastic properties . Depending on the structure of the composite and the type of external forcing during the tests under uniaxial tension, the value of Young's modulus decreases proportionally to the increasing size of talc particles added into the polymer matrix. However, when tested under bending conditions (see Figure 9b) two clear maxima of the highest values were observed for the samples BPA.DM-NVP-2 and BPA.DM-NVP-3. During bending a complex stress state is induced in the tested sample. At the polymer-filler interface the external forces act with higher intensity in the case of the talc sizes in the range of 15 to 35 µm (BPA.DM-NVP-2 and BPA.DM-NVP-3 samples). For the smallest filler particles (8 µm), due to their aeration effect (e.g., when mixing the filler with monomers), there are weaker filler-polymer interactions in the polymer matrix. In the case of very large talc particles, despite the lack of aeration effect, the mechanical properties decrease along with weakening the polymer network at the mineral-polymer interface (BPA.DM-NVP-5). Analyzing the results of the deformation test, it is clear that in the complex state of stress that occurs during bending, the highest values (see Figure 10b) were obtained for the specimens BPA.DM-NVP-2 and BPA.DM-NVP-3. However, in the case of uniaxial stretching where the force acts only in one plane, the smallest elongation was observed for the smallest and the largest values of talc grains (see Figure 9a). Analyzing the results of the deformation test, it is clear that in the complex state of stress that occurs during bending, the highest values (see Figure 10b) were obtained for the specimens BPA.DM-NVP-2 and BPA.DM-NVP-3. However, in the case of uniaxial stretching where the force acts only in one plane, the smallest elongation was observed for the smallest and the largest values of talc grains (see Figure 9a). Flammability Tests The flammability research was carried out in a horizontal burning test. The samples were burning for 60 s (15 s over a burner and then self-burning for 45 s). All samples burned with a bright smokeless flame. In Figures 11 and 12 the images of the selected samples 1 (BPA.DM-NVP-0) and 6 (BPA.DM-NVP-5), respectively, taken using a thermographic camera are visible. The results contained in Table 4 are shown for the temperature measuring range 20-500 • C. The graphs were made using a computer program Vigo System (Ożarów Mazowiecki, Poland). The analysis of the temperature field in the area of the burning sample includes the determination of the changes of the maximum temperature in the whole thermal image (area 1, T 1 ) recorded at 20, 25, 30, 35 and 40 s after the application of the ignition source (see Figures 13 and 14). The temperature along a straight line running through the longitudinal axis of the sample (area 2, T 2 ) was also measured (see Table 4). Flammability Tests The flammability research was carried out in a horizontal burning test. The samples were burning for 60 s (15 s over a burner and then self-burning for 45 s). All samples burned with a bright smokeless flame. In Figures 11 and 12 the images of the selected samples 1 (BPA.DM-NVP-0) and 6 (BPA.DM-NVP-5), respectively, taken using a thermographic camera are visible. The results contained in Table 4 are shown for the temperature measuring range 20-500 °C. The graphs were made using a computer program Vigo System (Ożarów Mazowiecki, Poland). The analysis of the temperature field in the area of the burning sample includes the determination of the changes of the maximum temperature in the whole thermal image (area 1, T1) recorded at 20, 25, 30, 35 and 40 s after the application of the ignition source (see Figures 13 and 14). The temperature along a straight line running through the longitudinal axis of the sample (area 2, T2) was also measured (see Table 4). For all samples with talc, reduction of the initial burning temperature recorded with the camera is observed. The average temperature for sample 1 (BPA.DM-NVP-0) is 248 °C, while for sample 6 (BPA.DM-NVP-5) this is 223 °C. The addition of talc decreases the flame temperature by about 10%. Figure 15 shows the samples after the combustion test. Sample 1 (without talc) burned the fastest. The other materials burned similarly. No large effect of talc particle size on the burning distance was observed, but in comparison with the pure copolymer, the samples with talc maintained their shape. The flammability tests of the materials show clearly that the addition of talc affects their burning behaviour. The BPA.DM-NVP-0 copolymer (without the additives) burned fastest and most intensively. The addition of talc caused a delay in the combustion process and reduced the burning temperature. This effect is best seen the samples with a larger talc particle size. For all samples with talc, reduction of the initial burning temperature recorded with the camera is observed. The average temperature for sample 1 (BPA.DM-NVP-0) is 248 • C, while for sample 6 (BPA.DM-NVP-5) this is 223 • C. The addition of talc decreases the flame temperature by about 10%. Figure 15 shows the samples after the combustion test. Sample 1 (without talc) burned the fastest. The other materials burned similarly. No large effect of talc particle size on the burning distance was observed, but in comparison with the pure copolymer, the samples with talc maintained their shape. The flammability tests of the materials show clearly that the addition of talc affects their burning behaviour. The BPA.DM-NVP-0 copolymer (without the additives) burned fastest and most intensively. The addition of talc caused a delay in the combustion process and reduced the burning temperature. This effect is best seen the samples with a larger talc particle size. Conclusions The UV-polymerization method was successfully used for the synthesis of crosslinked composites based on bisphenol A glycerolate di-methacrylate (BPA.DM), and N-vinyl-2pyrrolidone (NVP). Talc with different particle sizes (≤8, 15, 35, 50, 250, 500 and 710 µm) was used as a filler. The ≤500 and ≤710 µm particles of talc were too heavy to achieve a uniform filler distribution in the composite. Analyzing the change of stress values in relation to the cross-sectional area of the tested samples it is clear that larger particles did not bind with the polymer matrix (BPA.DM-NVP-5). The profilometric tests showed that the surface roughness of the samples correlates directly with the size of the talc particles. In terms of the physicochemical properties of the composites, it was noted that the particle size did not practically affect the swelling of the composites in water. The tensile modulus values of the samples decrease when larger talc particles are used. Under the bending conditions, the highest values were obtained for the composites containing talc particles of ≤15 µm and ≤35 µm. The size of the talc particles influences the burning behaviour of the composites. The addition of talc delayed the combustion process and decreased the combustion temperature by more than 10%. The biggest difference in relation to the polymer matrix was obtained for the composites with particles of ≤250 µm in size. The research proved that the addition of talc can affect the physicochemical parameters of the polymer composites positively while using particles of different sizes, and it is possible to intensify or weaken a given feature.
/** * Shifts the provided {@code val} towards but not past zero. If the absolute value of {@code val} * is less than or equal to shift, zero will be returned. Otherwise, negative {@code val}s will * have {@code shift} added and positive vals will have {@code shift} subtracted. * * <p>If {@code shift} is negative, the result is undefined. This method is the same as {@link * #shiftTowardsZeroWithClipping(double, double)} except that it eliminates the check on {@code * shift} for speed in deep-inner loops. This is a profile/jitwatch-guided optimization. * * <p>Inspired by AdaGradRDA.ISTAHelper from FACTORIE. */ public static double shiftTowardsZeroWithClippingRecklessly(double val, double shift) { if (val > shift) { return val - shift; } else if (val < -shift) { return val + shift; } else { return 0.0; } }
It is known as "security theatre," a suite of frequently invasive measures that provide the appearance of bolstering the safety of travellers, while in fact accomplishing very little. A lavish new production may be about to open in the United States, staged by the creators of such hits as "Take Your Shoes Off At The Airport" and "Wand the Old Lady In the Wheelchair." The Trump administration is reported to be contemplating rules to force visitors arriving at the border from a raft of countries – possibly including even European allies such as France and Germany – to hand over their social media passwords and provide access to the contacts on their phones. Story continues below advertisement Read also: More border resources for migrants is not a solution That would represent a shocking infringement of privacy and liberty, running counter to everything free societies are built upon. Would that the situation was much better on this side of the border. Though Canadian officials say they don't arrest travellers who refuse to provide their phone passwords or submit them to warrantless searches, it is probably in their power under Canadian law to do so. It's a murky legal area the federal government shows little inclination to illuminate. Canadian border agents may also be able to confiscate devices, and deny entry to visitors for refusing access. Canada's border agency operates under interim search guidelines that aren't readily available to the public; the federal Office of the Privacy Commissioner's website describes the search standard as "evidence of contraventions may be found on the digital device or media." Yes, there should be a reduced expectation of privacy at border crossings, but that's awfully broad. By all means, dig into the smartphone of a suspected terrorist or someone believed to be involved in smuggling. But we need a taller evidentiary hurdle than "may be found." Otherwise, every border crossing by a tourist invites a government fishing expedition. Terrorism, and all crime, present risks. But those should be dealt with thoughtfully and proportionately. Story continues below advertisement Story continues below advertisement Instead what's on offer, with the likelihood of more to come, is security theatre. It's getting to the point where border agencies and airport security should consider applying for funding from the Canada Council, or America's National Endowment for the Arts.
package org.springframework.cloud.zookeeper.discovery.watcher.presence; import java.util.Collections; import org.apache.curator.x.discovery.ServiceCache; import org.junit.Assert; import org.junit.Test; import static org.assertj.core.api.BDDAssertions.then; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author <NAME> */ public class DefaultDependencyPresenceOnStartupVerifierTests { private static final String SERVICE_NAME = "service01"; @Test public void should_throw_exception_if_obligatory_dependencies_are_missing() { //given: DefaultDependencyPresenceOnStartupVerifier dependencyVerifier = new DefaultDependencyPresenceOnStartupVerifier(); ServiceCache serviceCache = mock(ServiceCache.class); given(serviceCache.getInstances()).willReturn(Collections.emptyList()); //when: try { dependencyVerifier.verifyDependencyPresence(SERVICE_NAME, serviceCache, true); Assert.fail("Should throw no instances running exception"); } catch (Exception e) { //then: then(e).isInstanceOf(NoInstancesRunningException.class); } } }
/* * Copyright (C) 2013-2021 Canonical, Ltd. * Copyright (C) 2022-2023 Colin Ian King. * * This program 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 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "stress-ng.h" #include "core-builtin.h" #include "core-capabilities.h" #if defined(HAVE_SYS_FSUID_H) #include <sys/fsuid.h> #else UNEXPECTED #endif #if defined(HAVE_GRP_H) #include <grp.h> #else UNEXPECTED #endif #if !defined(_DEFAULT_SOURCE) #define _DEFAULT_SOURCE 1 #endif #if !defined(_BSD_SOURCE) #define _BSD_SOURCE 1 #endif #define GIDS_MAX (1024) typedef struct { shim_rlimit_resource_t id; int ret; struct rlimit rlim; } stress_rlimit_info_t; static stress_rlimit_info_t rlimits[] = { #if defined(RLIMIT_AS) { RLIMIT_AS, 0, { 0, 0 } }, #endif #if defined(RLIMIT_CORE) { RLIMIT_CORE, 0, { 0, 0 } }, #endif #if defined(RLIMIT_CPU) { RLIMIT_CPU, 0, { 0, 0 } }, #endif #if defined(RLIMIT_DATA) { RLIMIT_DATA, 0, { 0, 0 } }, #endif #if defined(RLIMIT_FSIZE) { RLIMIT_FSIZE, 0, { 0, 0 } }, #endif #if defined(RLIMIT_MEMLOCK) { RLIMIT_MEMLOCK, 0, { 0, 0 } }, #endif #if defined(RLIMIT_MSGQUEUE) { RLIMIT_MSGQUEUE, 0, { 0, 0 } }, #endif #if defined(RLIMIT_NICE) { RLIMIT_NICE, 0, { 0, 0 } }, #endif #if defined(RLIMIT_NOFILE) { RLIMIT_NOFILE, 0, { 0, 0 } }, #endif #if defined(RLIMIT_RSS) { RLIMIT_RSS, 0, { 0, 0 } }, #endif #if defined(RLIMIT_RTPRIO) { RLIMIT_RTPRIO, 0, { 0, 0 } }, #endif #if defined(RLIMIT_RTTIME) { RLIMIT_RTTIME, 0, { 0, 0 } }, #endif #if defined(RLIMIT_SIGPENDING) { RLIMIT_SIGPENDING, 0, { 0, 0 } }, #endif #if defined(RLIMIT_STACK) { RLIMIT_STACK, 0, { 0, 0 } }, #endif }; static const stress_help_t help[] = { { NULL, "set N", "start N workers exercising the set*() system calls" }, { NULL, "set-ops N", "stop after N set bogo operations" }, { NULL, NULL, NULL } }; /* * stress on set*() calls * stress system by rapid get*() system calls */ static int stress_set(const stress_args_t *args) { size_t i; int ret_hostname; const size_t hostname_len = stress_hostname_length(); const size_t longname_len = hostname_len << 1; char *hostname; char *longname; #if defined(HAVE_GETPGID) && \ defined(HAVE_SETPGID) const pid_t mypid = getpid(); #endif const bool cap_sys_resource = stress_check_capability(SHIM_CAP_SYS_RESOURCE); #if defined(HAVE_SETREUID) const bool cap_setuid = stress_check_capability(SHIM_CAP_SETUID); #endif #if defined(HAVE_GETPGID) && \ defined(HAVE_SETPGID) const bool cap_root = stress_check_capability(0); #endif for (i = 0; i < SIZEOF_ARRAY(rlimits); i++) { rlimits[i].ret = getrlimit(rlimits[i].id, &rlimits[i].rlim); } hostname = calloc(hostname_len, sizeof(*hostname)); if (!hostname) { pr_inf_skip("%s: cannot allocate hostname array of %zu bytes, skipping stessor\n", args->name, hostname_len); return EXIT_NO_RESOURCE; } longname = calloc(longname_len, sizeof(*hostname)); if (!longname) { pr_inf_skip("%s: cannot allocate longname array of %zu bytes, skipping stessor\n", args->name, longname_len); free(hostname); return EXIT_NO_RESOURCE; } ret_hostname = gethostname(hostname, hostname_len - 1); if (ret_hostname == 0) { hostname[hostname_len - 1] = '\0'; (void)shim_strlcpy(longname, hostname, longname_len); } stress_set_proc_state(args->name, STRESS_STATE_RUN); do { int ret; gid_t gid; uid_t uid; #if defined(HAVE_SETREUID) uid_t bad_uid; #else UNEXPECTED #endif struct rlimit rlim; /* setsid will fail, ignore return */ VOID_RET(pid_t, setsid()); if (!stress_continue(args)) break; /* getgid always succeeds */ gid = getgid(); VOID_RET(int, setgid(gid)); if (!stress_continue(args)) break; if (*longname) { VOID_RET(int, sethostname(longname, longname_len)); VOID_RET(int, sethostname(hostname, strlen(hostname))); } #if defined(HAVE_GETPGID) && \ defined(HAVE_SETPGID) { pid_t pid; pid = getpgid(mypid); if (pid != -1) { if (!cap_root) { const pid_t bad_pid = stress_get_unused_pid_racy(false); /* Exercise invalid pgid */ VOID_RET(int, setpgid(mypid, bad_pid)); /* Exercise invalid pid */ VOID_RET(int, setpgid(bad_pid, pid)); /* Exercise invalid pid and pgid */ VOID_RET(int, setpgid(bad_pid, bad_pid)); } VOID_RET(int, setpgid(mypid, pid)); if (!stress_continue(args)) break; } } #else UNEXPECTED #endif #if defined(HAVE_SETTIMEOFDAY) if (!stress_check_capability(SHIM_CAP_SYS_TIME)) { struct timeval tv; struct timezone tz; /* We should not be able to set the time of day */ ret = gettimeofday(&tv, &tz); if (ret == 0) { ret = settimeofday(&tv, &tz); if (ret != -EPERM) { pr_fail("%s: settimeofday failed, did not have privilege to " "set time, expected -EPERM, instead got errno=%d (%s)\n", args->name, errno, strerror(errno)); } /* * exercise bogus times west tz, possibly undefined behaviour but * on Linux anything +/- 15*60 is -EINVAL */ tz.tz_minuteswest = 36 * 60; VOID_RET(int, settimeofday(&tv, &tz)); } } #else UNEXPECTED #endif #if defined(HAVE_GETPGRP) && \ defined(HAVE_SETPGRP) { pid_t pid; /* getpgrp always succeeds */ pid = getpgrp(); if (pid != -1) { VOID_RET(int, setpgrp()); if (!stress_continue(args)) break; } } #else UNEXPECTED #endif /* getuid always succeeds */ uid = getuid(); VOID_RET(int, setuid(uid)); if (!stress_continue(args)) break; #if defined(HAVE_GRP_H) ret = getgroups(0, NULL); if (ret > 0) { gid_t groups[GIDS_MAX]; int n; (void)shim_memset(groups, 0, sizeof(groups)); ret = STRESS_MINIMUM(ret, (int)SIZEOF_ARRAY(groups)); n = getgroups(ret, groups); if (n > 0) { const gid_t bad_groups[1] = { (gid_t)-1 }; /* Exercise invalid groups */ VOID_RET(int, shim_setgroups(INT_MIN, groups)); VOID_RET(int, shim_setgroups(0, groups)); VOID_RET(int, shim_setgroups(1, bad_groups)); VOID_RET(int, shim_setgroups(n, groups)); } } #else UNEXPECTED #endif #if defined(HAVE_SETREUID) VOID_RET(int, setreuid((uid_t)-1, (uid_t)-1)); /* * Validate setreuid syscalls exercised to increase the current * ruid and euid without CAP_SETUID capability cannot succeed */ if ((!cap_setuid) && (stress_get_unused_uid(&bad_uid) >= 0)) { if (setreuid(bad_uid, bad_uid) == 0) { pr_fail("%s: setreuid failed, did not have privilege to set " "ruid and euid, expected -EPERM, instead got errno=%d (%s)\n", args->name, errno, strerror(errno)); } } #else UNEXPECTED #endif #if defined(HAVE_SETREGID) #if defined(HAVE_GETRESGID) { gid_t rgid = (gid_t)-1; gid_t egid = (gid_t)-1; gid_t sgid = (gid_t)-1; ret = getresgid(&rgid, &egid, &sgid); if (ret == 0) { VOID_RET(int, setregid(rgid, egid)); VOID_RET(int, setregid((gid_t)-1, egid)); VOID_RET(int, setregid(rgid, (gid_t)-1)); if (geteuid() != 0) { VOID_RET(int, setregid((gid_t)-2, egid)); VOID_RET(int, setregid(rgid, (gid_t)-2)); } } } #else UNEXPECTED #endif VOID_RET(int, setregid((gid_t)-1, (gid_t)-1)); #else UNEXPECTED #endif #if defined(HAVE_SETRESUID) #if defined(HAVE_GETRESUID) { uid_t ruid = (uid_t)-1; uid_t euid = (uid_t)-1; uid_t suid = (uid_t)-1; ret = getresuid(&ruid, &euid, &suid); if (ret == 0) { VOID_RET(int, setresuid(ruid, euid, suid)); VOID_RET(int, setresuid(ruid, euid, (uid_t)-1)); VOID_RET(int, setresuid(ruid, (uid_t)-1, suid)); VOID_RET(int, setresuid(ruid, (uid_t)-1, (uid_t)-1)); VOID_RET(int, setresuid((uid_t)-1, euid, suid)); VOID_RET(int, setresuid((uid_t)-1, euid, (uid_t)-1)); VOID_RET(int, setresuid((uid_t)-1, (uid_t)-1, suid)); if (geteuid() != 0) { VOID_RET(int, setresuid((uid_t)-2, euid, suid)); VOID_RET(int, setresuid(ruid, (uid_t)-2, suid)); VOID_RET(int, setresuid(ruid, euid, (uid_t)-2)); } VOID_RET(int, setresuid(ruid, euid, suid)); } } #else UNEXPECTED #endif VOID_RET(int, setresuid((uid_t)-1, (uid_t)-1, (uid_t)-1)); #else UNEXPECTED #endif #if defined(HAVE_SETRESGID) #if defined(HAVE_GETRESGID) { gid_t rgid = (gid_t)-1; gid_t egid = (gid_t)-1; gid_t sgid = (gid_t)-1; ret = getresgid(&rgid, &egid, &sgid); if (ret == 0) { VOID_RET(int, setresgid(rgid, egid, sgid)); VOID_RET(int, setresgid(rgid, egid, (gid_t)-1)); VOID_RET(int, setresgid(rgid, (gid_t)-1, sgid)); VOID_RET(int, setresgid(rgid, (gid_t)-1, (gid_t)-1)); VOID_RET(int, setresgid((gid_t)-1, egid, sgid)); VOID_RET(int, setresgid((gid_t)-1, egid, (gid_t)-1)); VOID_RET(int, setresgid((gid_t)-1, (gid_t)-1, sgid)); if (geteuid() != 0) { VOID_RET(int, setresgid((gid_t)-2, egid, sgid)); VOID_RET(int, setresgid(rgid, (gid_t)-2, sgid)); VOID_RET(int, setresgid(rgid, egid, (gid_t)-2)); } VOID_RET(int, setresgid(rgid, egid, sgid)); } } #else UNEXPECTED #endif VOID_RET(int, setresgid((gid_t)-1, (gid_t)-1, (gid_t)-1)); #else UNEXPECTED #endif #if defined(HAVE_SETFSGID) && \ defined(HAVE_SYS_FSUID_H) { int fsgid; /* Passing -1 will return the current fsgid */ fsgid = setfsgid((uid_t)-1); if (fsgid >= 0) { /* Set the current fsgid, should work */ ret = setfsgid((uid_t)fsgid); if (ret == fsgid) { /* * we can try changing it to * something else knowing it can * be restored successfully */ VOID_RET(int, setfsgid(gid)); VOID_RET(int, setfsgid((uid_t)getegid())); /* And restore */ VOID_RET(int, setfsgid((uid_t)fsgid)); } } } #else UNEXPECTED #endif #if defined(HAVE_SETFSUID) && \ defined(HAVE_SYS_FSUID_H) { int fsuid; /* Passing -1 will return the current fsuid */ fsuid = setfsuid((uid_t)-1); if (fsuid >= 0) { /* Set the current fsuid, should work */ ret = setfsuid((uid_t)fsuid); if (ret == fsuid) { /* * we can try changing it to * something else knowing it can * be restored successfully */ VOID_RET(int, setfsuid(uid)); VOID_RET(int, setfsuid((uid_t)geteuid())); /* And restore */ VOID_RET(int, setfsuid((uid_t)fsuid)); } } } #else UNEXPECTED #endif #if defined(__NR_sgetmask) && \ defined(__NR_ssetmask) { long mask; mask = shim_sgetmask(); shim_ssetmask(mask); } #endif #if defined(HAVE_GETDOMAINNAME) && \ defined(HAVE_SETDOMAINNAME) { char name[2048]; ret = shim_getdomainname(name, sizeof(name)); if (ret == 0) { /* Exercise zero length name (OK-ish) */ VOID_RET(int, shim_setdomainname(name, 0)); /* Exercise long name (-EINVAL) */ VOID_RET(int, shim_setdomainname(name, sizeof(name))); /* Set name back */ VOID_RET(int, shim_setdomainname(name, strlen(name))); } if (!stress_continue(args)) break; } #else UNEXPECTED #endif /* * Invalid setrlimit syscall with invalid * resource attribute resulting in EINVAL error */ (void)shim_memset(&rlim, 0, sizeof(rlim)); if ((getrlimit((shim_rlimit_resource_t)INT_MAX, &rlim) < 0) && (errno == EINVAL)) { (void)setrlimit((shim_rlimit_resource_t)INT_MAX, &rlim); } for (i = 0; i < SIZEOF_ARRAY(rlimits); i++) { if (rlimits[i].ret == 0) { /* Bogus setrlimit syscall with invalid rlim attribute */ rlim.rlim_cur = rlimits[i].rlim.rlim_cur; if (rlim.rlim_cur > 1) { rlim.rlim_max = rlim.rlim_cur - 1; (void)setrlimit(rlimits[i].id, &rlim); } /* Valid setrlimit syscall and ignoring failure */ (void)setrlimit(rlimits[i].id, &rlimits[i].rlim); } } /* * Invalid setrlimit syscalls exercised * to increase the current hard limit * without CAP_SYS_RESOURCE capability */ if (!cap_sys_resource) { for (i = 0; i < SIZEOF_ARRAY(rlimits); i++) { if ((rlimits[i].ret == 0) && (rlimits[i].rlim.rlim_max < RLIM_INFINITY)) { rlim.rlim_cur = rlimits[i].rlim.rlim_cur; rlim.rlim_max = RLIM_INFINITY; ret = setrlimit(rlimits[i].id, &rlim); if (ret != -EPERM) { pr_fail("%s: setrlimit failed, did not have privilege to set " "hard limit, expected -EPERM, instead got errno=%d (%s)\n", args->name, errno, strerror(errno)); } if (ret == 0) { (void)setrlimit(rlimits[i].id, &rlimits[i].rlim); } } } } { /* * Exercise stime if it is available and * ignore CAP_SYS_TIME requirement to call * it. Exercise this just once as constantly * setting the time may cause excessive * time drift. */ time_t t; static bool test_stime = true; if (test_stime && (time(&t) != ((time_t)-1))) { VOID_RET(int, shim_stime(&t)); test_stime = false; } } stress_bogo_inc(args); } while (stress_continue(args)); stress_set_proc_state(args->name, STRESS_STATE_DEINIT); free(longname); free(hostname); return EXIT_SUCCESS; } stressor_info_t stress_set_info = { .stressor = stress_set, .class = CLASS_OS, .verify = VERIFY_ALWAYS, .help = help };
<reponame>brandonkal/expect /** * check function is promise instance * * @param v * @returns */ export function isPromise(v: any): v is Promise<any> { if ( typeof v === "object" && typeof v.then === "function" && typeof v.catch === "function" ) { return true; } return false; }
// Copyright 2019 <NAME> (Falcons) // SPDX-License-Identifier: Apache-2.0 /* * stoppedController.hpp * * Created on: Jan 9, 2019 * Author: <NAME> */ #ifndef STOPPEDCONTROLLER_HPP_ #define STOPPEDCONTROLLER_HPP_ #include "boost/signals2.hpp" #include "abstractGameDataAdapter.hpp" #include "abstractRefBoxAdapter.hpp" #include "arbiterGameData.hpp" #include "judgement.hpp" class StoppedController { public: typedef boost::signals2::signal<void ()> signal_t; boost::signals2::connection preparingSignalSubscribe (const signal_t::slot_type&); /* Control a game in 'stopped' state. In this state, the controller shall execute * given judgement. The only possible transition in this state is towards the * 'preparing' state. This transition must eventually be taken. * * If and only if the controller declares the game preparing, it must raise the * preparing signal before it returns from the control method. */ void control (const ArbiterGameData&); private: void declareGamePreparing(); signal_t _preparingSignal; bool _signalSent; }; #endif /* STOPPEDCONTROLLER_HPP_ */
The roles of stress, coping, and parental support in adolescent psychological well-being in the context of COVID-19: A daily-diary study Background COVID-19 has introduced novel stressors into American adolescents’ lives. Studies have shown that adolescents adopt an array of coping mechanisms and social supports when contending with stress. It is unclear, though, which strategies are most effective in mitigating daily pandemic-related stress, as few micro-longitudinal studies have explored adolescents’ daily affect during COVID-19. Parental support may also be a critical component of adolescents’ pandemic-related coping, as adolescents’ peer networks have been limited by public health measures. Methods This longitudinal study examined links between stress, coping, parental support, and affect across 14 consecutive days and 6216 assessments from a national sample of adolescents (N=444; Mage=15.0; 60% female; 44% Black/African American, 39% White/Europen American, 9% Latinx, 6% Asian American, 2% Native American) during school closures and state-mandated stay-at-home orders between April 8 and April 21, 2021. Results Adolescents’ health and financial stress predicted increases in same-day (health stress’ effect size = .16; financial stress’ effect size = .11) and next-day negative affect (health stress’ effect size = .05; financial stress’ effect size = .08). Adolescents’ secondary control engagement coping predicted increases in same-day (effect size = .10) and next-day (effect size = .04) positive affect and moderated the link between health stress and negative affect. Parental social support predicted increases in same-day (effect size = .26) and next-day (effect size = .06) positive affect and decreases in same-day (effect size = .17) negative affect and moderated the link between financial stress and negative affect. Limitations Results are indicative of conditions at the immediate onset of COVID-19 and should be interpreted as such. Conclusions Findings provide information as to how health providers and parents can help adolescents mitigate the impact of COVID-19-related health and economic stressors on their psychological well-being. It remains critical to monitor the psychosocial impact of the pandemic on adolescents’ affect while continuing to identify personal and environmental protective factors for reducing harm and maximizing resilience. Introduction Stress during adolescence is a normative developmental phenomenon (Shankar and Park, 2016;Wang, M.-T., Degol, J. L., & Henry, D. A. 2020); however, during the COVID-19 pandemic, adolescents experienced circumstances that may have exacerbated these naturally occurring stressors, such as loss of education time, restricted access to peers, and disruption of daily routines (Fegert et al., 2020). Not only are these adolescents experiencing intensified versions of "typical" stressors, but they also have been impacted by pandemic-related concerns about infection, quarantine, and economic stability, all of which have been linked to feelings of ongoing, unavoidable stress (Brooks et al., 2020;Polizzi et al., 2020;Wang, M.-T., Scanlon, C. L., Hua, M., & Del Toro, J. 2021). As such, adolescents' daily coping and the extent to which they receive social support from parents during this challenging time may have consequences for their psychological well-being (Cicchetti and Rogosch, 2002;Luthar and Brown, 2007). Studies have shown that adolescents adopt a wide array of coping mechanisms when contending with stress (Compas et al., 2017;Skinner and Zimmer-Gembeck, 2007). For instance, some adolescents tend to use coping strategies that directly impact a situation; others may use strategies aimed at adapting to a challenging situation; still others may opt to avoid the stressor completely (Connor-Smith et al., 2000). While extant literature has supported the typology of these coping strategies, it is unclear which strategies are most effective in mitigating daily pandemic-related stress. Moreover, adolescents often rely on their social networks-including their parents-to provide support during times of crisis (Cook et al., 2016;Kolak et al., 2018;McMahon et al., 2020;Wang, M.-T. & Eccles, J. S. 2012). Parental social support in the time of COVID-19 may be a critical component of positive adolescent adjustment, as adolescents' peer networks were limited by stay-at-home orders. Thus, it is imperative to understand adolescents' daily experiences of pandemic-related stress and which coping strategies and supports buffer against the effect of stress on psychological well-being. In this study, we used a daily-diary approach to examine the longitudinal links of COVID-related stress, coping strategies, and parental support with adolescents' daily affect at the onset of a global pandemic. We also investigated the mitigating role of coping strategies and parental support in the link between stress and adolescents' affect. The 14-day micro-longitudinal design along with a nationwide American sample provide a novel insight into real-time adolescent stress and adjustment during a pandemic. Theoretical and empirical rationale Drawing from the strength-based ecological framework of risk and resilience, we aim to understand the context of stress surrounding American adolescents during the COVID-19 pandemic and identify ways to promote psychological wellness (Cowen, 1994). According to Kirby and Fraser (1997), an individual's overall well-being is closely linked to their daily experiences of risk and protective factors. Risk factors refer to situations or circumstances that increase maladjustment, such as daily stress, a hostile parent-child relationship, or maladaptive coping. Risk factors present adolescents with adversities that impede their ability to fulfill needs, acquire competencies, and form relationships with others (Sandler, 2001), thereby raising the likelihood of maladaptive functioning (Cicchetti and Rogosch, 2002). Conversely, protective factors are internal or external resources (e.g., adaptive coping skills or social support, respectively) that not only lead to increased well-being but also buffer against the nefarious effects of risk factors. It is posited that these protective factors contribute to resilience-an individual's capacity to endure, persist, and triumph despite stressful circumstances (Corcoran and Nichols-Casebolt, 2004;Luthar and Brown, 2007). Adolescent stress and psychosocial well-being We focused on health and financial stressors since these stressors have been prominently featured in extant literature addressing COVID-19 (e.g., Polizzi et al. 2020) and adolescents are limited in their ability to directly change circumstances contributing to their pandemic-related health and financial worries. Pandemic-related health stress The potential for COVID-19 infection and death confronted adolescents with stressors related to their own and loved ones' well-being. Polizzi et al. (2020) warned against impending health-related stressors during the nascent stages of the COVID-19 outbreak, cautioning that individuals may start worrying about their own and others' risk of infection or death. In addition, news media were saturated with infection and mortality rates, and fear of interacting with COVID-19-infected individuals has been documented (Lin, 2020;Polizzi et al., 2020). Consequently, COVID-19's pandemic nature likely exacerbated fear and worry that resulted in stigmatization and anxiety (Guan et al., 2020). Scholars have shown that pandemics are tied to helplessness and hopelessness (Polizzi et al., 2020) as well as to loneliness and social isolation (Loades et al., 2020), all of which are hallmark emotions associated with affective disorders. For adolescents, worry over losing a loved one and the actual loss of a loved one have been connected to significant mental health problems (Stikkelbroek et al., 2016). Hence, pandemic-related stress over the potential infection and death of loved ones may put adolescents at risk for affective maladjustment. Pandemic-related financial stress With more than 44.2 million Americans filing for unemployment during the first 2.5 months of the COVID-19 pandemic (Lambert, 2020) and the closing of schools abruptly challenging food security for many children dependent on government-subsidized meals (Van Lancker and Parolin, 2020), COVID-19 drastically increased financial stressors faced by adolescents and their families (Prime et al., 2020). Researchers have long understood that financial stress deleteriously depletes the cognitive, social, and emotional resources available for coping with other life stressors (Wadsworth, 2015). In adolescents, financial stress has been associated with a higher likelihood of poor mental health (Arbel et al., 2018;Schneider et al., 2015). For instance, Santiago and colleagues (2011) found that elevated financial stress was associated with increased anxiety, depression, and attention difficulties. Because Americans are generally unprepared for even a minor financial emergency (McGrath, 2016), many adolescents may have experienced heightened economic stress surrounding the potential for or actuality of their parents losing their job and the ability to obtain basic needs during COVID-19. Coping and adolescent affect The Responses to Stress Model identifies coping as a buffer in the relation between stress and adjustment while also distinguishing between engagement/approach coping and disengagement/avoidance coping (Connor-Smith et al., 2000). On the one hand, engagement coping is composed of primary and secondary control coping. Primary control engagement coping involves altering a stressor or one's response to a stressor by using strategies such as problem solving, emotional expression, and emotion regulation. Secondary control engagement coping encompasses adapting to a stressor through acceptance, cognitive restructuring, positive thinking, or distraction. On the other hand, disengagement coping encompasses behavioral, affective, and cognitive avoidance. Compas et al. (2017) concluded that both primary and secondary control engagement coping were associated with adaptive psychological well-being, including heightened positive affect and lowered negative affect. Both types of coping have been linked to better psychological functioning in the context of poverty-related and traumatic stress . Conversely, adolescents using disengagement strategies (e.g., avoidance, denial, and wishful thinking) as a means of coping with stress have a higher risk of experiencing emotional maladjustment (Compas et al., 2017). Yet, it is noteworthy that certain types of coping strategies may operate differentially on adolescents' affect pending the duration and intensity of stress. For instance, Jensen et al. (2013) found that although problem solving (i.e., primary control engagement coping) was often the go-to coping strategy for many adolescents, distraction (i.e., secondary control engagement coping) and avoidance (i.e., disengagement coping) were the most widely used adolescent coping strategies when faced with life-threatening situations. Since the context of stress surrounding the novel coronavirus has been ongoing and unavoidable, coping via disengagement strategies (e.g., situation avoidance) may not be possible. Conversely, acceptance, distraction, cognitive restructuring, and/or optimistic thinking (i.e., secondary control engagement coping) may provide immediate relief from intense stressors (Sheppes and Gross, 2011). Parental support and adolescent affect Parental support has been identified as one of the most effective protective factors during uncontrollably high periods of stress (Rodriguez-Llanes et al., 2013). Since adolescents were likely spending more time at home due to stay-at-home orders, the role of parental social support may be especially critical for their children's psychological well-being during the pandemic (Pfefferbaum et al., 2014). Indeed, family cohesion and parental emotional support have been connected to positive affect throughout adolescence, and secure parent-child relationships have been found to buffer against the effects of stress during challenging times (Cook et al., 2016;Kolak et al., 2018;McMahon et al., 2020). Prosocial relationships with parents have also been linked to resilience in the face of adversity (Luthar, 2006), and researchers have established that parental social support has a direct positive effect on adolescents' affect, especially following exposure to mass trauma (Dimitry, 2012;Kronenberg et al., 2010). The current study Despite the psychological consequences associated with pandemicrelated public health measures (Brooks et al., 2020), most studies examining the impact of pandemics have focused on medical personnel or other adults. Even fewer longitudinal studies have examined the effect of pandemic-related stress on adolescents' daily affect, leaving much to be learned about adolescents' daily responses to stress during pandemics. To capture adolescents' daily stress, coping, parental support, and affect at the onset of the pandemic, we examined a nationwide sample using daily-diary approaches across 14 days. Our study was uniquely situated in the context of a burgeoning pandemic and can provide an intensive view into adolescents' everyday experiences and behaviors as they unfold in real time. Moreover, the daily-diary approach minimized systematic recall bias and examined within-person processes and variability in these processes over time (Bolger et al., 2003). In this study, we investigated (a) same-and next-day links between pandemic-related health and financial stress and adolescents' affect, (b) same-and next-day links between coping strategies and parental support and adolescents' affect, and (c) the moderating effect of coping strategies and parental support on the link between adolescents' stress and their affect. We hypothesized that higher levels of health and financial stress would be positively correlated with negative affect. Moreover, we expected that secondary control engagement coping and parental support would link to increased positive affect and decreased negative affect. Finally, we anticipated that the link between stress and affect would vary by adolescents' secondary control engagement coping or parental support, though we refrained from specific hypotheses regarding the strength and pattern of moderation effects due to a limited literature base. Participants This study used data from an ongoing nationwide longitudinal study examining school experiences, family functioning, and adolescent wellbeing in the United States. The original study recruited a national sample of adolescents by using a representative, random sampling method. When COVID-19 was declared a national emergency in the United States in March 2020, the original longitudinal study was leveraged by inviting a subsample of adolescent participants to participate in a 14-day daily-diary study focusing on adolescents' stress and adjustment during the pandemic. As a condition of participation, participants' state governments had to have issued stay-at-home orders that mandated schools and nonessential businesses to close. Approximately 79% of the qualified participants from the original study agreed to participate in the daily-diary study. The final sample included 444 adolescents aged 13-18 from 38 states (M age = 15.0; 40% male; 44% Black/African American, 39% White/Europen American, 9% Latinx, 6% Asian American, 2% Native American; 62% with incomes below 130% of the poverty level). This subsample differed by sociodemographic characteristics from the original sample in only one way: It had more participants from the Northeast and South regions (vs. West and Midwest) as compared to the original study sample (see Table 1). The higher number of participants from the Northeast and South regions was attributed to the fact that more states in these regions implemented stayat-home orders during the study. Procedures At the time of data collection, all schools and nonessential businesses within the participants' home states were closed to facilitate social distancing. All consented adolescents and their parents first completed baseline measures and provided demographic information. All adolescents then completed daily-diary assessments between 5:00 pm and 12:00 am using their cellphones, tablets, or computers across 14 consecutive days from April 8 to April 21, 2021. Participants received two to four reminders to complete the daily diary via email or text message each day. Parents received $20 for completing the baseline survey, and adolescents received $40 for completing the baseline survey and daily-diary entries. All materials and procedures were approved by the authors' university institutional review board. Daily affect Adolescents' positive and negative affect were measured daily using the Positive and Negative Affect Scale for Children (PANAS-C), a wellvalidated psychological scale (Laurent et al., 1999). We assessed positive affect with four items (e.g., grateful, energetic, happy, hopeful) and negative affect with six items (e.g., sad, anxious, depressed). Adolescents reported their mood during the past 24 h on a 5-point scale from 1 (not at all) to 5 (extremely). Items were averaged together to form daily composite scores of positive affect (R C = .82) and negative affect (R C = .87). Daily stress We assessed daily stress using a modified version of the Multicultural Events Schedule for Adolescents (Gonzales et al., 2001). Adolescents were asked how stressful they found these occurring events and rated the stressfulness of health and financial stressors over the past 24 h on a 4-point scale ranging from 1 (not at all) to 4 (a lot). Items regarding health stressors (six items; e.g., being infected by coronavirus disease; your family members being infected by coronavirus disease) and financial stressors (three items; e.g., not having enough food to eat; not having money to buy basic necessities) were averaged together to form daily composite scores (health stress: R C = .91; financial stress: R C = .76). Daily coping We measured adolescents' daily coping using an abbreviated version of the Response to Stress Questionnaire (Connor-Smith et al., 2000). Adolescents were asked whether they did these things (i.e., different strategies) to make themselves feel good or help themselves to deal with some concern or worries. Engagement coping was assessed by 10 items measuring primary (e.g., "I tried some possible ways to solve the problem/concern") and secondary (e.g., "I looked at the bright side of the problem"; "I keep my mind off the problem by exercising, listening to music, etc.") control coping responses. Disengagement coping was measured by three items (e.g., "I avoided thinking about the problem/concern"). Adolescents rated each item on a 4-point scale ranging from 1 (not at all) to 4 (a lot). Due to the skewed nature of daily coping, the items were recoded into binary indicators (0 = no, 1 = yes) and summed together to form daily composite scores of primary control coping (R C = .87), secondary control coping (R C = .77), and disengagement coping (R C = .68). Confirmatory factor analyses were conducted to verify that these three coping constructs were related but distinct constructs. Daily parental support We measured the extent to which adolescents positively interacted with parents and received social support from them each day with items from the Network of Relationship Inventory (e.g., "I felt socially supported by my parent"; "I did something fun or relaxing with my parent"; Furman and Buhrmester, 2009). The items had a 5-point response scale ranging from 1 (not at all) to 5 (a lot; R C = .79). Covariates Due to their associations with adolescents' stress, coping, and affect, we accounted for several sociodemographic and pandemic-specific covariates. We included the numerical day of reporting (1-14) and weekend (0 = weekday, 1 = weekend) as time-level covariates. Six childlevel covariates were collected from child reports or parent reports: (a) adolescents' age, (b) sex, (c) race, (d) federal poverty level as a proxy of socioeconomic status (e.g., household incomes below 130 percent of the poverty level), (e) adolescents' emotion regulation, and (f) whether parents experienced job loss during the COVID-19 pandemic. As our participants lived across the United States, we included pandemic-related covariates regarding the type of community (i.e., urban, suburban, and rural) and localized severity of COVID-19 (i.e., publicly available infection cases for each participant's specific county) to contextualize our results within COVID-19. Finally, we included adolescents' average levels of positive and negative affect in early March of 2020 (i.e., before the pandemic). The inclusion of pre-pandemic affective outcomes allowed us to capture the change in adolescents' affect possibly due to the pandemic. Analytic plan This study examined how adolescents' stress, coping, and parental support predicted their affect using longitudinal multilevel modeling in Mplus with daily observations (Level 1) nested within participants (Level 2). The outcomes of interest were same-and next-day affect at Level 1. Level 1 key predictors included stress, coping, and parental support. At Level 2, we explained the variation in adolescents' average level of affect over time by including child-level covariates. All Level 1 predictors were group mean centered at the individual level. The main effects of stress, coping, and parental support on affect were tested first, and interactions between stress-coping and stress-parental support were tested sequentially. The intraclass correlation (days within person) indicated that approximately 70% of the outcome variance was at the person level (positive affect: 66%; negative affect: 69%), whereas ~30% was at the daily level (positive affect: 34%; negative affect: 31%), thus justifying the use of a multilevel modeling approach. Missing data The amount of missing data at both the daily and person levels was low. Of the possible 6,216 daily assessments (14 days, 444 adolescents), there were only 7.4% missing data at the daily level (n = 462 missing daily assessments) due to missing or partially completed daily diaries. There were also varying levels of missing data at the child level: 100% of adolescents and parents completed the baseline and demographic surveys; 66% of adolescents did not miss any daily-diary entries; 22% missed 1 or 2 daily entries; and 6% missed 3,4 daily entries. On average, adolescents completed 13 out of 14 daily-diary entries. Little's missing completely at random test suggested that the data were missing completely at random, χ 2 (14) = 9.51, p = ns. An examination of missing data patterns indicated that adolescents with complete data did not differ from those with missing data on key constructs or demographic characteristics. To retain all adolescents in the analyses, we accounted for missing data through full-information maximum likelihood estimation. Descriptive statistics Over the 14 days of daily data collection, 423 adolescents (95.3% of the participants) reported health stress on more than one day, and 3876 days (62% of the total days) included adolescent reports of health stress. In addition, 377 adolescents (85% of the participants) reported financial stress on more than one day, and 3,098 days (50% of the total days) included reports of financial stress. Table 2 presents means, standard deviations, and correlations among all study constructs. As shown in Model 3, Table 3, two significant interaction effects emerged for same-day negative affect: The association between stress and negative affect varied based on secondary control engagement coping (B = .05, SE = .02, p < .05, 95% CI , ES = .05) and parental support (B = .06, SE = .03, p < .05, 95% CI , ES = .05). We plotted the interaction at high (Mean + 1 SD) and low (Mean -1 SD) levels of each variable. Secondary control engagement coping moderated the link between health stress and negative affect (see Fig. 1a): On days when health stress was low and secondary control engagement coping was high, adolescents experienced less negative affect (B = .13, t = .28). In contrast, adolescents experienced higher negative affect (B = .22, t = .42) when they had high health stress and high secondary control engagement coping. Moreover, parental support buffered against the effect of financial stress on negative affect, regardless of adolescents' stress level (see Fig. 1b; low parental support: B = .18, t = .29; high parental support: B = .07, t = .45). Same-day effect on positive affect As shown in Table 4, health and financial stress were not related to same-day positive affect (health stress: B = .02, SE = .04, p = ns, 95% CI Table 2 Descriptive statistics (means, standard deviations, and zero-order bivariate correlations) for all study constructs. Discussion Amidst COVID-19's stay-at-home orders and mandated school closures, American adolescents were thrust into developmentally challenging circumstances (Wang et al., in press). In this study, we identified how pandemic-related stressors, potential coping mechanisms, and Fig. 1. Moderation effects (a). The moderation effect of secondary control engagement coping on the same-day link between adolescents' health stress and negative affect (b). The moderation effect of parental support on the same-day link between adolescents' financial stress and negative affect (c). The moderation effect of secondary control engagement coping on the next-day link between adolescents' health stress and negative affect. parental support link to adolescents' daily positive and negative affect. Using a daily-diary approach with a nationwide American sample, we found that adolescents' health and financial stress predicted same-and next-day increases in negative affect. Furthermore, adolescents' secondary control engagement coping not only predicted same-and next-day increases in positive affect, but it also moderated the link between health stress and negative affect. Parental support predicted increases in adolescents' same-and next-day positive affect and decreases in same-day negative affect. Parental support also moderated the link between financial stress and negative affect. Pandemic-related stress and adolescent affect Pervasive health and financial stress were linked to same-and nextday increases in adolescents' negative affect. These results were unsurprising, as the presence of both health-related and financial stressors creates a context of unavoidable and unpredictable pandemic-related stress. With the United States leading the world in COVID-19 infection and death rates, adolescents were faced with the very real possibility of losing a loved one, an occurrence that has been linked to significant mental health deficits (Stikkelbroek et al., 2016). Moreover, the contagion of pandemics often requires public health measures that necessarily impact the national economy. Indeed, millions of Americans lost their jobs during the COVID-19 pandemic (Lambert, 2020). Hence, the health and financial stressors associated with the pandemic are inextricably intertwined, salient risk factors that threaten adolescents' daily affect. Coping and adolescent affect In alignment with literature supporting the benefits of engagement coping on adolescent functioning (Compas et al., 2017), secondary control engagement coping-such as positive thinking, cognitive restructuring, acceptance, and distraction-was linked to same-and next-day increases in positive affect, indicating both immediate and sustained benefits. In addition, neither primary control engagement coping strategies (e.g., problem solving, emotional expression and regulation) nor disengagement coping strategies (e.g., denial, avoidance, and wishful thinking) predicted adolescents' positive or negative affect in this study. Why, then, were secondary control engagement coping strategies effective while other coping strategies were not? Primary control engagement coping strategies depend on an individual's ability to control certain aspects of or responses to a given stressor, whereas disengagement responses assume that the stressor and its associated stress are avoidable (Compas et al., 2017;Connor-Smith et al., 2000). However, in the context of a pandemic, health and financial stressors are, in large part, out of adolescents' control and unavoidable. Thus, coping mechanisms reliant on primary control or disengagement may be less likely to evoke positive affect than those that emphasize adaptation and accommodation. Indeed, perceived controllability over stressors has been found to positively influence adolescents' likelihood of using adaptive coping strategies (Zimmer-Gembeck et al., 2016). In light of this information, parents and practitioners who work with adolescents contending with pandemic-related stress may encourage the use of secondary control engagement coping strategies-such as distraction (e.g., exercising, reading, helping others) and optimistic thinking-so as to promote positive affect among adolescents. Furthermore, the buffering role of secondary control engagement coping in pandemic-related health stress was stronger when that stress was low; yet, as health stress increased, this buffering effect diminished. There may be differences in short-and long-term coping regarding both type and efficacy (Jensen et al., 2013;Sheppes and Gross, 2011). For example, secondary control engagement coping has been found to not only be the preferred (Jensen et al., 2013) but also the most efficacious coping mechanisms for handling short-term periods of intense stress (Sheppes and Gross, 2011). It follows, then, that as stress levels fluctuate throughout the course of the pandemic, certain coping skills may become more or less effective. In alignment with an underlying assumption of the Responses to Stress Model, effective coping occurs when the positive impact of coping or protective factors outweighs the negative impact of the stressor, thereby illustrating that responses to stress and the efficacy of coping necessarily oscillate based on context. Although secondary control engagement coping strategies were effective for adolescents managing Table 4 Multilevel model predicting adolescents' same-day and next-day positive affect over a 14-day period. Note: * p < .05, ** p < .01, *** p < .001. low levels of COVID-19-related health stress, it may be the case that solely using secondary control engagement coping strategies is no longer sufficient to counter the negative effects of elevated stress on well-being. Moreover, exogenous contextual variables and temporal shifts in healthrelated stressors may have affected the efficacy of secondary control engagement coping (Sandler, 2001). As COVID-19 continues to affect American families, it will be important to monitor the types and intensity of stressors, adolescents' use of coping mechanisms, and the efficacy of those coping mechanisms in promoting positive developmental outcomes. Parental support and adolescent psychological well-being Parental support predicted adolescents' increased positive affect within and across days and was related to lower same-day negative affect. Parental support has contributed to adolescents' resilience, especially when that support comes during traumatic or developmentally challenging times (Bradley, 2007;Kolak et al., 2018). Consistent with the documented literature on poverty and psychological well-being (Santiago et al., 2017;Schneider et al., 2015;Wadsworth, 2015), we also found that parental support buffered against the same-day effect of financial stress on adolescents' negative affect, and this buffering effect existed regardless of adolescents' level of stress. The efficacy of parental support is highly dependent on context (Jensen et al., 2013;Wadsworth, 2015). As a result, the degree to which adolescents have perceived control over a given stressor may be an important determinate of efficacy (Zacher and Rudolph, 2020;Zimmer-Gembeck et al., 2016): Although adolescents can engage in direct and preventative measures to protect their own health during a pandemic (e.g., social distancing), they may have little, if any, control over the financial circumstances of their family. Ergo, when a family experiences financial stress, adolescents may need their parents' assistance to navigate it. Limitations and future directions Although our daily-diary assessment provides a longitudinal perspective on adolescents' daily experiences, the 14-day assessment period was limited to the immediate onset of the pandemic. Future work should examine the extent to which these patterns hold throughout and after the pandemic, especially considering that disaster-related psychosocial impairments may lead to long-term negative developmental cascades (Masten, 2021). Researchers should also consider using within-day experience sampling so as to better understand the daily dynamics among stress, coping, and adjustment. In doing so, we can provide further credence to the causal relations suggested, but not proven, by our results. In addition, future studies should investigate adolescents' coping strategies and parental support as mediators in addition to moderators. For instance, some adolescents may be more likely to adopt disengagement coping strategies when confronted with stress, which in turn may lead to more negative affect. Finally, though racially and socioeconomically diverse, our nationwide sample had more adolescent participants from certain regions than others (e.g., the Midwest). This study should be replicated with geographically different samples to enhance the generalizability of the key findings. Implications and conclusion At the onset of COVID-19, adolescents faced a host of novel or amplified stressors that impacted their psychological well-being. While our findings showed strong connections between daily stressors and negative affect, we were also able to determine several factors-namely, secondary control engagement coping and parental social support-that helped youth mitigate the impact of health and financial stress on negative affect while also supporting youth's positive emotional experience in the midst of a global crisis. Practitioners working to support youth during times of heightened health or financial stress may want to encourage the use of secondary control engagement coping strategies among youth (e.g., distraction, cognitive restructuring) and remind parents of how important it is for youth to feel their social and emotional support during times of adversity. Moreover, researchers should continue to pursue lines of inquiry that allow for a better understanding of how adolescents' stressors, coping responses, and affective states may have shifted throughout the course of the pandemic. In particular, future studies should pursue questions pertaining to post-COVID psychological well-being and adjustment of adolescents to determine which individual, family, or school factors may mitigate the long-term psychosocial effects related to a multi-systemic disaster. Americans have not encountered a health crisis this pervasive or economically devastating since the Spanish flu pandemic of 1918, and COVID-19 placed adolescents into unprecedented developmentally challenging circumstances. Our study's micro-longitudinal design and critically timed data collection periods allowed us to show that American adolescents' pandemic-related health and financial stress were closely tied to their daily affect, even in the nascent stages of the pandemic. Although much is left to learn about coping and support as the pandemic continues, our study provides the first steps toward understanding how we may mitigate the impact of COVID-19-related health and economic stressors on adolescents' psychological wellbeing. Considering the prolonged, pervasive, and contentious nature of the COVID-19 crisis in the United States, it is critical to monitor the psychosocial impact of the pandemic on adolescents while continuing to identify personal and environmental protective factors for maximizing resilience. Declaration of Competing Interest All other authors declare that they have no conflicts of interest.
// Start starts the server. func (s *Server) Start() error { router := s.makeRoutes() Log.Info("HTTP server started", "port", s.config.Port) return http.ListenAndServe(fmt.Sprintf(":%d", s.config.Port), router) }
The Kern County Sheriff's Office is investigating a report of possible threats made involving students at Curran Middle School, a spokesperson for the agency said Tuesday. Court documents obtained by 23ABC suggest that a "hit list" identified 10 to 15 students who currently attend the school. "The unknown subjected to created the 'hit list' said he would shoot the students while they attended school on 02/14/2017," according to the court documents. Officials were alerted to the issue on January 2 after a child notified her father. On January 3, investigators found a threatening post on Instagram under the account name "2k 17 shots," which suggested the shooting would take place on February 15. The case is an ongoing investigation and at this point no arrests have been made, according to KCSO Public Information Officer Ray Pruitt. Curran is a Bakersfield City School District school and is located on Lymric Way in Southwest Bakersfield. The Bakersfield City School District sent out the following statement:
Andy Murray fans queue from early hours to claim spots on Henman Hill to watch No 2 seed take on Milos Raonic Murraymania has descended on SW19 before the Wimbledon gentlemen’s singles final in which the Scot will take on Canadian Milos Raonic. With Centre Courttickets long ago sold out, die-hard fans of Andy Murray queued from the early hours to claim a spot on Henman Hill to watch on a giant screen at the All England club on Sunday. Murray, 29, the No 2 seed, is the bookmakers’ favourite at 2-7 to win his second Wimbledon and third grand slam title, with Raonic, 25, the No 6 seed and playing his first grand slam final, at 3-1. Facebook Twitter Pinterest Spectators race up Murray Mound on day thirteen of the Wimbledon Championships to secure a good spot for the final. Photograph: Anthony Devlin/PA The Duke and Duchess of Cambridge, the prime minister, David Cameron, actors Hugh Grant and Benedict Cumberbatch, and the London mayor, Sadiq Khan, are among guests expected in the royal box. Scotland’s first minister, Nicola Sturgeon, is also expected although she is thought unlikely to repeat the stunt of her predecessor Alex Salmond, who flouted Wimbledon’s strict rule to unfurl a saltire in the royal box. Princess Elizabeth of Yugoslavia, 80, is also among the expected spectators. Raonic was born in Podgorica, Montenegro, part for former Yugoslavia, before moving to Canada at three. Tennis legends including multiple Wimbledon champions Chris Evert, Boris Becker, Björn Borg, Stefan Edberg and Roy Emerson are also expected. On Henman Hill – or Murray Mound – there was a frenzied sprint by fans to claim a spot in front of the large screen beaming the game live. Facebook Twitter Pinterest Fans run to get a seat on Murray Mound ahead of the start of play on men’s finals day. Photograph: Jordan Mansfield/Getty Images There was no doubting the loyalties of Jill Thomson, a 27-year-old environmental campaigner originally from Edinburgh, and friend Lizzie Edwards, 25, originally from Dumfries, both now living in London and sporting blue and white flags on their cheeks, and who had camped out overnight to get tickets. “I’m confident Murray will win,” said Thomson, “but because he has done it before, maybe that adds greater pressure.” Edwards, a Labour parliamentary researcher, was looking forward to some drama away from the party’s leadership battle. “It’s very nice to be here, away from the madness,” she said. “Everybody is Scottish today.” Draped in the Guernsey flag, supporting local girl Heather Watson in the mixed doubles finals as well as Murray, Channel islanders Margaret Poidevin, 65, and Jan Yabsley, 52, sprinted straight to Henman Hill to claim a prime spot. “I’m pretty confident Murray will win. He’s playing very well this year,” said Poidevin. “He’s not the underdog so there is more pressure on him to do well. It’s a good job Federer is not playing as my loyalties would have been very torn.” Yabsley added: “There is definitely more pressure on Andy. I’ll be really sad for him if he loses.” Facebook Twitter Pinterest Scottish Murray fans before the mens singles final. Photograph: Tom Jenkins for the Guardian Nurse Cath Powis, from Chelmsford, was looking forward to a good game, regardless who wins. “We seem to have allegiance to Murray when we feel like it, usually when he is in a final,” she said. “Is he British, or Scottish? But I hope he does well.” Musing on the threat of a post-Brexit breakup of the UK, she added: “I wonder, will he have to have a passport to get here in the future?” Fellow nurse Sue Butterworth, from Chesham, Buckinghamshire, was putting her faith in Murray to make it a double. “I’m confident he can do it, because he has been playing really well,” she said. Murray was not the only Scot going for a title. Gordon Reid, 24, is hoping to take home the inaugural Wimbledon men’s singles wheelchair title on Sunday.
/** * Calculates the centicell id for the given lat, lng. * * @param lat latitude * @param lng longitude * * @return centi cell id or null if it couldn't be calculated */ public static Integer calculateCentiCellId(Double lat, Double lng) { Integer centiCellId = null; if (lat != null && lng != null) { try { centiCellId = CellIdUtils.toCentiCellId(lat, lng); } catch (UnableToGenerateCellIdException e) { LOG.info("Unable to generate cell id", e); } } return centiCellId; }
import { Injectable } from '@nestjs/common'; import axios from 'axios'; import cheerio from 'cheerio'; import { parseDomain, ParseResultType } from 'parse-domain'; import * as simpleUnfurl from 'simple-unfurl'; import { SuccessResponse } from '../exceptions/success-exception.filter'; import { MysqlCacheService } from './mysql-cache.service'; @Injectable() export class AppService { constructor(private readonly mysqlCacheService: MysqlCacheService) {} async unfurlLink(url: string): Promise<any> { const documentObject = await this.fetchHTML(url); const resource = { title: await this.getTitle(url, documentObject), favicon: await this.getFavicon(url, documentObject), description: await this.getDescription(url, documentObject), }; // Add to resource to our cache. await this.mysqlCacheService.set(url, resource); return new SuccessResponse(resource).response(); } private async getFavicon( url: string, documentObject: any, ): Promise<string | null> { let favicon = null; const $ = await documentObject; const faviconUrl = $("link[rel='icon']").attr('href'); // verify if valid complete favicon url try { new URL(faviconUrl); return faviconUrl; } catch (error) {} const parsedUrl = new URL(url); const hostname = parsedUrl.hostname; const parseResult = parseDomain(hostname); if (faviconUrl && parseResult.type === ParseResultType.Listed) { const { domain, topLevelDomains } = parseResult; if (domain && topLevelDomains) favicon = faviconUrl.startsWith('/') ? `${domain}.${topLevelDomains[0]}${faviconUrl}` : `${domain}.${topLevelDomains[0]}/${faviconUrl}`; } return favicon; } private async getTitle( url: string, documentObject: any, ): Promise<string | null> { const $ = await documentObject; let title = $('title').text(); if (!title) { const pageData = await simpleUnfurl(url); title = pageData.title; } return title ? title : null; } private async getDescription( url: string, documentObject: any, ): Promise<string | null> { const $ = await documentObject; let description = null; const mainHTML = $('main p').text(); try { description = mainHTML.split('.').slice(0, 2).join('. '); // Fetch the first two sentences from paragraph tags in the main HTML element. } catch (error) { const pageData = await simpleUnfurl(url); description = pageData.description; } return description; } private async fetchHTML(url: string) { // fetch and load HTML page from url. const { data } = await axios.get(url); return cheerio.load(data); } }
// NewCmdLineSet registers flags for the passed template value in the standard // library's main flag.CommandLine FlagSet so binaries using dials for flag // configuration can play nicely with libraries that register flags with the // standard library. (or libraries using dials can register flags and let the // actual process's Main() call Parse()) func NewCmdLineSet(cfg *NameConfig, template interface{}) (*Set, error) { pval, ptyp, ptrifyErr := ptrified(template) if ptrifyErr != nil { return nil, ptrifyErr } s := Set{ Flags: flag.CommandLine, ParseFunc: func() error { flag.Parse(); return nil }, ptrType: ptyp, flagsRegistered: true, NameCfg: cfg, flagFieldName: map[string]string{}, } if err := s.registerFlags(pval, ptyp); err != nil { return nil, err } return &s, nil }
package com.github.songjiang951130.leetcode.backtrack; import com.google.common.collect.Lists; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; public class MoneyTest { Money money = new Money(); @Test public void handle() { List<List<Integer>> result = money.handle(new int[]{10, 10, 20, 40, 60, 120}, 100); List<Integer> list = Lists.newArrayList(10, 10, 20, 60); List<List<Integer>> expect1 = new ArrayList<>(); expect1.add(list); assertTrue(expect1.equals(result)); } }
/** * Converts a hex character pair into a byte. For example the pair {@code '7'} * and {@code 'D'} returns the byte value {@code 125}. * * <p> * The input values must be only the characters {@code 0-9}, {@code A-F} and * {@code a-f}. * * @throws IllegalArgumentException if either c1 or c2 is an illegal character. * @param c1 first character of pair * @param c2 second character of pair * @return */ public static byte hexCharToByte(char c1, char c2) { int high = hexToDec(c1); int low = hexToDec(c2); if (high == -1 || low == -1) { char illegal = (high == -1) ? c1 : c2; throw new IllegalArgumentException("Character '" + illegal + "' is illegal. Only characters 0-9, A-F and a-f are allowed."); } return (byte) ((high * 16) + low); }
t=int(input()) while t>0: n=int(input()) athletes=input().split(" ") athletes=[int(_) for _ in athletes] athletes=sorted(athletes) i=0 min=None while i<n-1: if min == None or athletes[i+1]-athletes[i]<min: min=athletes[i+1]-athletes[i] i+=1 print(min) t-=1
Guest Post by Willis Eschenbach In her always interesting blog, Dr. Judith Curry [and Anthony at WUWT] points to a very well-researched article by Bjorn Lomborg, peer-reviewed, entitled “Impact of Current Climate Proposals” (full text). He has repeated the work that Tom Wigley did for the previous IPCC report. There is a simplified climate model called “MAGICC” which is used extensively by the IPCC. It can be set up to emulate the results of any of the climate models used by the IPCC, including their average results, by merely changing the MAGICC settings. This lets us figure out how much cooling we can expect from a variety of programs that promise to reduce CO2. The abstract of the paper says (emphasis and formatting mine): This article investigates the temperature reduction impact of major climate policy proposals implemented by 2030, using the standard MAGICC climate model. Even optimistically assuming that promised emission cuts are maintained throughout the century, the impacts are generally small. The impact of the US Clean Power Plan (USCPP) is a reduction in temperature rise by 0.013°C by 2100 . . The full US promise for the COP21 climate conference in Paris, its so-called Intended Nationally Determined Contribution (INDC) will reduce temperature rise by 0.031°C . . The EU 20-20 policy has an impact of 0.026°C , the EU INDC 0.053°C , and China INDC 0.048°C . , the EU INDC , and China INDC . All climate policies by the US, China, the EU and the rest of the world, implemented from the early 2000s to 2030 and sustained through the century will likely reduce global temperature rise about 0.17°C in 2100. These impact estimates are robust to different calibrations of climate sensitivity, carbon cycling and different climate scenarios. Current climate policy promises will do little to stabilize the climate and their impact will be undetectable for many decades. Note that in all cases, these are the optimistic numbers, in which the supposed reductions in CO2 emissions are assumed to continue after 2030 all the way until 2100. Of particular interest to me was the impact of the Obama War On Coal, or as it is known, the US Clean Power Plan (USCPP). Even if we can implement it, and then assuming we can follow it until 2100, the total reduction in temperature rise is estimated to be 0.013°C. Now, that’s a bit over a hundredth of a degree Celsius. The problem is, nobody has a good handle on just how small that reduction in temperature actually is, because we have nothing to compare it to. Even fever thermometers only measure to a tenth of a degree. Casting about to rephrase this number in units that might be more understandable than hundredths of a degree, I remembered the old rule of thumb about how much the air cools off as you climb a mountain. Everyone knows that as you go up a mountain, the air gets cooler. The rate at which non-condensing air cools with increasing altitude is called the “dry adiabatic lapse rate”. The rule of thumb states that for every hundred metres higher that you climb, the temperature drops by 1°C. Now, a human being is typically around 1.7 metres tall, plus or minus. This means that other things being equal, the air at your head is about 0.017°C cooler than the air at your feet. And recall from above that the “impact of the US Clean Power Plan (USCPP) is a reduction in temperature rise by 0.013°C by 2100” … Which means that after spending billions of dollars and destroying valuable power plants and reducing our energy options and making us more dependent on Middle East oil, all we will do is make the air around our feet as cool as the air around our heads … I am overcome with gratitude for such a stupendous accomplishment. Seriously. The sum total of the entire restructuring of the US energy production will be to make the air around our feet as cool as the air around our heads. Now, at this point the advocates of the policy often say something like “Yes, but this is just the first step. Wait until the other nations get so amazed at the damage we’re doing to our own economy that they all want to sign on and do the same”. Of course they don’t put it honestly like that, but their belief is that if the US gets stupid, everyone will follow our lead. I don’t believe it for one minute, no matter how much they SAY that they will come to the party, but let’s imagine that fairy tale to be true. Well, Lomborg calculated that as well. He used MAGICC to compute the combined effect of the CO2 promises of the whole world, and the answer was 0.17°C of cooling by 2100 in the optimistic scenario, where everyone not only meets their promised reductions but holds to them from 2030 to 2100. And the number for what Lomborg calls the “pessimistic” scenario, but which might more accurately be called the “realistic” scenario, is a reduction in warming of 0.05°C (see his Table 1). And this in turn is equivalent to the difference in temperature that you’d get from walking five metres higher on the hillside. You know, like when you say “it’s so hot here, I think I’ll walk up the hill the equivalent of two flights of stairs so I’m five metres higher, and I’ll be cooler by five hundredths of a degree” … In any case, the MAGICC results are what are used by the IPCC, so there you have it. If everything that the politicians in Paris are promising comes to pass, it will make a difference of between five hundredths and seventeen hundredths of a degree by 2100 … at an astronomical price, billions and billions of dollar globally. Sigh … an astronomically large price for an unmeasurably small cooling. Freakin’ brilliant. This is what passes for the peak of “responsible” scientific thought these days about the climate, but to me, it’s just the height of temperature folly. Best of the autumn days to everyone, w. AS USUAL: If you disagree with someone, please quote the exact words you disagree with. This lets everyone understand exactly what you are objecting to. Note: Willis was apparently reading Curry’s article while the WUWT article from Lomborg posted, so I added a link in the first paragraph -Anthony Advertisements Share this: Print Email Twitter Facebook Pinterest LinkedIn Reddit
// The idea is to make the Sorted tree simplest. After PatchWasSucc(), there are many // edges with pred having only one succ and succ having only one pred. If there is no // any Action (either for building tree or checking validity), this edge can be shrinked // and reduce the problem size. // // However, there is one problem as whether we need add additional fields in the AppealNode // to save this simplified tree, or we just modify the mSortedChildren on the tree? // The answer is: We just modify the mSortedChildren to shrink the useless edges. void Parser::SimplifySortedTree() { std::deque<AppealNode*> working_list; working_list.push_back(mRootNode->mSortedChildren.ValueAtIndex(0)); while(!working_list.empty()) { AppealNode *node = working_list.front(); working_list.pop_front(); MASSERT(node->IsSucc() && "Sorted node is not succ?"); if (node->IsToken()) continue; node = SimplifyShrinkEdges(node); for (unsigned i = 0; i < node->mSortedChildren.GetNum(); i++) { working_list.push_back(node->mSortedChildren.ValueAtIndex(i)); } } if (mTraceSortOut) DumpSortOut(mRootNode->mSortedChildren.ValueAtIndex(0), "Simplify AppealNode Trees"); }
/** * <p>A {@link LinkValueList} is a representation of the string that is contained in a {@link CoapMessage} with * content type {@link ContentFormat#APP_LINK_FORMAT}.</p> * * <p>A {@link LinkValueList} contains zero or more instances of {@link LinkValue}.</p> * * <p>The notations are taken from RFC 6690</p> * * @author Oliver Kleine */ public class LinkValueList { //******************************************************************************************* // static methods //******************************************************************************************* /** * Decodes a serialized link-value-list, e.g. the payload (content) of a {@link CoapMessage} with content type * {@link ContentFormat#APP_LINK_FORMAT} and returns a corresponding {@link LinkValueList} instance. * * @param linkValueList the serialized link-value-list * * @return A {@link LinkValueList} instance corresponsing to the given serialization */ public static LinkValueList decode(String linkValueList) { LinkValueList result = new LinkValueList(); Collection<String> linkValues = getLinkValues(linkValueList); for(String linkValue : linkValues) { result.addLinkValue(LinkValue.decode(linkValue)); } return result; } private static Collection<String> getLinkValues(String linkValueList) { List<String> linkValues = new ArrayList<>(); Collections.addAll(linkValues, linkValueList.split(",")); return linkValues; } //****************************************************************************************** // instance related fields and methods //****************************************************************************************** private Collection<LinkValue> linkValues; private LinkValueList() { this.linkValues = new TreeSet<>(new Comparator<LinkValue>() { @Override public int compare(LinkValue linkValue1, LinkValue linkValue2) { return linkValue1.getUriReference().compareTo(linkValue2.getUriReference()); } }); } /** * Creates a new instance of {@link LinkValueList} * @param linkValues the {@link LinkValue}s to be contained in the {@link LinkValueList} to be created */ public LinkValueList(LinkValue... linkValues) { this.linkValues = new ArrayList<>(Arrays.asList(linkValues)); } /** * Adds an instance of {@link LinkValue} to this {@link LinkValueList}. * @param linkValue the {@link LinkValue} to be added */ public void addLinkValue(LinkValue linkValue) { this.linkValues.add(linkValue); } public boolean removeLinkValue(String uriReference) { for (LinkValue linkValue : this.linkValues) { if (linkValue.getUriReference().equals(uriReference)) { this.linkValues.remove(linkValue); return true; } } return false; } /** * Returns all URI references contained in this {@link LinkValueList} * * @return all URI references contained in this {@link LinkValueList} */ public List<String> getUriReferences() { List<String> result = new ArrayList<>(linkValues.size()); for (LinkValue linkValue : linkValues) { result.add(linkValue.getUriReference()); } return result; } /** * Returns the URI references that match the given criterion, i.e. contain a {@link LinkParam} with the given * pair of keyname and value. * * @param key the {@link LinkParam.Key} to match * @param value the value to match * * @return the URI references that match the given criterion */ public Set<String> getUriReferences(LinkParam.Key key, String value) { Set<String> result = new HashSet<>(); for (LinkValue linkValue : linkValues) { if (linkValue.containsLinkParam(key, value)) { result.add(linkValue.getUriReference()); } } return result; } /** * Returns the {@link LinkParam}s for the given URI reference. * * @param uriReference the URI reference to lookup the {@link LinkParam}s for * * @return the {@link LinkParam}s for the given URI reference */ public Collection<LinkParam> getLinkParams(String uriReference) { List<LinkParam> result = new ArrayList<>(); for (LinkValue linkValue : this.linkValues) { if (linkValue.getUriReference().equals(uriReference)) { return linkValue.getLinkParams(); } } return null; } public LinkValueList filter(LinkParam.Key key, String value) { LinkValueList result = new LinkValueList(); for (LinkValue linkValue : this.linkValues) { if (linkValue.containsLinkParam(key, value)) { result.addLinkValue(linkValue); } } return result; } public LinkValueList filter(String hrefValue) { if (hrefValue.endsWith("*")) { return filterByUriPrefix(hrefValue.substring(0, hrefValue.length() - 1)); } else { return filterByUriReference(hrefValue); } } private LinkValueList filterByUriPrefix(String prefix) { LinkValueList result = new LinkValueList(); for (LinkValue linkValue : this.linkValues) { if (linkValue.getUriReference().startsWith(prefix)) { result.addLinkValue(linkValue); } } return result; } private LinkValueList filterByUriReference(String uriReference) { LinkValueList result = new LinkValueList(); for (LinkValue linkValue : this.linkValues) { if (linkValue.getUriReference().endsWith(uriReference)) { result.addLinkValue(linkValue); return result; } } return result; } /** * Returns a string representation of this {@link LinkValueList}, i.e. the reversal of {@link #decode(String)} * @return a string representation of this {@link LinkValueList}, i.e. the reversal of {@link #decode(String)} */ public String encode() { StringBuilder builder = new StringBuilder(); for (LinkValue linkValue : this.linkValues) { builder.append(linkValue.toString()); builder.append(","); } if (builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } /** * Returns a string representation of this {@link LinkValueList} (same as {@link #encode()} * @return a string representation of this {@link LinkValueList} (same as {@link #encode()} */ @Override public String toString() { return this.encode(); } }
def create_dataset(file_name, input_type, size, classes, test_size, add_to): if input_type == 'mongo': create_dataset_mongo(file_name, size, classes, test_size, add_to) elif input_type == 'json': create_dataset_json(file_name, size, classes, test_size, add_to) else: click.BadParameter('Invalid input type given, choose either mongo or json')
import calendar #import calendar module print("This Program Creates and Displays a Calendar of months for any year after 1970 and before 2039") #later after 1900 while True: try: year = int(input("Enter the Calendar Year: ")) except ValueError: print("Invalid Entry") else: if 1970 <= year < 2039 : break else: print('Year Range:(1970-2038)') print() #blank line while True: try: month = int(input("Enter the first month to start from: ")) except ValueError: print("Invalid Entry") else: if 0 < month < 13: break else:print('Dummy, Month Range is 1...12') print() #blank line for _ in range(3): # user is given a total of three chances try: number = int(input('Enter number of months to print the calendar: (MAXIMUM is 12): > ')) except ValueError: print('Invalid Entry') else: if number > 12: print('Maximum is 12: DEFAULT=2') number = 2 break else: break #if all input is good else: print('You are not serious!!! DEFAULT=2') number=2 for cal in range(number): print() if month+cal <= 12: display = calendar.month(year, month+cal) #pass else: #correct from here later month = cal year += 1 display = calendar.month(year, cal-month+number) print(display)
def cameracalibrator_master_srv(command,chessboard_size,chessboard_square): rospy.wait_for_service('cameracalibrator_master') proxy = rospy.ServiceProxy('cameracalibrator_master',CameraCalibratorCmd) try: response = proxy(command,chessboard_size,chessboard_square) except rospy.ServiceException, e: print('ERROR: service request failed') response = None return response
/** * Add a relationship to the data set. * * @param relationship The relationship to be added. */ public void addRelationship( Relationship relationship ) { if (relationship != null) { if (relationships == null) { relationships = new LinkedList<Relationship>(); } relationships.add( relationship ); } }
// AddAttribute adds the name and value for a node attribute to the fingerprint // response func (f *FingerprintResponse) AddAttribute(name, value string) { if f.Attributes == nil { f.Attributes = make(map[string]string, 0) } f.Attributes[name] = value }
import * as assert from 'assert' import * as t from 'io-ts' import { withValidate } from '../src/withValidate' import { assertSuccess, assertFailure } from './helpers' describe('withValidate', () => { it('should return a clone of a codec with the given validate function', () => { const T = withValidate(t.number, (u, c) => t.number.validate(u, c).map(n => n * 2)) assertSuccess(T.decode(1), 2) assertFailure(T, null, ['Invalid value null supplied to : number']) }) it('should accept a name', () => { const T = withValidate(t.number, (u, c) => t.number.validate(u, c).map(n => n * 2), 'T') assert.strictEqual(T.name, 'T') }) })
<gh_stars>1-10 import numpy as np # import pandas as pd import tensorflow as tf import parse_data_utils, model # tf.enable_eager_execution() tfrecord_file = '../data/cnn/tfrecords/guide_passenger_withORFcanon_allsites_feat8_11batches_SAbg.tfrecord' tpm_dataset = tf.data.TFRecordDataset(tfrecord_file) TRAIN_MIRS = ['lsy6','mir1'] VAL_MIRS = ['mir7'] MIRLEN, SEQLEN = 10, 12 def _parse_fn_train(x): return parse_data_utils._parse_repression_function(x, TRAIN_MIRS, MIRLEN, SEQLEN, 8, 2, True) def _parse_fn_val(x): return parse_data_utils._parse_repression_function(x, TRAIN_MIRS + VAL_MIRS, MIRLEN, SEQLEN, 8, 2, True) tpm_dataset = tpm_dataset.map(_parse_fn_train) tpm_iterator = tpm_dataset.make_initializable_iterator() next_tpm_batch = parse_data_utils._build_tpm_batch(tpm_iterator, 1) padded = model.pad_vals(tf.squeeze(next_tpm_batch['features'][:, 1]), next_tpm_batch['nsites'], 4, 1, -50) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(tpm_iterator.initializer) print(sess.run(next_tpm_batch))
/** * This class allows a bpmscript to assume an interface and look like a * regular service. Useful for things like spring * * @author jamie */ public class BpmScriptProxy implements InvocationHandler { private String definitionName; private long defaultTimeout; private Map<String, Long> timeouts; private IBpmScriptFacade bpmScriptFacade; public BpmScriptProxy(IBpmScriptFacade bpmScriptFacade, String definitionName, long timeout, Map<String, Long> timeouts) { super(); this.bpmScriptFacade = bpmScriptFacade; this.definitionName = definitionName; this.defaultTimeout = timeout; this.timeouts = timeouts; } @SuppressWarnings("unchecked") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long timeout = defaultTimeout; Long specificTimeout = null; if(timeouts != null) { specificTimeout = timeouts.get(method.getName()); } if(specificTimeout != null) { timeout = specificTimeout; } return bpmScriptFacade.call(definitionName, method.getName(), timeout, args); } }
use crate::error::CompileError; use shaderc::{IncludeType, ResolvedInclude}; use shaderc::{ShaderKind, CompileOptions}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::borrow::Cow; pub fn compile<T>(path: T, include_path: Option<T>, shader_kind: ShaderKind, compiler_options: Option<CompileOptions>) -> Result<Vec<u32>, CompileError> where T: AsRef<Path>, { compile_with_options(&read_to_string(&path), include_path, shader_kind, compiler_options) } pub fn compile_from_string<T>(input: &str, include_path: Option<T>, shader_kind: ShaderKind, compiler_options: Option<CompileOptions>) -> Result<Vec<u32>, CompileError> where T: AsRef<Path>, { compile_with_options(input, include_path, shader_kind, compiler_options) } pub fn compile_with_options<T>(src: &str, include_path: Option<T>, shader_kind: ShaderKind, options: Option<CompileOptions>) -> Result<Vec<u32>, CompileError> where T: AsRef<Path>, { // TODO Probably shouldn't create this every time. let mut compiler = shaderc::Compiler::new().ok_or(CompileError::CreateCompiler)?; let mut options = { match options { None => CompileOptions::new().ok_or(CompileError::CreateCompiler).unwrap(), Some(option) => option, } }; let path = { if let Some(path) = &include_path { options.set_include_callback(|path, include_type, folder_path, depth| { get_include(path, include_type, folder_path, depth) }); path.as_ref().to_str().ok_or(CompileError::InvalidPath)? } else { options.set_include_callback(|path, include_type, folder_path, depth| { default_get_include(path, include_type, folder_path, depth) }); "" } }; let result = compiler .compile_into_spirv( src, shader_kind, path, "main", Some(&options), ) .map_err(CompileError::Compile)?; let data = result.as_binary(); Ok(data.to_owned()) } pub fn read_to_string<'a, T>(path: &T) -> Cow<'a, str> where T: AsRef<Path>, { let mut f = File::open(path).map_err(CompileError::Open).expect(""); let mut src = String::new(); f.read_to_string(&mut src).map_err(CompileError::Open).expect(""); Cow::Owned(src) } fn default_get_include( path: &str, include_type: IncludeType, folder_path: &str, _depth: usize, ) -> Result<ResolvedInclude, String> { // TODO: Does this print out anything meaningful? Err(format!("No include path given for {}", path).to_string()) } fn get_include( path: &str, include_type: IncludeType, folder_path: &str, _depth: usize, ) -> Result<ResolvedInclude, String> { match include_type { IncludeType::Relative => { let p = Path::new(path); let mut folder = PathBuf::from(folder_path); folder.pop(); folder.push(p); let p = folder; if !p.is_file() { return Err("Include doesn't point to file".to_string()); } let resolved_name = p .to_str() .ok_or("Path has invalid characters".to_string())? .to_owned(); let p = p.canonicalize().map_err(|_| "Failed to parse include path".to_string())?; let mut content = String::new(); File::open(p) .map_err(|_| "Couldn't open include directory".to_string())? .read_to_string(&mut content) .map_err(|_| "Failed to read included shader".to_string())?; Ok(ResolvedInclude { resolved_name, content, }) } IncludeType::Standard => Err("Standard includes are unimplemented".to_string()), } }
#ifndef SDKD_RESULTSET_H_ #define SDKD_RESULTSET_H_ #ifndef SDKD_INTERNAL_H_ #error "include sdkd_internal.h first" #endif #include <algorithm> #include <cmath> // #define CBSDKD_XERRMAP(X) \ // X(LCB_BUCKET_ENOENT, Error::SUBSYSf_CLUSTER|Error::MEMD_ENOENT) \ // X(LCB_AUTH_ERROR, Error::SUBSYSf_CLUSTER|Error::CLUSTER_EAUTH) \ // X(LCB_CONNECT_ERROR, Error::SUBSYSf_NETWORK|Error::ERROR_GENERIC) \ // X(LCB_NETWORK_ERROR, Error::SUBSYSf_NETWORK|Error::ERROR_GENERIC) \ // X(LCB_ENOMEM, Error::SUBSYSf_MEMD|Error::ERROR_GENERIC) \ // X(LCB_KEY_ENOENT, Error::SUBSYSf_MEMD|Error::MEMD_ENOENT) \ // X(LCB_ERR_TIMEOUT, Error::SUBSYSf_CLIENT|Error::CLIENT_ETMO) namespace CBSdkd { class Handle; class ResultOptions { public: bool full; bool preload; unsigned int multi; unsigned int expiry; unsigned int flags; unsigned int iterwait; unsigned int delay_min; unsigned int delay_max; unsigned int delay; unsigned int timeres; unsigned int persist; unsigned int replicate; ResultOptions(const Json::Value&); ResultOptions(bool full = false, bool preload = false, unsigned int expiry = 0, unsigned int delay = 0); unsigned int getDelay() const; private: void _determine_delay(); }; class TimeWindow { public: TimeWindow() : time_total(0), time_min(-1), time_max(0), time_avg(0), count(0) { } virtual ~TimeWindow() { } // Duration statistics unsigned int time_total; unsigned int time_min; unsigned int time_max; unsigned int time_avg; std::vector<suseconds_t> durations; unsigned count; std::map<std::string, int> ec; }; class ResultSet { public: ResultSet(int pFactor) : remaining(0), vresp_complete(false), parent(NULL), dsiter(NULL) { m_pFactor = pFactor; clear(); } // Sets the status for a key // @param err the error from the operation // @param key the key (mandatory) // @param nkey the size of the key (mandatory) // @param expect_value whether this operation should have returned a value // @param value the value (can be NULL) // @param n_value the size of the value void setRescode(std::error_code err, const void* key, size_t nkey, bool expect_value, const void* value, size_t n_value); void setRescode(std::error_code err) { setRescode(err, NULL, 0, false, NULL, 0); } void setRescode(std::error_code err, const char *key, size_t nkey) { setRescode(err, key, nkey, false, NULL, 0); } void setRescode(std::error_code err, const std::string key, bool expect_value) { setRescode(err, key.c_str(), key.length(), true, NULL, 0); } void setRescode(std::error_code err, bool isFinal) { vresp_complete = isFinal; setRescode(err, NULL, 0, false, NULL, 0); } std::map<std::string,int> stats; std::map<std::string,std::string> fullstats; std::vector<TimeWindow> timestats; ResultOptions options; static int m_pFactor; Error getError() { return oper_error; } Error setError(Error newerr) { Error old = oper_error; oper_error = newerr; return old; } void resultsJson(Json::Value *in) const; void markBegin() { struct timeval tv; gettimeofday(&tv, NULL); opstart_tmsec = getEpochMsecs(); } static suseconds_t getEpochMsecs(timeval& tv) { gettimeofday(&tv, NULL); return (suseconds_t)(((double)tv.tv_usec / 1000.0) + tv.tv_sec * 1000); } static suseconds_t getEpochMsecs() { struct timeval tv; return getEpochMsecs(tv); } static suseconds_t getPercentile(std::vector<suseconds_t> durations) { int size = durations.size(); if (size == 0) { return 0; } if (size == 1) { return durations[0]; } std::sort (durations.begin(), durations.end()); int idx = (int)ceil(size*m_pFactor/100)-1; return durations[idx]; } void clear() { stats.clear(); fullstats.clear(); timestats.clear(); remaining = 0; win_begin = 0; cur_wintime = 0; opstart_tmsec = 0; } Error oper_error; int remaining; unsigned int obs_persist_count; unsigned int obs_replica_count; unsigned int query_resp_count; unsigned int fts_query_resp_count; unsigned int cbas_query_resp_count; unsigned long long obs_master_cas; bool vresp_complete; bool ryow; std::string scan_consistency; Handle* parent; private: friend class Handle; DatasetIterator *dsiter; // Timing stuff time_t win_begin; time_t cur_wintime; // Time at which this result set was first batched suseconds_t opstart_tmsec; }; } // namespace #endif /* SDKD_RESULTSET_H_ */
/** * A class for handling a single-selection across a set of ClassDisplay items. */ public class ClassDisplaySelectionManager { private final Set<ClassDisplay> classDisplayList = new HashSet<>(); private final List<FXPlatformConsumer<ClassDisplay>> selectionListeners = new ArrayList<>(); private ClassDisplay selected = null; public ClassDisplaySelectionManager() { } /** * Add a ClassDisplay to the set of possibly-selected classes */ public void addClassDisplay(ClassDisplay classDisplay) { classDisplayList.add(classDisplay); } /** * Remove a ClassDisplay from the set of possibly-selected classes */ public void removeClassDisplay(ClassDisplay classDisplay) { classDisplayList.remove(classDisplay); } /** * Select the given item. The setSelected method of all classes will * be called with the relevant true/false state. */ public void select(ClassDisplay target) { target.setSelected(true); selected = target; for (ClassDisplay display : classDisplayList) { if (!display.equals(target)) { display.setSelected(false); } } for (FXPlatformConsumer<ClassDisplay> selectionListener : selectionListeners) { selectionListener.accept(target); } } /** * Gets the currently selected ClassDisplay. May be null. */ public ClassDisplay getSelected() { return selected; } /** * Adds a selection listener to be called back when the selection changes. * Note: it is possible that null may be passed as the current selection. */ public void addSelectionListener(FXPlatformConsumer<ClassDisplay> listener) { selectionListeners.add(listener); } }
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import viewsets from profiles_api import serializers from profiles_api import models class TestApiView(APIView): """Test API view""" def get(self,request,format=None): """Return a List of test APIViews""" fruits_list = [] for i in range(10): fruits_list.append("Kutta") return Response({'message':'Le baba aam kha','data':fruits_list}) class UserProfileViewSets(viewsets.ModelViewSet): """Handling for creating and updating user profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all()
#include <bits/stdc++.h> using namespace std; #define ll long long int int main() { int t;cin>>t; while(t--) { int a,b,c,d,x,y,l,r,u,dd; cin>>a>>b>>c>>d>>x>>y>>l>>dd>>r>>u; l-=x;r-=x;u-=y;dd-=y; int hr,vr; if(b>a) hr=abs(b-a); else hr=(-1) * abs(b-a); if(d>c) vr=abs(d-c); else vr=(-1)*abs(d-c); if(a==0 && b==0 && c==0 && d==0) cout<<"Yes\n"; else { if(a==0 && b==0 && (c!=0 || d!=0)) { if( (abs(u)>0 || abs(dd)>0) && (vr >=dd && vr <=u) ) cout<<"Yes\n"; else cout<<"No\n"; } else { if((a!=0 || b!=0) && c==0 && d==0) { if((abs(l)>0 || abs(r)>0)&&(hr>=l && hr <=r)) cout<<"Yes\n"; else cout<<"No\n"; } else { if((abs(l)>0 || abs(r)>0)&&(hr>=l && hr <=r) && (abs(u)>0 || abs(dd)>0) && (vr >=dd && vr <=u)) cout<<"Yes\n"; else cout<<"No\n"; } } } } }
Implantology and the severely resorbed edentulous mandible. Patients with a severely resorbed edentulous mandible often suffer from problems with the lower denture. These problems include: insufficient retention of the lower denture, intolerance to loading by the mucosa, pain, difficulties with eating and speech, loss of soft-tissue support, and altered facial appearance. These problems are a challenge for the prosthodontist and surgeon. Dental implants have been shown to provide a reliable basis for fixed and removable prostheses. This has resulted in a drastic change in the treatment concepts for management of the severely resorbed edentulous mandible. Reconstructive, pre-prosthetic surgery has changed from surgery aimed to provide a sufficient osseous and mucosal support for a conventional denture into surgery aimed to provide a sufficient bone volume enabling implants to be placed at the most optimal positions from a prosthetic point of view. The aim of this paper is to review critically the literature on procedures related to the severely resorbed edentulous mandible and dental implant treatment. The study includes the transmandibular implant, (short) endosseous implants, and reconstructive procedures such as distraction osteogenesis, augmentation of the mandibular ridge with autogenous bone, and bone substitutes followed by the placement of implants. The number of patients participating in a study, the follow-up period, the design of the study, the degree of mandibular resorption, and the survival rate of the dental implants all are considered evaluation parameters. Although numerous studies have described the outcome results of dental implants in the edentulous mandible, there have been few prospective studies designed as randomized clinical trials that compare different treatment modalities to restore the severely resorbed mandible. Therefore, it is not yet possible to select an evidence-based treatment modality. Future research has to be focused on long-term, detailed follow-up clinical trials before scientifically based decisions in treating these patients can be made. This will contribute to a higher level of care in this field.
<reponame>nguyennguyen1112000/classroom import { Body, Controller, Post, Res } from '@nestjs/common'; import { GoogleService } from './google.service'; import { GoogleAuthDto } from './dto/google-login.dto'; @Controller('google') export class GoogleController { constructor(private readonly googleService: GoogleService) {} @Post() async googleAuth(@Body() googleAuthDto: GoogleAuthDto) { try { const response = await this.googleService.googleLogin(googleAuthDto); return response; } catch (error) { console.log(error.message); } } }
/* * Called by generic_file_read() to read a page of data * * In turn, simply calls a generic block read function and * passes it the address of befs_get_block, for mapping file * positions to disk blocks. */ static int befs_readpage(struct file *file, struct page *page) { return block_read_full_page(page, befs_get_block); }
import { CronJob } from 'cron' import { logger, errorHandler } from '../utils' import { security } from './security' import { discovery } from './collaboration' import { reloadConfigInfo } from '../persistance/persistance' import { Config } from '../config' // Private functions const reloadCloudSettings = async (): Promise<void> => { try { // Get my organisation info await security.cacheItemsPrivacy() const cid = await discovery.reloadCid(Config.GATEWAY.ID) const partners = await discovery.reloadPartners() const info = await discovery.reloadPartnerInfo(cid) // Store configuration info await reloadConfigInfo(cid, info.name, info.nodes, partners) } catch (err) { const error = errorHandler(err) logger.error('Could refresh privacy and partners') logger.error(error.message) } } // Create jobs const reloadJob = new CronJob('0 0 * * * *', (() => { // Running every hour logger.info('Running scheduled task: Reloading privacy') reloadCloudSettings() }), null, true) // Export scheduler export const scheduledJobs = { start: () => { reloadJob.start() }, stop: () => { reloadJob.stop() } }
All of that free publicity couldn't push Megyn Kelly over the top. Despite a week's worth of stories about her controversial interview with conspiracy theorist Alex Jones, the Q&A ended up being watched by only 3.5 million viewers, and was soundly beaten by CBS rival “60 Minutes,” which drew 5.3 million viewers, according to Nielsen. The NBC hour-long “Sunday Night with Megyn Kelly” program was criticized ahead of time because Jones had in the past called the 2012 shootings at Sandy Hook Elementary School in Newton, Conn., a hoax. Members of that community, where 20 children and six educators were killed, were among those who spoke out against NBC airing the interview, and a local NBC affiliate refused to even carry the program. During the interview, Jones never gave a direct answer when the 46-year-old former FOX News host pressed him to admit he was wrong in his claim about the shootings. MEGYN KELLY'S INTERVIEW WITH ALEX JONES GETTING COMPLETE OVERHAUL The program took a nosedive in comparison to Kelly’s debut on June 4, which featured an interview with Russian president Vladimir Putin. That interview drew 6.2 million viewers. And Kelly didn’t just lose viewers. Forbes reported JPMorgan, along with several local advertisers, dropped spots from the show or, in the case of the financial company, the enirety of NBC News, until after the interview aired. But the controversy didn’t end there. Before the interview, Jones leaked an audio recording of what he said was a phone conversation with Kelly. In the conversation, Kelly was heard promising she would not portray him as “some kind of boogeyman.” MEGYN KELLY WARNS ALEX JONES 'ISN'T GOING AWAY' Shortly before the interview, which was aired on Father’s Day, Jones released a video in which he offered condolences to families who had lost children in the “horrible tragedy” of Newtown, but did not refer to his previous comments disputing the killings. A parent of one of the victims also spoke out. Nicole Hockley, who lost her 6-year-old son Dylan in the shooting, publicly announced she wouldn’t view the interview for “obvious” reasons. Relatives of the shooting victims have called Jones’ comments hurtful and said he has encourage people to harass them. Lawyers representing 12 people who lost loved ones in the Sandy Hook massacre wrote to the network and asked them not to air the interview. Prior to the interview, Kelly released a statement on Twitter June 13 explaining the importance of airing her conversation with Jones. Al Tompkins, the Poynter Institute’s senior faculty for broadcasting and online, told Forbes that Kelly will need to boost her ratings to ensure her reported seven-figure salary with the network. But he says there is still plenty of time. "What will show her success long term is if she gets the ratings she needs or not,” he explained. “These programs take a while to find an audience, and you won’t find it in the first few months.” The Associated Press contributed to this report.
#!/usr/bin/env python3 import argparse import glob import os import os.path as p import subprocess import sys DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) ) DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' ) # We don't include python-future (not to be confused with pythonfutures) because # it needs to be inserted in sys.path AFTER the standard library imports but we # can't do that with PYTHONPATH because the std lib paths are always appended to # PYTHONPATH. We do it correctly inside Vim because we have access to the right # sys.path. So for dev, we rely on python-future being installed correctly with # # pip install -r python/test_requirements.txt # # Pip knows how to install this correctly so that it doesn't matter where in # sys.path the path is. python_path = [ p.join( DIR_OF_THIS_SCRIPT, 'python' ), p.join( DIR_OF_THIRD_PARTY, 'ycmd' ) ] if os.environ.get( 'PYTHONPATH' ): python_path.append( os.environ[ 'PYTHONPATH' ] ) os.environ[ 'PYTHONPATH' ] = os.pathsep.join( python_path ) def RunFlake8(): print( 'Running flake8' ) args = [ sys.executable, '-m', 'flake8', p.join( DIR_OF_THIS_SCRIPT, 'python' ) ] root_dir_scripts = glob.glob( p.join( DIR_OF_THIS_SCRIPT, '*.py' ) ) args.extend( root_dir_scripts ) subprocess.check_call( args ) def ParseArguments(): parser = argparse.ArgumentParser() parser.add_argument( '--skip-build', action = 'store_true', help = 'Do not build ycmd before testing' ) parser.add_argument( '--coverage', action = 'store_true', help = 'Enable coverage report' ) parser.add_argument( '--no-flake8', action = 'store_true', help = 'Do not run flake8' ) parser.add_argument( '--dump-path', action = 'store_true', help = 'Dump the PYTHONPATH required to run tests ' 'manually, then exit.' ) parsed_args, unittest_args = parser.parse_known_args() if 'COVERAGE' in os.environ: parsed_args.coverage = ( os.environ[ 'COVERAGE' ] == 'true' ) return parsed_args, unittest_args def BuildYcmdLibs( args ): if not args.skip_build: subprocess.check_call( [ sys.executable, p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ), '--quiet' ] ) def UnittestTests( parsed_args, extra_unittest_args ): unittest_args = [ '-cb' ] prefer_regular = any( p.isfile( arg ) for arg in extra_unittest_args ) if not prefer_regular: unittest_args += [ '-p', '*_test.py' ] if extra_unittest_args: unittest_args.extend( extra_unittest_args ) if not ( prefer_regular and extra_unittest_args ): unittest_args.append( '-s' ) test_directory = p.join( DIR_OF_THIS_SCRIPT, 'python', 'ycm', 'tests' ) unittest_args.append( test_directory ) if parsed_args.coverage: executable = [ sys.executable, '-We', '-m', 'coverage', 'run' ] else: executable = [ sys.executable, '-We' ] unittest = [ '-m', 'unittest' ] if not prefer_regular: unittest.append( 'discover' ) subprocess.check_call( executable + unittest + unittest_args ) def Main(): ( parsed_args, unittest_args ) = ParseArguments() if parsed_args.dump_path: print( os.environ[ 'PYTHONPATH' ] ) sys.exit() if not parsed_args.no_flake8: RunFlake8() BuildYcmdLibs( parsed_args ) UnittestTests( parsed_args, unittest_args ) if __name__ == "__main__": Main()
Australian chiropractors are five year university trained, and are government registered and government regulated health professionals. To become a registered chiropractor in Australia you must have studied an accredited 5-year chiropractic program conducted at a University within Australia, or have completed an accredited program overseas that satisfies the requirements set by the Australian Chiropractic Regulating authority. A chiropractor’s education never ends. After entering practice, all chiropractors must complete continuing professional development courses and seminars to upgrade and improve their skills and to stay current on the latest scientific research. Currently there are four universities in Australia that have chiropractic degree programs. The RMIT University in Melbourne, Victoria offers a Bachelor of Health Science (Chiropractic) - 3 year undergraduate program followed by a Master of Clinical Chiropractic - 2 year postgraduate program. The Macquarie University in Sydney, New South Wales has a 3 year Bachelor of Chiropractic Science which provides the basis for entry into a 2 year Master of Chiropractic. The Murdoch University in Perth, Western Australia offers a Bachelor of Applied Science (in Chiropractic) / Bachelor of Chiropractic. This is offered as a double degree. Successful completion of the whole program of study is required for professional registration as a chiropractor. The Central Queensland University (Mackay, Brisbane, Melbourne and Sydney) offers a 3 year Bachelor of Science (Chiropractic) and a 2 year Master of Clinical Chiropractic.
<gh_stars>0 """Test random branches.""" from big_wall_finder.mp import parse_mp as mp def test_random_branch(): """Test random branch.""" d = mp.load_data() for _ in range(100): mp.print_random_branch(d) if __name__ == '__main__': test_random_branch()
Influencing Factors of the Initiation Point in the Parachute-Bomb Dynamic Detonation System The parachute system has been widely applied in modern armament design, especially for the fuel-air explosives. Because detonation of fuel-air explosives occurs during flight, it is necessary to investigate the influences of the initiation point to ensure successful dynamic detonation. In fact, the initiating position exist the falling area in the fuels, due to the error of influencing factors. In this paper, the major influencing factors of initiation point were explored with airdrop and the regularity between initiation point area and factors were obtained. Based on the regularity, the volume equation of initiation point area was established to predict the range of initiation point in the fuel. The analysis results showed that the initiation point appeared area, scattered on account of the error of attitude angle, secondary initiation charge velocity, and delay time. The attitude angle was the major influencing factors on a horizontal axis. On the contrary, secondary initiation charge velocity and delay time were the major influencing factors on a horizontal axis. Overall, the geometries of initiation point area were sector coupled with the errors of the attitude angle, secondary initiation charge velocity, and delay time. Introduction The parachute system is widely used nowadays in various fields, such as goods transportation and rapid deployment of war fighters, equipment and supplies. The armament design is important in fuel-air explosives (FAE). The FAE system is composed of buster charge, fuel, canister, secondary initiation charge, and parachute. The secondary initiation charge is set on the top of parachute in the FAE system. A process is called dynamic detonation when the detonation of fuel-air explosives occurs during flight. A successful dynamic detonation depends on the initiated position of secondary initiation charge. If the position of the charge initiating is in the cloud, dynamic detonation is successful; otherwise, dynamic detonation fails. Therefore, the influencing factors of initiation point is becoming an important issue. In the dynamic detonation system design, there is only a coordinate of initiation point. When the factors have errors in the experiment in case of reality condition, for example, error caused by devices or random error, the accuracy of initiation point decrease. Therefore, the initiation point area is produced. According to the characteristics of dynamic detonation, the parachute-bomb system trajectory is divided into three phase 1 : extraction phase, falling stability phase, and secondary initiating phase. Previous studies mostly focused on the changing flight signatures of parachute-bomb system in the extraction phase and landing point in the falling stability phase . Related results were obtained by and numerical simulation . However, the parachute-non-bomb phase was seldom studied. Though a series of airdrop tests, the major influencing factors of initiation point and the regularity were obtained. Based on the regularity, the volume equation of initiation point area was established to predict the range of initiation position in the fuels. General The airdrop experiments were carried out with hot air balloon system. As shown in Fig. 1, the parachute-bomb system was lifted 300 m above the ground with the hot air balloon system. Two high-speed digital cameras were placed on the ground. When the wind speed was less than 5 m·s -1 , the throwing system was triggered and the parachute system began to drop. At the same time, the experimental process was photographed with two high speed digital cameras. The parachute-bomb system is composed of buster charge, fuel, canister, secondary initiation charge, and parachute,as shown in Fig. 2. The data of the dropping process were acquired with two V12 high-speed color photography systems. The photographing frequency was 1000 frames per second. The secondary initiation charge trajectory of dynamic detonation system was obtained by image processing technology. In order to ensure the synchronism of the data recording, primary initiation time was considered as zero time. The coordinate system was established with the swept area of parachute system and the ground projective point of the parachute center was considered as the origin point. The typical result of secondary initiation charge trajectory is shown in Fig. 3 a) Sketch of the experimental layout b) Photo of experimental layout Trajectory of secondary initiation charge As shown in Fig. 3, the secondary initiation charge trajectory tends to be a straight line. Thus, the secondary initiation charge appeared to be like uniform motion. According to the experiment, influencing factors of secondary initiation charge trajectory included the attitude angle, parachute-non-bomb velocity, and delay time. Influence of attitude angle on the initiation point These factors influenced the attitude angle, for example, wind power, wind speed, type of parachute, and the length of parachute rope, and so on. When the attitude angle changed, the initiation point was different with the predict point. In order to find the rule between attitude angle with initiation points, points of trajectory under same delay time (0.2 s) and velocity (32.20m/s) were picked to drawn in Fig. 4 . As Fig. 4 shown, the shape of inanition point area is curve of trigonometric function under attitude angle. The attitude angle had obvious influence on horizontal axis(X axis), and little effect on vertical axis(Y axis). In a word, the attitude angle is the major influences on horizontal axis. The initiation points area changed significantly with the attitude angle on horizontal axis. The point in Fig.3 is fitted on the purpose of finding the influence rules. The relation formulae is expressed as Influence of velocity of secondary initiation charge on the initiation point The changes of velocity of secondary initiation charge were caused by these factors, for example, parachute formation (deformation or satiation), the resistance of fuel dispersal, and the gravity, and so on. When the velocity changed, the initiation point was different with the predict point. In order to find the dispersion rule between velocities of secondary initiation charge with initiation points, points of trajectory under same delay time (0.2 s) and the attitude angle (0°) were picked to drawn in Fig. 5. As Fig. 5 shown, the shape of inanition point dispersion is a straight line under the velocities. The velocity of secondary initiation charge had obvious influence on vertical axis, and no effect on horizontal axis. In brief, the velocity of secondary initiation charge is the major influences on vertical axis. The initiation point's area changed significantly with the velocity on horizontal axis. The point in Fig. 5 is fitted on the purpose of finding the influence rules. The relation formulae is expressed as Where c, d are constants and have relationship with delay time and the attitude angle; x, y are the coordinate of X, Y axis about initiation point, respectively. electromagnetic interference, and ground conditions (flat, hard, wet or low-lying), and so on. When the delay time changed, the initiation point was different with the predict point. In order to find the rule between delay time with initiation points, points of trajectory under same attitude angle (0°) and velocity (32.20m/s) were picked to drawn in a Fig. 6. As Fig. 6 shown, the shape of inanition point area is a straight line under delay time. The delay time had obvious influence on vertical axis, and no effect on horizontal axis. In short, the delay time is the major influences on vertical axis. The initiation point area changed significantly with the delay time on vertical axis. The point in Fig. 6 is fitted on the purpose of finding the influence rules. The relation formulae is expressed as Where e, f are constants and have relationship with delay time and the attitude angle; x, y are the coordinate of X, Y axis about initiation point, respectively. . 7. As the Fig. 7 shown, the shape of initiation point is sector. The volume of the dispersion sector could be estimated by math method, as shown in Fig. 8 Where v max , v min respectively represent maximum and minimum of velocity; t max , t min respectively represent maximum and minimum of delay time. In addition, the expression of the partition volume In conclusion, with Eq. (1)-(3), the volume of initiation point dispersion is expressed as Whereθmax andθmin respectively represent maximum and minimum of attitude angle in the error range; tmax and tmin respectively represent maximum and minimum of delay time in the error range;vmax and vmin respectively represent maximum and minimum of velocity in the error range. Conclusion In the paper, we studied the influencing factors of the initiation point dispersion in the fuel-air explosives. The main conclusions can be summarized as follows: The attitude angle is the major influences on horizontal axis. The dispersion relationship can be represented by
On decorrelated track-to-track fusion based on Accumulated State Densities Originally, the Accumulated State Density (ASD) has been proposed to provide an exact solution to the out-of-sequence measurement problem. The posterior probability density function of the joint states accumulated over time was derived for a centralized fusion, in which time delayed data may appear. On the other hand, an exact solution for T2TF has been published as the Distributed Kalman Filter (DKF). However, the DKF is exact only if global knowledge in terms of the measurement models for all sensors are available at a local processor. In a previous publication it was shown that an exact solution for T2TF can also be achieved as a convex combination of local ASDs generated at each node in a distributed sensor system. This method crucially differs from the DKF, in that an exact solution is achieved without each processing platform being required to have knowledge of the global information. The contribution of this paper is a presentation of the Distributed ASD (DASD) filter with a fixed length of the ASD state. This approach prevents the increasing transmission loads of the previous DASD implementation.
General manager Marc Bergevin said this week the answer to the Canadiens’ problems is in the locker room. Maybe if the GM looks around the room long enough he can find the roughly $8.5 million in salary-cap money he didn’t spend this summer to help improve his team. It’s hard to believe the NHL’s second-most valuable franchise with a record 24 Stanley Cups — the Canadiens were evaluated at $1.12 billion last year by Forbes, trailing only the New York Rangers at $1.25 billion — wouldn’t spend close to the $75-million cap limit. But that didn’t happen after Bergevin failed to re-sign free-agents Andrei Markov and Alexander Radulov this summer and didn’t seem to have a Plan B in place. Or at least not one that would work. Bergevin said he “kicked tires” on a lot of free agents this summer and made some “really, really good offers,” but the players decided they didn’t want to come to Montreal “for whatever reason.” That left the dapper GM with a lot of money sitting in his pockets. The Canadiens now have a 2-7-1 record — along with the worst offence in the NHL and the second-worst defence — heading into Saturday’s game against the New York Rangers at the Bell Centre (7 p.m., SN1, CITY, TVA Sports, TSN Radio 690). After Friday’s practice in Brossard, Andrew Shaw came to the defence of his GM. “Montreal’s not one of those markets where players want to go,” Shaw said. “I don’t know if it’s because of the media or whatnot. But around the league, it’s one of the places that people don’t like to go. Maybe it’s the tax bracket, who knows? I think it’s the highest in the league here. “I think he made some good moves,” Shaw added about Bergevin. “He got Karl (Alzner), who’s been great for us, a strong defenceman. I’m sure (Bergevin’s) not done. Who knows? I mean, it’s a long year, things can change. But I think he’s been doing a great job.” Bergevin acquired Shaw from the Chicago Blackhawks in the summer of 2016 in exchange for two second-round picks at the NHL Draft and then signed him to a six-year, $23.4-million contract, so you wouldn’t expect the player to say anything bad about the GM. “He’s a confident guy … he’s going to go out and work his ass off like we are right now, too,” Shaw said about Bergevin. “He’s doing his best job. It’s a tough job, man. A lot of pressure … more pressure than the players, that’s for sure. We got new faces, new guys. We just need to start clicking together.” Shaw makes a good point about free agents not wanting to come to Montreal, which makes you wonder why Bergevin didn’t lock up Markov and Radulov — two players who expressed their desire to stay here — earlier in the free-agent process. But that’s ancient history and now the GM says the answer to the Canadiens’ problems is in the locker room and he won’t make a panic trade. As for the extra salary-cap money, Bergevin said Wednesday: “It’s only frustrating if you know you can’t spend it or you don’t have it and you wish you could because then you could get the asset. But that’s not the case.” It might already be too late for Bergevin to spend that money to help the Canadiens this season. It took 95 points to make the Eastern Conference playoffs last season and to hit that mark the Canadiens would have to go 45-27 the rest of this season — depending on how many loser points they might earn in overtime and shootouts. “We’re not counting ourselves out just yet,” Brendan Gallagher said. “But it does need to turn around here pretty quickly. You can’t look too far ahead … you can’t win three games in one night.” Gallagher agrees with Bergevin that the answer is in the room. “What he means by that is we’re a capable group in here,” Gallagher said. “We’ve won games before, we understand what we need to do. I would agree with that. You look internal. For us, we’ve done it in spurts this season and we just haven’t been able to sustain it.” The Canadiens’ 4-0 loss to the Los Angeles Kings onThursday night at the Bell Centre highlighted some reasons there are NHL players who don’t want to play in Montreal with fans mock cheering goalie Carey Price after routine saves and starting a mock “Olé! Olé!” chant late in the third period. But Shaw enjoys playing here. “I like the passion around the city about the game of hockey,” he said. “They love it, it’s their No. 1 sport sport here and everyone in the city loves it, they thrive on hockey. Being back in Canada is nice. The living is great, the food’s great, the city’s great. You’re playing for the Montreal Canadiens … it’s pretty awesome.” It would be a lot more awesome if they started winning. [email protected] twitter.com/StuCowan1
NASA has successfully launched their first ever asteroid sampling mission, OSIRIS-REx, Thursday Sept. 8 2016. By Jonathan Stroud JournalistsForSpace.com The Atlas V 411, a United Launch Alliance rocket, has successfully launched from Cape Canaveral, Florida, carrying the spacecraft OSIRIS-REx (Origins Spectral Interpretation Resource Identification Security – Regolith Explorer). The spacecraft, built by Lockheed Martin, is designed to gather samples from the carbon-rich asteroid, Bennu (formerly 1999 RQ36). The near-Earth asteroid will be surveyed by OSIRIS-REx for two years before briefly rendezvousing with the surface to collect samples using the spacecraft’s mechanical arm. The spacecraft contains five specialized sensing and scanning instruments that will be utilized to explore Bennu, determine a sample location, and provide important information about the surface. Once the samples are collected, using the Touch-And-Go Sample Acquisition Mechanism (TAGSAM), it will return to Earth completing its seven-year mission. Scientists will analyze the asteroid samples in hopes of better understanding other asteroids, as well as how planets and life were formed in our solar system. The OSIRIS-REx spacecraft is targeted to reach the asteroid in 2018 and is estimated to return home to Earth in 2023. The Atlas V, flown three times previously, can have up to five strap-on boosters; although, to get the OSIRIS-REx into space only one booster was required. According to United Launch Alliance, “The Atlas V 400 series incorporates the flight proven 4-m diameter 12.0 m (39.3 ft) large payload fairing (LPF), the 12.9 m (42.3 ft) extended payload fairing (EPF), or the 13.8 m (45.3 ft) extended EPF (XEPF).” Why is this cool? The OSIRIS-Rx mission is cool because it could potentially give clues to how life began on Earth. How life arose is currently unknown, but scientists have speculated a comet or asteroid may have brought the ingredients of life to the planet. The findings from Bennu could revolutionize our understanding of the solar system. Why should I care? You should care about this mission because as of right now, no body really knows how complex-life began on this small rock being hurled through space we all call Home. NASA Continues its Social Media Outreach NASA continues to increase the agencies public outreach by allowing traditional media and social media influencers to receive special access to events. For the OSIRIS-REx launch, NASA allowed Social Media influencer Haley Vaca access through the NASA Social program. According to Vaca, “the experience was absolutely amazing. I am so thankful that NASA allowed me to experience this first-hand. For obvious reasons, the Launch was the best part of the Social; but other than that, seeing all the behind the scenes activity and everything that goes into this mission, it is truly Jaw dropping.” If you are passionate about space and satellites, and you are a social media influencer, you can apply for the GOES-R Launch in November. Find out more about the NASA Social program by CLICKING HERE. Check out a video of the launch below: Make sure to follow Journalists For Space for more OSIRIS-REx and other space related updates! Enjoy the “OSIRIS-REx Seeks to Find Origins of Life” article? Help support Journalists For Space by donating below!
//GetProject is the public wrapper for getting all the informations on a specific project func (pg *PostgreSQL) GetProject(projectName string) (models.Project, error) { p, err := pg.getProject(projectName) if err != nil { return models.Project{}, err } return p.ToModel(), nil }
// WithTraceID injects custom trace id into context to propagate. func WithTraceID(ctx context.Context, traceID trace.TraceID) context.Context { sc := trace.SpanContextFromContext(ctx) if !sc.HasTraceID() { var ( span trace.Span ) ctx, span = NewSpan(ctx, "gtrace.WithTraceID") defer span.End() sc = trace.SpanContextFromContext(ctx) } ctx = trace.ContextWithRemoteSpanContext(ctx, trace.NewSpanContext(trace.SpanContextConfig{ TraceID: traceID, SpanID: sc.SpanID(), TraceFlags: sc.TraceFlags(), TraceState: sc.TraceState(), Remote: sc.IsRemote(), })) return ctx }
<gh_stars>0 import React, { useRef} from 'react'; import { Form, FormControl } from 'react-bootstrap'; import {debounce} from '../core/utils'; interface SearchProps { onSearch: (keyword: string) => void } function Search(props:SearchProps) { const searchRef = useRef<HTMLInputElement>(null); const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { const form = event.currentTarget; event.preventDefault(); if (form.checkValidity() === false) { return; } debounced() } const debounced = debounce(() => { console.log('test') if(searchRef.current) { props.onSearch(searchRef.current.value) } }, 3000); return ( <div className="mt-5"> <Form onSubmit={handleSubmit}> <Form.Group className="form-group"> <FormControl type="text" aria-describedby="search" role="search" placeholder="Search a location" ref={searchRef} required /> </Form.Group> </Form> </div> ); } export default Search;
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0499 */ /* Compiler settings for jit.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __jit_h__ #define __jit_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IDebugIDEJIT2_FWD_DEFINED__ #define __IDebugIDEJIT2_FWD_DEFINED__ typedef interface IDebugIDEJIT2 IDebugIDEJIT2; #endif /* __IDebugIDEJIT2_FWD_DEFINED__ */ #ifndef __IDebugJIT2_FWD_DEFINED__ #define __IDebugJIT2_FWD_DEFINED__ typedef interface IDebugJIT2 IDebugJIT2; #endif /* __IDebugJIT2_FWD_DEFINED__ */ #ifndef __IDebugRuntimeJITServerProvider2_FWD_DEFINED__ #define __IDebugRuntimeJITServerProvider2_FWD_DEFINED__ typedef interface IDebugRuntimeJITServerProvider2 IDebugRuntimeJITServerProvider2; #endif /* __IDebugRuntimeJITServerProvider2_FWD_DEFINED__ */ #ifndef __IDebugSetJITEventCallback2_FWD_DEFINED__ #define __IDebugSetJITEventCallback2_FWD_DEFINED__ typedef interface IDebugSetJITEventCallback2 IDebugSetJITEventCallback2; #endif /* __IDebugSetJITEventCallback2_FWD_DEFINED__ */ #ifndef __IDebugProgramJIT2_FWD_DEFINED__ #define __IDebugProgramJIT2_FWD_DEFINED__ typedef interface IDebugProgramJIT2 IDebugProgramJIT2; #endif /* __IDebugProgramJIT2_FWD_DEFINED__ */ #ifndef __IJITDebuggingHost2_FWD_DEFINED__ #define __IJITDebuggingHost2_FWD_DEFINED__ typedef interface IJITDebuggingHost2 IJITDebuggingHost2; #endif /* __IJITDebuggingHost2_FWD_DEFINED__ */ #ifndef __IDebugWrappedJITDebugger2_FWD_DEFINED__ #define __IDebugWrappedJITDebugger2_FWD_DEFINED__ typedef interface IDebugWrappedJITDebugger2 IDebugWrappedJITDebugger2; #endif /* __IDebugWrappedJITDebugger2_FWD_DEFINED__ */ #ifndef __IDebugEngineJITSettings2_FWD_DEFINED__ #define __IDebugEngineJITSettings2_FWD_DEFINED__ typedef interface IDebugEngineJITSettings2 IDebugEngineJITSettings2; #endif /* __IDebugEngineJITSettings2_FWD_DEFINED__ */ #ifndef __IDEJITServer_FWD_DEFINED__ #define __IDEJITServer_FWD_DEFINED__ #ifdef __cplusplus typedef class IDEJITServer IDEJITServer; #else typedef struct IDEJITServer IDEJITServer; #endif /* __cplusplus */ #endif /* __IDEJITServer_FWD_DEFINED__ */ #ifndef __JITDebuggingHost_FWD_DEFINED__ #define __JITDebuggingHost_FWD_DEFINED__ #ifdef __cplusplus typedef class JITDebuggingHost JITDebuggingHost; #else typedef struct JITDebuggingHost JITDebuggingHost; #endif /* __cplusplus */ #endif /* __JITDebuggingHost_FWD_DEFINED__ */ /* header files for imported files */ #include "msdbg.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_jit_0000_0000 */ /* [local] */ #define JIT_DEUBUGGER_SHARED_MEMORY_PREFIX L"Local\\Microsoft_VS80_JIT_Debugger-" #define MAX_JIT_DEUBUGGER_SHARED_MEMORY_SIZE 0x4000 #define MAX_MARSHALLED_DEBUGGER_SIZE (0x4000 - offsetof(JIT_DEUBUGGER_SHARED_MEMORY, MarshalledDebuggerData)) #define JIT_DEBUGGER_MAGIC_NUMBER ((DWORD)'JIT8') struct JIT_DEUBUGGER_SHARED_MEMORY { DWORD dwMagicNumber; CLSID clsidDebugger; DWORD dwMarshalledDebuggerSize; BYTE MarshalledDebuggerData[ANYSIZE_ARRAY]; }; enum enum_JIT_FLAGS { JIT_FLAG_RPC = 0x1, JIT_FLAG_NOCRASH = 0x2, JIT_FLAG_DEBUGEXE = 0x4, JIT_FLAG_SELECT_ENGINES = 0x8 } ; typedef DWORD JIT_FLAGS; typedef struct tagCRASHING_PROGRAM_INFO { GUID guidEngine; DWORD dwProcessId; UINT64 ProgramId; LPCOLESTR szExceptionText; JIT_FLAGS JitFlags; IDebugSetJITEventCallback2 *pSetEventCallback; } CRASHING_PROGRAM_INFO; extern RPC_IF_HANDLE __MIDL_itf_jit_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_jit_0000_0000_v0_0_s_ifspec; #ifndef __IDebugIDEJIT2_INTERFACE_DEFINED__ #define __IDebugIDEJIT2_INTERFACE_DEFINED__ /* interface IDebugIDEJIT2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IDebugIDEJIT2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("B2F73449-98EA-4866-90A0-425837FC5E23") IDebugIDEJIT2 : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE AttachJITDebugger( /* [in] */ __RPC__in_opt IDebugProcess2 *pProcess, /* [in] */ __RPC__in_opt IDebugProgram2 *pJITProgram, /* [in] */ JIT_FLAGS JitFlags) = 0; }; #else /* C style interface */ typedef struct IDebugIDEJIT2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDebugIDEJIT2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDebugIDEJIT2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IDebugIDEJIT2 * This); HRESULT ( STDMETHODCALLTYPE *AttachJITDebugger )( IDebugIDEJIT2 * This, /* [in] */ __RPC__in_opt IDebugProcess2 *pProcess, /* [in] */ __RPC__in_opt IDebugProgram2 *pJITProgram, /* [in] */ JIT_FLAGS JitFlags); END_INTERFACE } IDebugIDEJIT2Vtbl; interface IDebugIDEJIT2 { CONST_VTBL struct IDebugIDEJIT2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDebugIDEJIT2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDebugIDEJIT2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDebugIDEJIT2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDebugIDEJIT2_AttachJITDebugger(This,pProcess,pJITProgram,JitFlags) \ ( (This)->lpVtbl -> AttachJITDebugger(This,pProcess,pJITProgram,JitFlags) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDebugIDEJIT2_INTERFACE_DEFINED__ */ #ifndef __IDebugJIT2_INTERFACE_DEFINED__ #define __IDebugJIT2_INTERFACE_DEFINED__ /* interface IDebugJIT2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IDebugJIT2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("2ea4c00d-7156-4f8e-b990-fb4271147617") IDebugJIT2 : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE JITDebug( /* [in] */ CRASHING_PROGRAM_INFO CrashingProgram) = 0; }; #else /* C style interface */ typedef struct IDebugJIT2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDebugJIT2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDebugJIT2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IDebugJIT2 * This); HRESULT ( STDMETHODCALLTYPE *JITDebug )( IDebugJIT2 * This, /* [in] */ CRASHING_PROGRAM_INFO CrashingProgram); END_INTERFACE } IDebugJIT2Vtbl; interface IDebugJIT2 { CONST_VTBL struct IDebugJIT2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDebugJIT2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDebugJIT2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDebugJIT2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDebugJIT2_JITDebug(This,CrashingProgram) \ ( (This)->lpVtbl -> JITDebug(This,CrashingProgram) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDebugJIT2_INTERFACE_DEFINED__ */ #ifndef __IDebugRuntimeJITServerProvider2_INTERFACE_DEFINED__ #define __IDebugRuntimeJITServerProvider2_INTERFACE_DEFINED__ /* interface IDebugRuntimeJITServerProvider2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IDebugRuntimeJITServerProvider2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("e7f35f78-362c-4d8a-8f76-3a7dbae0a237") IDebugRuntimeJITServerProvider2 : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetRuntimeJITSession( /* [out] */ __RPC__deref_out_opt IDebugJIT2 **ppJITServer) = 0; virtual HRESULT STDMETHODCALLTYPE IsAvailable( void) = 0; }; #else /* C style interface */ typedef struct IDebugRuntimeJITServerProvider2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDebugRuntimeJITServerProvider2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDebugRuntimeJITServerProvider2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IDebugRuntimeJITServerProvider2 * This); HRESULT ( STDMETHODCALLTYPE *GetRuntimeJITSession )( IDebugRuntimeJITServerProvider2 * This, /* [out] */ __RPC__deref_out_opt IDebugJIT2 **ppJITServer); HRESULT ( STDMETHODCALLTYPE *IsAvailable )( IDebugRuntimeJITServerProvider2 * This); END_INTERFACE } IDebugRuntimeJITServerProvider2Vtbl; interface IDebugRuntimeJITServerProvider2 { CONST_VTBL struct IDebugRuntimeJITServerProvider2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDebugRuntimeJITServerProvider2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDebugRuntimeJITServerProvider2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDebugRuntimeJITServerProvider2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDebugRuntimeJITServerProvider2_GetRuntimeJITSession(This,ppJITServer) \ ( (This)->lpVtbl -> GetRuntimeJITSession(This,ppJITServer) ) #define IDebugRuntimeJITServerProvider2_IsAvailable(This) \ ( (This)->lpVtbl -> IsAvailable(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDebugRuntimeJITServerProvider2_INTERFACE_DEFINED__ */ #ifndef __IDebugSetJITEventCallback2_INTERFACE_DEFINED__ #define __IDebugSetJITEventCallback2_INTERFACE_DEFINED__ /* interface IDebugSetJITEventCallback2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IDebugSetJITEventCallback2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("92DCA9C3-37A3-4498-8466-4C57EA885E49") IDebugSetJITEventCallback2 : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetJITEvent( void) = 0; }; #else /* C style interface */ typedef struct IDebugSetJITEventCallback2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDebugSetJITEventCallback2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDebugSetJITEventCallback2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IDebugSetJITEventCallback2 * This); HRESULT ( STDMETHODCALLTYPE *SetJITEvent )( IDebugSetJITEventCallback2 * This); END_INTERFACE } IDebugSetJITEventCallback2Vtbl; interface IDebugSetJITEventCallback2 { CONST_VTBL struct IDebugSetJITEventCallback2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDebugSetJITEventCallback2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDebugSetJITEventCallback2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDebugSetJITEventCallback2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDebugSetJITEventCallback2_SetJITEvent(This) \ ( (This)->lpVtbl -> SetJITEvent(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDebugSetJITEventCallback2_INTERFACE_DEFINED__ */ #ifndef __IDebugProgramJIT2_INTERFACE_DEFINED__ #define __IDebugProgramJIT2_INTERFACE_DEFINED__ /* interface IDebugProgramJIT2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IDebugProgramJIT2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("87379803-2fad-4801-abdf-218b5d2f076f") IDebugProgramJIT2 : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetJITCallback( /* [out] */ __RPC__deref_out_opt IDebugSetJITEventCallback2 **ppCallback) = 0; }; #else /* C style interface */ typedef struct IDebugProgramJIT2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDebugProgramJIT2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDebugProgramJIT2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IDebugProgramJIT2 * This); HRESULT ( STDMETHODCALLTYPE *GetJITCallback )( IDebugProgramJIT2 * This, /* [out] */ __RPC__deref_out_opt IDebugSetJITEventCallback2 **ppCallback); END_INTERFACE } IDebugProgramJIT2Vtbl; interface IDebugProgramJIT2 { CONST_VTBL struct IDebugProgramJIT2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDebugProgramJIT2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDebugProgramJIT2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDebugProgramJIT2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDebugProgramJIT2_GetJITCallback(This,ppCallback) \ ( (This)->lpVtbl -> GetJITCallback(This,ppCallback) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDebugProgramJIT2_INTERFACE_DEFINED__ */ #ifndef __IJITDebuggingHost2_INTERFACE_DEFINED__ #define __IJITDebuggingHost2_INTERFACE_DEFINED__ /* interface IJITDebuggingHost2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IJITDebuggingHost2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("42ef9f29-7777-42ed-ba74-944aefd663da") IJITDebuggingHost2 : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE JITAsLoggedInUser( /* [in] */ CRASHING_PROGRAM_INFO CrashingProgram) = 0; }; #else /* C style interface */ typedef struct IJITDebuggingHost2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IJITDebuggingHost2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IJITDebuggingHost2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IJITDebuggingHost2 * This); HRESULT ( STDMETHODCALLTYPE *JITAsLoggedInUser )( IJITDebuggingHost2 * This, /* [in] */ CRASHING_PROGRAM_INFO CrashingProgram); END_INTERFACE } IJITDebuggingHost2Vtbl; interface IJITDebuggingHost2 { CONST_VTBL struct IJITDebuggingHost2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IJITDebuggingHost2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IJITDebuggingHost2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IJITDebuggingHost2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IJITDebuggingHost2_JITAsLoggedInUser(This,CrashingProgram) \ ( (This)->lpVtbl -> JITAsLoggedInUser(This,CrashingProgram) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IJITDebuggingHost2_INTERFACE_DEFINED__ */ #ifndef __IDebugWrappedJITDebugger2_INTERFACE_DEFINED__ #define __IDebugWrappedJITDebugger2_INTERFACE_DEFINED__ /* interface IDebugWrappedJITDebugger2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IDebugWrappedJITDebugger2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("4dfa78ac-43c1-4de5-8179-3c3ec9010a31") IDebugWrappedJITDebugger2 : public IDebugJIT2 { public: virtual HRESULT STDMETHODCALLTYPE GetName( /* [out] */ __RPC__deref_out_opt BSTR *pbstrName) = 0; }; #else /* C style interface */ typedef struct IDebugWrappedJITDebugger2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDebugWrappedJITDebugger2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDebugWrappedJITDebugger2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IDebugWrappedJITDebugger2 * This); HRESULT ( STDMETHODCALLTYPE *JITDebug )( IDebugWrappedJITDebugger2 * This, /* [in] */ CRASHING_PROGRAM_INFO CrashingProgram); HRESULT ( STDMETHODCALLTYPE *GetName )( IDebugWrappedJITDebugger2 * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrName); END_INTERFACE } IDebugWrappedJITDebugger2Vtbl; interface IDebugWrappedJITDebugger2 { CONST_VTBL struct IDebugWrappedJITDebugger2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDebugWrappedJITDebugger2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDebugWrappedJITDebugger2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDebugWrappedJITDebugger2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDebugWrappedJITDebugger2_JITDebug(This,CrashingProgram) \ ( (This)->lpVtbl -> JITDebug(This,CrashingProgram) ) #define IDebugWrappedJITDebugger2_GetName(This,pbstrName) \ ( (This)->lpVtbl -> GetName(This,pbstrName) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDebugWrappedJITDebugger2_INTERFACE_DEFINED__ */ #ifndef __IDebugEngineJITSettings2_INTERFACE_DEFINED__ #define __IDebugEngineJITSettings2_INTERFACE_DEFINED__ /* interface IDebugEngineJITSettings2 */ /* [unique][uuid][object] */ typedef struct tagWRAPPED_DEBUGGER_ARRAY { DWORD dwCount; IDebugWrappedJITDebugger2 **Members; } WRAPPED_DEBUGGER_ARRAY; EXTERN_C const IID IID_IDebugEngineJITSettings2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("b9f3fdf1-7b6d-4899-bd94-72e4d4acd2e1") IDebugEngineJITSettings2 : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE QueryIsEnabled( void) = 0; virtual HRESULT STDMETHODCALLTYPE Enable( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetWrappedDebuggers( /* [out] */ __RPC__out WRAPPED_DEBUGGER_ARRAY *pWrappedDebuggers) = 0; }; #else /* C style interface */ typedef struct IDebugEngineJITSettings2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDebugEngineJITSettings2 * This, /* [in] */ __RPC__in REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDebugEngineJITSettings2 * This); ULONG ( STDMETHODCALLTYPE *Release )( IDebugEngineJITSettings2 * This); HRESULT ( STDMETHODCALLTYPE *QueryIsEnabled )( IDebugEngineJITSettings2 * This); HRESULT ( STDMETHODCALLTYPE *Enable )( IDebugEngineJITSettings2 * This); HRESULT ( STDMETHODCALLTYPE *GetWrappedDebuggers )( IDebugEngineJITSettings2 * This, /* [out] */ __RPC__out WRAPPED_DEBUGGER_ARRAY *pWrappedDebuggers); END_INTERFACE } IDebugEngineJITSettings2Vtbl; interface IDebugEngineJITSettings2 { CONST_VTBL struct IDebugEngineJITSettings2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDebugEngineJITSettings2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDebugEngineJITSettings2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDebugEngineJITSettings2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDebugEngineJITSettings2_QueryIsEnabled(This) \ ( (This)->lpVtbl -> QueryIsEnabled(This) ) #define IDebugEngineJITSettings2_Enable(This) \ ( (This)->lpVtbl -> Enable(This) ) #define IDebugEngineJITSettings2_GetWrappedDebuggers(This,pWrappedDebuggers) \ ( (This)->lpVtbl -> GetWrappedDebuggers(This,pWrappedDebuggers) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDebugEngineJITSettings2_INTERFACE_DEFINED__ */ #ifndef __JITLib_LIBRARY_DEFINED__ #define __JITLib_LIBRARY_DEFINED__ /* library JITLib */ /* [uuid] */ EXTERN_C const IID LIBID_JITLib; EXTERN_C const CLSID CLSID_IDEJITServer; #ifdef __cplusplus class DECLSPEC_UUID("46D26D39-F692-4f6c-8153-086E6DA9F059") IDEJITServer; #endif EXTERN_C const CLSID CLSID_JITDebuggingHost; #ifdef __cplusplus class DECLSPEC_UUID("36bbb745-0999-4fd8-a538-4d4d84e4bd09") JITDebuggingHost; #endif #endif /* __JITLib_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree( unsigned long *, BSTR * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
/* * Copyright 2016-2018 Crown Copyright * * 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 uk.gov.gchq.gaffer.operation.serialisation; import com.fasterxml.jackson.core.type.TypeReference; import uk.gov.gchq.gaffer.commonutil.iterable.CloseableIterable; import uk.gov.gchq.gaffer.data.GroupCounts; import uk.gov.gchq.gaffer.data.element.Edge; import uk.gov.gchq.gaffer.data.element.id.EntityId; import uk.gov.gchq.gaffer.data.graph.Walk; import uk.gov.gchq.gaffer.operation.data.EntitySeed; /** * Utility class which contains a number of inner classes for different {@link TypeReference}s * used by the Gaffer project to denote the output type of an {@link uk.gov.gchq.gaffer.operation.io.Output}. * * @see uk.gov.gchq.gaffer.operation.io.Output#getOutputTypeReference() */ public final class TypeReferenceImpl { private TypeReferenceImpl() { } public static class CountGroups extends TypeReference<GroupCounts> { } public static class Void extends TypeReference<java.lang.Void> { } public static class String extends TypeReference<java.lang.String> { } public static class Long extends TypeReference<java.lang.Long> { } public static class Integer extends TypeReference<java.lang.Integer> { } public static class Object extends TypeReference<java.lang.Object> { } public static class Element extends TypeReference<uk.gov.gchq.gaffer.data.element.Element> { } public static class Boolean extends TypeReference<java.lang.Boolean> { } public static class CloseableIterableObj extends TypeReference<CloseableIterable<?>> { } public static class IterableObj extends TypeReference<Iterable<?>> { } public static <T> TypeReference<T> createExplicitT() { return (TypeReference) new TypeReferenceImpl.Object(); } public static <T> TypeReference<Iterable<? extends T>> createIterableT() { return (TypeReference) new IterableObj(); } public static <T> TypeReference<CloseableIterable<? extends T>> createCloseableIterableT() { return (TypeReference) new CloseableIterableObj(); } public static <T> TypeReference<Iterable<T>> createIterableExplicitT() { return (TypeReference) new IterableObj(); } public static class IterableElement extends TypeReference<Iterable<? extends uk.gov.gchq.gaffer.data.element.Element>> { } public static class CloseableIterableElement extends TypeReference<CloseableIterable<? extends uk.gov.gchq.gaffer.data.element.Element>> { } public static class CloseableIterableEntityId extends TypeReference<CloseableIterable<? extends EntityId>> { } public static class CloseableIterableEntitySeed extends TypeReference<CloseableIterable<? extends uk.gov.gchq.gaffer.operation.data.EntitySeed>> { } public static class Exporter extends TypeReference<uk.gov.gchq.gaffer.operation.export.Exporter> { } public static class MapExporter extends TypeReference<java.util.LinkedHashMap<java.lang.String, uk.gov.gchq.gaffer.operation.export.Exporter>> { } public static class Map extends TypeReference<java.util.LinkedHashMap> { } public static class MapStringSet extends TypeReference<java.util.Map<String, Set<Object>>> { } public static class Operations extends TypeReference<Set<Class<uk.gov.gchq.gaffer.operation.Operation>>> { } public static class JobDetail extends TypeReference<uk.gov.gchq.gaffer.jobtracker.JobDetail> { } public static class JobDetailIterable extends TypeReference<CloseableIterable<uk.gov.gchq.gaffer.jobtracker.JobDetail>> { } public static class Stream<T> extends TypeReference<java.util.stream.Stream<T>> { } public static class Array<T> extends TypeReference<T[]> { } public static class List<T> extends TypeReference<java.util.List<T>> { } public static class Set<T> extends TypeReference<java.util.Set<T>> { } public static class IterableEntitySeed extends TypeReference<Iterable<? extends EntitySeed>> { } public static class IterableMap extends TypeReference<Iterable<? extends java.util.Map<java.lang.String, java.lang.Object>>> { } public static class IterableString extends TypeReference<Iterable<? extends java.lang.String>> { } public static class IterableObject extends TypeReference<Iterable<? extends java.lang.Object>> { } public static class ListString extends TypeReference<java.util.List<java.lang.String>> { } public static class IterableIterableEdge extends TypeReference<Iterable<Iterable<Edge>>> { } public static class IterableEdge extends TypeReference<Iterable<Edge>> { } public static class IterableListEdge extends TypeReference<Iterable<java.util.List<Edge>>> { } public static class IterableWalk extends TypeReference<Iterable<Walk>> { } }
def _scanRelease(self, release:PyPackageRelease, statistics:StageStatisticsData) -> map[str:ReleaseFileDescriptor]: release_file_name=release.getReleaseFileName() if self._cache_folder is not None: destFile=os.path.join(self._cache_folder,release_file_name) else: destFile=os.path.join(self._getTempFolder(),release_file_name) if not os.path.exists(destFile): try: self.__logger.debug("Downloading release file {} to {}".format(release_file_name,destFile)) Utils.downloadUrl(release.getDownloadUrl(),destFile) except Exception as e: raise AnalysisException("Unable to download release file content") from e else: self.__logger.debug("Using cashed release file {}".format(destFile)) extract_folder=os.path.join(self._getTempFolder(),"release__"+release_file_name+"___"+release.getReleaseFileType()) self.__logger.debug("Extracting release file {} to {}".format(release_file_name,extract_folder)) file_count=self.__extractReleaseFile(release.getReleaseFileName(),destFile,extract_folder) statistics.addStatistic("processed_files",file_count) return self.__collectFilesHashes(extract_folder)
<gh_stars>0 package open.iot.server.service.security.model.token; import java.io.Serializable; public interface JwtToken extends Serializable { String getToken(); }
def register_to(backend, oauth, client_base=None): if client_base is None: client_base = _get_oauth_client_cls(oauth) config = backend.OAUTH_CONFIG.copy() if client_base: class RemoteApp(client_base, backend): pass config['client_cls'] = RemoteApp return oauth.register(backend.OAUTH_NAME, overwrite=True, **config)
def new_safe_logical_unit(self, um: UnitModel, unit_type: type[LT], logger: AmpelLogger, _chan: None | ChannelId = None ) -> LT: if logger.verbose: logger.log(VERBOSE, f"Instantiating unit {um.unit}") buf_hdlr = ChanRecordBufHandler(logger.level, _chan, {'unit': um.unit}) if _chan \ else DefaultRecordBufferingHandler(logger.level, {'unit': um.unit}) unit = self.new_logical_unit( model = um, logger = AmpelLogger.get_logger( base_flag = (getattr(logger, 'base_flag', 0) & ~LogFlag.CORE) | LogFlag.UNIT, console = len(logger.handlers) == 1, handlers = [buf_hdlr] ), sub_type = unit_type ) setattr(unit, '_buf_hdlr', buf_hdlr) return unit
def write_data(self, data): self.dc.value(1) self.cs.value(0) self.spi.write(data) self.cs.value(1)
/** * Created by Nathan Dunn on 12/17/14. */ public class DataGenerator { public final static String SEQUENCE_PREFIX = "LG"; public static String[] organisms = { "Zebrafish" ,"Alligator Pipefish" ,"Bloody Stickleback" ,"Brook Stickleback" ,"Three-spined Stickleback" ,"Amur Stickleback" ,"Spinach Stickleback" ,"Bean weevil" ,"Flour mite" ,"May conehead" ,"Wheat curl mite" ,"Sea spiders" ,"Lesser wax moth" ,"Acacia psyllid" ,"Panamanian leafcutter ant" ,"Bluegreen aphid" ,"Pea aphid" ,"Pale spruce gall adelgid" ,"Balsam woolly adelgid" ,"Hemlock woolly adelgid" ,"Yellow fever mosquito" ,"Asian tiger mosquito" ,"Eastern salt marsh mosquito" ,"Floodwater mosquito" ,"Small tortoiseshell" ,"Emerald ash borer" ,"Catalan furry blue" ,"Black cutworm" ,"Turnip moth" ,"Citrus spiny whitefly" ,"Brown legged grain mite" ,"Striped ground cricket" ,"Southern ground cricket" ,"Lesser mealworm" ,"Lone star tick" ,"Cayenne tick" ,"Bont tick" ,"The Gulf-Coast Tick" ,"Red-banded sand wasp" ,"Large raspberry aphid" ,"Emerald cockroach wasp" ,"Mediterranean flour moth" ,"Squash bug" ,"South American fruit fly" ,"Mexican fruit fly" ,"West Indian fruit fly" ,"Guava fruitfly" ,"Caribbean fruitfly" ,"Sri Lankan relict ant" ,"Seashore earwig" ,"Maritime earwig" ,"Two striped walking stick" ,"African malaria mosquito" ,"African malaria mosquito" ,"Common malaria mosquito" ,"Asian malaria mosquito" ,"Asian longhorned beetle" ,"Indian muga silkmoth" ,"Tussore silk moth" ,"Chinese oak silkmoth" ,"Japanese oak silkmoth" ,"Boll weevil" ,"Webspinner" ,"Soybean aphid" ,"Cotton aphid" ,"Small raspberry aphid" ,"Giant honeybee" ,"Red dwarf honey bee" ,"Honey bee" ,"East Asian elm sawfly" ,"European garden spider" ,"African giant black millipede" ,"Orb-weaving spider" ,"Brine shrimp" ,"Waterlouse" ,"Turnip sawfly" ,"Sydney funnel spider" ,"Leafcutter ant" ,"Leafcutter ant" ,"Texas leafcutter ant" ,"Silver Y moth" }; public static List<String> getOrganisms() { List<String> arrayList = new ArrayList<>(); for(String o : organisms){ arrayList.add(o); } return arrayList; } public static List<String> getSequences(int numberToGet) { List<String> sequences = new ArrayList<>(); for(int i = 1 ; i < numberToGet+1 ;i++){ sequences.add(SEQUENCE_PREFIX+i); } return sequences; } public static List<String> getAnnotations() { List<String> annotations = new ArrayList<>(); return annotations; } public static List<String> getUsers() { List<String> users = new ArrayList<>(); users.add("Yvone Patague"); users.add("Darcel Ostendorf"); users.add("Yolande Boisvert"); users.add("Fawn Pettyjohn"); users.add("Shantel Bufford"); users.add("Edwina Haag"); users.add("Glady Larimer"); users.add("Marylynn Marez"); users.add("Cherly Hanshaw"); users.add("Margeret Vasta"); users.add("Vickey Wolfrum"); users.add("Cindy Kirshner"); users.add("Duncan Hallberg"); users.add("Art Villagomez"); users.add("Ryann Noakes"); users.add("Branda Clower"); users.add("Nora Siemers"); users.add("Marita Dagostino"); users.add("Anastacia Hevey"); users.add("Luann Celaya"); users.add("Yvone Patague"); users.add("Darcel Ostendorf"); users.add("Yolande Boisvert"); users.add("Fawn Pettyjohn"); users.add("Shantel Bufford"); users.add("Edwina Haag"); users.add("Glady Larimer"); users.add("Marylynn Marez"); users.add("Cherly Hanshaw"); users.add("Margeret Vasta"); users.add("Vickey Wolfrum"); users.add("Cindy Kirshner"); users.add("Duncan Hallberg"); users.add("Art Villagomez"); users.add("Ryann Noakes"); users.add("Branda Clower"); users.add("Nora Siemers"); users.add("Marita Dagostino"); users.add("Anastacia Hevey"); users.add("Luann Celaya"); return users; } public static void populateOrganismList(ListBox organismList) { organismList.clear(); for(String organism : organisms){ organismList.addItem(organism); } } public static TreeItem generateTreeItem(String geneName) { HTML html ; boolean isGene = Math.random()>0.5; if(isGene){ html = new HTML(geneName +" <div class='label label-success'>Gene</div>"); } else{ html = new HTML(geneName +" <div class='label label-warning'>Pseudogene</div>"); } TreeItem sox9b = new TreeItem(html); int i =0 ; sox9b.addItem(createTranscript(geneName, isGene,i++)); if(Math.random()>0.5){ sox9b.addItem(createTranscript(geneName, isGene,i++)); } sox9b.setState(true); return sox9b; } public static TreeItem createTranscript(String geneName, boolean isGene,int index){ Integer randomLength = (int) Math.round(Math.random()*5000.0); TreeItem treeItem = new TreeItem(); HTML transcriptHTML ; if(isGene){ transcriptHTML = new HTML(geneName + "-00"+index+ " <div class='label label-success' style='display:inline;'>mRNA</div><div class='badge pull-right' style='display:inline;'>"+randomLength+"</div>"); } else{ transcriptHTML = new HTML(geneName + "-00"+index+ " <div class='label label-warning' style='display:inline;'>Transcript</div><div class='badge pull-right' style='display:inline;'>"+randomLength+"</div>"); } if(Math.random()>0.7){ transcriptHTML.setHTML(transcriptHTML.getHTML()+"<div class='label label-danger' style='display:inline;'>Stop Codon</div>"); } treeItem.setWidget(transcriptHTML); int j = 0 ; treeItem.addItem(createExon(geneName + "-00"+index,j++)); if(Math.random()>0.2){ treeItem.addItem(createExon(geneName + "-00"+index,j++)); } if(Math.random()>0.2){ treeItem.addItem(createExon(geneName + "-00"+index,j++)); } treeItem.setState(true); return treeItem ; } private static HTML createExon(String geneName,int index) { Integer randomStart = (int) Math.round(Math.random()*5000.0); Integer randomLength = (int) Math.round(Math.random()*500.0); Integer randomFinish = randomStart + randomLength; return new HTML(geneName + "-00-"+index+ " <div class='label label-info' style='display:inline;'>Exon</div><div class='badge pull-right' style='display:inline;'>"+randomStart + "-"+randomFinish+"</div>"); } public static void generateSequenceRow(FlexTable sequenceTable, int i) { Anchor link = new Anchor(SEQUENCE_PREFIX+i); sequenceTable.setWidget(i, 0, link); sequenceTable.setHTML(i, 1, Math.rint(Math.random() * 100) + ""); // configurationTable.setHTML(i, 2, Math.rint(Math.random() * 100) + ""); Button button = new Button("Annotate"); // Button button2 = new Button("Details"); HorizontalPanel actionPanel = new HorizontalPanel(); actionPanel.add(button); // actionPanel.add(button2); sequenceTable.setWidget(i, 2, actionPanel); } public static void populateOrganismTable(FlexTable organismTable) { int i = 0 ; for(String organism : organisms){ Anchor link = new Anchor(organism); organismTable.setWidget(i, 0, link); organismTable.setHTML(i, 1, Math.rint(Math.random() * 100) + ""); Button button = new Button("Set"); // Button button2 = new Button("Details"); HorizontalPanel actionPanel = new HorizontalPanel(); actionPanel.add(button); // actionPanel.add(button2); organismTable.setWidget(i, 2, actionPanel); // organismTable.createOrganismRow(organism,i++); ++i ; } } public static void populateSequenceList(ListBox sequenceList) { List<String> sequences = getSequences(40); for(String seq : sequences){ sequenceList.addItem(seq); } } public static List<String> getGroups() { List<String> groups = new ArrayList<>(); groups.add("USDA i5K"); groups.add("Augmented Integration Tactical"); groups.add("Australian Training Wholesale"); groups.add("Automotive Sports"); groups.add("Bailey Financial Future Equipment"); groups.add("British Speciality Research"); groups.add("Casey Holding Containers"); groups.add("Chemical Apex Realizations"); groups.add("Diaz Fabrication Development"); groups.add("Digital Logistics"); groups.add("Dynamics Of Moscow"); groups.add("Fuentes Healthy Pharmecutical Integration"); groups.add("Fuller Technology Networks"); groups.add("Genetic Physiotronics"); groups.add("Hawkins Equity Solutions"); groups.add("Hill Unlimited Medical"); groups.add("Hurley Soft"); groups.add("Marquez Photologistics"); groups.add("Marsh Motors"); groups.add("Mcneil Chemical Instruments"); groups.add("Norris Semiconductor Of Kiev"); groups.add("Progressive Manufacturing Leasing"); groups.add("Russian Technology Horizons"); groups.add("Spanish Housing"); groups.add("Strategic Training Corporation"); groups.add("Waters Financial Metals"); groups.add("Archon Rose Five"); groups.add("Baron Wraith Guild"); groups.add("Coffin Mind Legion"); groups.add("Crimson Werewolf Guild"); groups.add("Dog Altar Seven"); groups.add("Drake Soul Hundred"); groups.add("Enchanted Fortress School"); groups.add("Gold Demon Guild"); groups.add("Master Phoenix Guild"); groups.add("Mystic Cheetah Alliance"); groups.add("Mystic Chime Guild"); groups.add("Phantom Hawk Guild"); groups.add("Randy Hippocampus Band"); groups.add("Recognized Totem Family"); groups.add("The Basilisk Confederation"); groups.add("The Phylactery College"); groups.add("The Serpent Thousand"); groups.add("Totem Soul Posse"); groups.add("Warrior Coffin Guild"); groups.add("Wraith Ambassador Conspiracy"); groups.add("Collective of Worlds"); groups.add("Constellation's Republic"); groups.add("Federated Directorate of Constellations"); groups.add("Federated Directorate of Galaxies"); groups.add("Federation of Planets"); groups.add("Galaxies' Oligarcy"); groups.add("Galaxy's Confederacy"); groups.add("Grand Collective of Constellations"); groups.add("Heavenly Federation of Worlds"); groups.add("Mercantile Coalition of Constellations"); groups.add("Nation of Spheres"); groups.add("Perfected Plutocracy"); groups.add("Perfected Technocracy"); groups.add("Planets' Electorate"); groups.add("Solidarity of Stars"); groups.add("System's Union"); groups.add("Theocratic Constellations"); groups.add("Tyranical Government of Constellations"); groups.add("Unified Empire"); groups.add("Worlds' Solidarity"); return groups; } public static void populateTrackList(List<TrackInfo> trackInfoList) { trackInfoList.add(new TrackInfo("Official Gene Set v3.2","HTMLFeature",true)); trackInfoList.add(new TrackInfo("GeneID","HTMLFeature",true)); trackInfoList.add(new TrackInfo("Fgenesh","HTMLFeature",false)); trackInfoList.add(new TrackInfo("Cflo_OGSv3.3","HTMLFeature",true)); trackInfoList.add(new TrackInfo("NCBI ESTs","HTMLFeature",true)); for(int i = 0 ; i < 40 ; i++){ trackInfoList.add(new TrackInfo("Track" + i)); } } public static String[] sequenceTypes = { "All" ,"Gene" ,"Pseudogene" ,"mRNA" ,"miRNA" ,"tRNA" ,"rRNA" ,"ncRNA" ,"snRNA" ,"snoRNA" ,"repeat region" ,"transposable element" }; public static void populateTypeList(ListBox typeList) { for(String seq : sequenceTypes){ typeList.addItem(seq); } } }
<gh_stars>0 import matplotlib.pyplot as plt from matplotlib.image import imread # 画像表示のためのメソッド from os import path image_path = path.dirname(path.dirname(path.abspath(__file__))) + '/dataset/lena.png' img = imread(image_path) plt.imshow(img) plt.show()
ROLE OF TOPICAL APPLICATION OF NANO SILVER ON ULCER HEALING: A COMPARATIVE STUDY Background: The disruption of cellular flow of any tissue or its integrity cause wounds which associated with loss of function however, etiology is highly diverse. Among the etiological factors, they can be physical, chemical and surgical and even microbial injuries. Therefore, correction of damaged tissue or wound management plays a significant role in better quality of life to the patient Material & Methods: The present study was prospective comparative interventional study 100 Patients who had ulcers were enrolled from outdoor and from ward by simple random sampling. Clearance from Institutional Ethics Committee was taken before start of study. Written informed consent was taken from each study participant. Results: In the present study, among the povidone iodine group, 49 (98%) patients had slough on day 1st, 04 (8%) patients had slough after 1 week, 40 (80%) patients had slough after 2 weeks, 33 (66%) patients had slough after 3 weeks, 19 (38%) patients had slough after 4 weeks, 08 (16%) patients had slough after 5 weeks and 0 (0%) patients had slough after 6 weeks. In the nano silver group, 49 (98%) patients had slough on day 1st, 41 (82%) patients had slough after 1 week, 24 (48%) patients had slough after 2 weeks, 09 (18%) patients had slough after 3 weeks, 03 (06%) patients had slough after 4 weeks, 0 (0%) patients had slough after 5 weeks. We found statistically significant differences on the presence of slough after 2nd week onwards in both groups (p value < 0.05). Conclusions: We concluded from the present study that the topical application of nano silver gel for ulcer dressing shows faster and better healing in comparison to ulcer healing in povidone iodine group. In nano silver group 100% patients had granulation tissue by the end of 5th weeks and none of patients had slough by the end of 5th weeks. Key words: ulcer, healing, nano silver, povidone iodine.
/** * True if the string is an {@code int} and [0, 65535], false otherwise. * * @param s a string that might be a valid port number * @return True if the string is an {@code int} and [0, 65535], false otherwise. */ public static boolean isPort(String s) { if(isInt(s)) { int possiblePort = Integer.parseInt(s); return possiblePort >= 0 && possiblePort <= 65535; } return false; }
export { clearStorageSync } from '../unsupportedApi'
import {BufferEncoders, RSocketClient} from "rsocket-core"; import RSocketWebSocketClient from "rsocket-websocket-client"; import {decode, encode} from "msgpack-lite"; import Cookies from "js-cookie"; import {ISubscription, Payload, ReactiveSocket} from "rsocket-types"; import { apiLogsEnabled, INFINITY_STREAM_RSOCKET_CLIENT_NAME, RETRY_TIMEOUT_SECONDS, RSOCKET_DEFAULT_URL, RSOCKET_FUNCTION, RSOCKET_OPTIONS, RSOCKET_REQUEST_COUNT, STREAM_RSOCKET_CLIENT_NAME } from "../constants/ApiConstants"; import {Flowable} from "rsocket-flowable"; import {Dispatch, DispatchWithoutAction} from "react"; import moment from "moment"; import {isEmptyArray} from "../framework/extensions/extensions"; import {setInterval} from "timers"; import {ConnectionStatus} from "rsocket-types/ReactiveSocketTypes"; import {ServiceExceptionDispatch, ServiceExecutionException, ServiceResponse} from "../model/ApiTypes"; import {doNothing} from "../framework/constants/Constants"; import {TOKEN_COOKIE} from "../constants/Cookies"; import {DATE_TIME_FORMAT} from "../constants/DateTimeConstants"; import {development} from "../constants/Environment"; export const createServiceMethodRequest = (serviceId: string, methodId: string, requestData: any = null) => ({ serviceMethodCommand: { serviceId: serviceId, methodId: methodId, toString: () => `${serviceId}.${methodId}` }, requestData: requestData }); export const createFunctionRequest = (methodId: string, requestData: any = null) => ({ serviceMethodCommand: { serviceId: RSOCKET_FUNCTION, methodId: methodId, toString: () => `${RSOCKET_FUNCTION}.${methodId}` }, requestData: requestData }); const clients: PlatformClient[] = [] export class PlatformClient { protected static INSTANCE: PlatformClient; #subscriptions = new Set<ISubscription>(); #rsocketUrl: string; #connected: DispatchWithoutAction = doNothing; #failed: Dispatch<Error> = doNothing; #rsocket?: ReactiveSocket<any, any>; #name?: string; #defaultToken?: string; #reconnectionInterval?: NodeJS.Timeout; #connectionStatus: ConnectionStatus = {kind: "NOT_CONNECTED"}; private constructor(rsocketUrl: string) { this.#rsocketUrl = rsocketUrl; clients.push(this); } token = (token: string) => { this.#defaultToken = token; return this; }; connect = (name: string, connected: DispatchWithoutAction, failed: Dispatch<Error>) => { if (this.#connectionStatus.kind != "NOT_CONNECTED") { return } this.#name = name; this.#connected = connected; this.#failed = failed; this.#processConnection(name, connected, failed); }; disposeRsocket = () => { try { this.#subscriptions.forEach(subscription => { try { subscription.cancel() } catch (ignored) { console.warn(ignored) } }); this.#subscriptions.clear(); if (this.#name) { console.log(`${this.#name} subscriptions canceled`); } this.#closeRsocket() } catch (ignored) { console.warn(ignored) } }; requestResponse = (request: any, onSuccess: Dispatch<any> = doNothing, onError: Dispatch<any> = doNothing) => { const command = request.serviceMethodCommand; const token = this.#defaultToken || Cookies.get(TOKEN_COOKIE); const metadata = createFunctionRequest(command.methodId, token); const payload = { data: encode(request), metadata: encode(metadata) }; this.#rsocket!.requestResponse(payload) .map(this.#writePayload) .subscribe({ onComplete: (response: ServiceResponse) => { this.#log(() => `[requestResponse(${command}): ${this.#rsocketUrl}]: Done at ${moment().format(DATE_TIME_FORMAT)}`); this.#onResponse(response, onSuccess, onError); }, onError: (error: Error) => { console.error(error); onError(error) }, onSubscribe: () => { this.#log(() => `[requestResponse(${command}): ${this.#rsocketUrl}]: Start at: ${moment().format(DATE_TIME_FORMAT)}`); } }) }; infinityRequestStream = (request: any, onNext: Dispatch<any> = doNothing, onError: Dispatch<any> = doNothing) => this.requestStream(request, onNext, doNothing, onError); requestStream = (request: any, onNext: Dispatch<any> = doNothing, onComplete: DispatchWithoutAction = doNothing, onError: Dispatch<any> = doNothing) => { let subscription: ISubscription | null; const command = request.serviceMethodCommand; const token = this.#defaultToken || Cookies.get(TOKEN_COOKIE); const metadata = createFunctionRequest(command.methodId, token); const payload = { data: encode(request), metadata: encode(metadata) }; this.#rsocket!.requestStream(payload) .map(this.#writePayload) .subscribe({ onComplete: () => { this.#log(() => `[requestStream(${command}): ${this.#rsocketUrl}]: Complete at: ${moment().format(DATE_TIME_FORMAT)}`); if (subscription) { this.#subscriptions.delete(subscription); subscription = null; } onComplete(); }, onError: (error: Error) => { console.error(error); if (subscription) { this.#subscriptions.delete(subscription); subscription = null; } onError(error) }, onNext: (response: ServiceResponse) => { this.#log(() => `[requestStream(${command}): ${this.#rsocketUrl}]: Event at ${moment().format(DATE_TIME_FORMAT)}`); this.#onResponse(response, onNext, onError) }, onSubscribe: (currentSubscription: ISubscription) => { this.#log(() => `[requestStream(${command}): ${this.#rsocketUrl}]: Start at: ${moment().format(DATE_TIME_FORMAT)}`); subscription = currentSubscription; this.#subscriptions.add(subscription); subscription.request(RSOCKET_REQUEST_COUNT); } } ); return () => { if (!subscription) { return; } subscription.cancel(); this.#subscriptions.delete(subscription); subscription = null; } }; chunkedRequest = (chunks: any[], onComplete: DispatchWithoutAction = doNothing, onError: Dispatch<any> = doNothing) => { const chunkValues = chunks; let subscription: ISubscription | null; const flowable = new Flowable<Payload<any, any>>(subscriber => subscriber.onSubscribe({ cancel: doNothing, request: count => { while (count--) { if (isEmptyArray(chunkValues)) { subscriber.onComplete(); return } const next = chunkValues.shift(); const token = this.#defaultToken || Cookies.get(TOKEN_COOKIE); const metadata = createFunctionRequest(next!.serviceMethodCommand.methodId, token); subscriber.onNext({ data: encode(next), metadata: encode(metadata) }); } } })); (this.#rsocket!.requestChannel(flowable).map(this.#writePayload) as Flowable<any>) .subscribe({ onComplete: () => { if (subscription) { this.#subscriptions.delete(subscription); subscription = null; } onComplete() }, onError: (error: Error) => { console.error(error); if (subscription) { this.#subscriptions.delete(subscription); subscription = null; } onError(error) }, onSubscribe: (currentSubscription: ISubscription) => { subscription = currentSubscription; this.#subscriptions.add(subscription); subscription.request(chunkValues.length); } } ); return () => { if (!subscription) { return; } subscription.cancel(); this.#subscriptions.delete(subscription); subscription = null; } }; fireAndForget = (request: any) => { const command = request.serviceMethodCommand; this.#log(() => `[fireAndForget(${command}): ${this.#rsocketUrl}]: Executed at: ${moment().format(DATE_TIME_FORMAT)}`); const token = this.#defaultToken || Cookies.get(TOKEN_COOKIE); const metadata = createFunctionRequest(command.methodId, token); const payload = { data: encode(request), metadata: encode(metadata) }; this.#rsocket!.fireAndForget(payload) }; #writePayload = (payload: any) => payload.data ? decode(payload.data as number[]) : null; #processConnection = (name: string, connected: () => void, failed: (value: Error) => void) => { new RSocketClient({ setup: RSOCKET_OPTIONS, transport: new RSocketWebSocketClient({url: this.#rsocketUrl}, BufferEncoders) }) .connect() .then(socket => { console.log(`${name} successfully connected to ${this.#rsocketUrl}`); this.#rsocket = socket; socket.connectionStatus().subscribe({ onSubscribe: (subscription: ISubscription) => subscription.request(RSOCKET_REQUEST_COUNT), onNext: status => this.#connectionStatus = status, onError: error => this.#connectionStatus = {kind: "ERROR", error: error}, onComplete: () => this.#connectionStatus = {kind: "CLOSED"} }); this.#startConnectionListening(); connected(); }, error => { console.error(error); this.#connectionStatus = {kind: "ERROR", error: error}; this.#startConnectionListening(); failed(error) }); }; #startConnectionListening = () => { if (this.#reconnectionInterval) { return; } const connected = () => { this.#reconnectionInterval && clearInterval(this.#reconnectionInterval); window.location.reload() }; this.#reconnectionInterval = setInterval(() => { switch (PlatformClient.platformClient().#connectionStatus.kind) { case "NOT_CONNECTED": console.log(`${this.#name} trying reconnect to ${this.#rsocketUrl}...`); this.#processConnection(this.#name!, connected, this.#failed); break; case "CLOSED": console.log(`${this.#name} trying reconnect to ${this.#rsocketUrl}...`); this.#processConnection(this.#name!, connected, this.#failed); break; case "ERROR": console.log(`${this.#name} trying reconnect to ${this.#rsocketUrl}...`); this.#processConnection(this.#name!, connected, this.#failed); break; } }, RETRY_TIMEOUT_SECONDS * 1000); }; #onResponse = (response: ServiceResponse, onSuccess: Dispatch<any>, onError: ServiceExceptionDispatch) => { const exception = response.serviceExecutionException; if (!exception) { onSuccess(response.responseData); return; } console.error(exception); const {errorCode, errorMessage, stackTrace} = response.serviceExecutionException; onError(new ServiceExecutionException(errorCode, errorMessage, stackTrace)); }; #closeRsocket = () => { if (!this.#rsocket) { return; } try { this.#rsocket.close(); console.log(`${this.#name} successfully disconnected from ${this.#rsocketUrl}`); } catch (exception) { console.warn(exception); } }; #log = (message: () => string) => { if (development() && apiLogsEnabled()) { console.log(message()); } }; static platformClient = (): PlatformClient => { PlatformClient.INSTANCE = PlatformClient.INSTANCE || new PlatformClient(RSOCKET_DEFAULT_URL); return PlatformClient.INSTANCE; }; static newPlatformClient = (url: string = RSOCKET_DEFAULT_URL): PlatformClient => new PlatformClient(url); } export const requestResponse = (request: any, onComplete: Dispatch<any> = doNothing, onError: Dispatch<any> = doNothing) => PlatformClient.platformClient().requestResponse(request, onComplete, onError); export const requestStream = (request: any, onNext: Dispatch<any> = doNothing, onComplete: DispatchWithoutAction = doNothing, onError: Dispatch<any> = doNothing) => { const client = PlatformClient.newPlatformClient(); let stream; client.connect(STREAM_RSOCKET_CLIENT_NAME, () => stream = client.requestStream(request, onNext, onComplete, onError), onError); return () => { stream?.(); client.disposeRsocket(); } } export const infinityRequestStream = (request: any, onNext: Dispatch<any> = doNothing, onError: Dispatch<any> = doNothing) => { const client = PlatformClient.newPlatformClient(); let stream; client.connect(INFINITY_STREAM_RSOCKET_CLIENT_NAME, () => stream = client.infinityRequestStream(request, onNext, onError), onError); return () => { stream?.(); client.disposeRsocket(); } } export const chunkedRequest = (chunks: any[], onComplete: DispatchWithoutAction = doNothing, onError: Dispatch<any> = doNothing) => PlatformClient.platformClient().chunkedRequest(chunks, onComplete, onError); export const fireAndForget = (request: any) => PlatformClient.platformClient().fireAndForget(request); export const disposeRsockets = () => clients.forEach(client => client.disposeRsocket());
// Counts the number of items in the list. Because we don't want to depend // on a full-blown JSON parser, we just count the number of commas static int count_list_items(const std::string &s) { size_t pos = 0; int num_items = 0; while (pos != std::string::npos) { pos = s.find(",", pos ? pos + 1 : pos); if (pos != std::string::npos) { num_items++; } } if (num_items > 0) { num_items++; } else if (s.size() > 2) { num_items = 1; } return num_items; }
import System.Plugins -- import System.Plugins.Utils import API src = "../Plugin.hs" wrap = "../Wrapper.hs" apipath = "../api" main = do status <- make src ["-i"++apipath] case status of MakeSuccess _ _ -> f MakeFailure e-> mapM_ putStrLn e where f = do v <- load "../Plugin.o" ["../api"] [] "resource" -- (i,_) <- exec "ghc" ["--numeric-version"] -- mapM_ putStrLn i putStrLn "done."
/* * Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.internal.serialization.impl; import static com.hazelcast.internal.serialization.impl.SerializationUtil.createObjectDataInputStream; import static com.hazelcast.internal.serialization.impl.SerializationUtil.createObjectDataOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import com.hazelcast.internal.serialization.InternalSerializationService; import com.hazelcast.internal.serialization.impl.defaultserializers.ArrayStreamSerializer; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.PortableReader; import com.hazelcast.nio.serialization.PortableWriter; import com.hazelcast.nio.serialization.Serializer; import com.hazelcast.nio.serialization.VersionedPortable; import com.hazelcast.nio.serialization.compatibility.CustomByteArraySerializer; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class SerializationUtilTest { private final InternalSerializationService mockSs = mock(InternalSerializationService.class); @Test public void testIsNullData() { Assert.assertTrue(SerializationUtil.isNullData(new HeapData())); } @Test(expected = Error.class) public void testHandleException_OOME() { SerializationUtil.handleException(new OutOfMemoryError()); } @Test(expected = Error.class) public void testHandleException_otherError() { SerializationUtil.handleException(new UnknownError()); } @Test(expected = IllegalArgumentException.class) public void testCreateSerializerAdapter_invalidSerializer() { SerializationUtil.createSerializerAdapter(new InvalidSerializer()); } @Test(expected = IllegalArgumentException.class) public void testGetPortableVersion_negativeVersion() { SerializationUtil.getPortableVersion(new DummyVersionedPortable(), 1); } @Test public void testReadWriteNullableBoolean_whenNull() throws IOException { byte[] bytes = serialize(null); assertNull(deserialize(bytes)); } @Test public void testReadWriteNullableBoolean_whenFalse() throws IOException { byte[] bytes = serialize(false); assertFalse(deserialize(bytes)); } @Test public void testReadWriteNullableBoolean_whenTrue() throws IOException { byte[] bytes = serialize(true); assertTrue(deserialize(bytes)); } @Test(expected = IllegalStateException.class) public void testReadWriteNullableBoolean_whenInvalid() throws IOException { byte[] bytes = new byte[1]; bytes[0] = 55; deserialize(bytes); } @Test public void testCreateSerializerAdapter() { // ArrayStreamSerializer is instance of StreamSerializer, hence using it as parameter SerializerAdapter streamSerializerAdapter = SerializationUtil.createSerializerAdapter(new ArrayStreamSerializer()); assertEquals(streamSerializerAdapter.getClass(), StreamSerializerAdapter.class); // CustomByteArraySerializer is instance of ByteArraySerializer, hence using it as parameter SerializerAdapter byteArraySerializerAdapter = SerializationUtil.createSerializerAdapter(new CustomByteArraySerializer()); assertEquals(byteArraySerializerAdapter.getClass(), ByteArraySerializerAdapter.class); } private byte[] serialize(Boolean b) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectDataOutput out = createObjectDataOutputStream(bout, mockSs); SerializationUtil.writeNullableBoolean(out, b); return bout.toByteArray(); } private Boolean deserialize(byte[] bytes) throws IOException { ObjectDataInput in = createObjectDataInputStream(new ByteArrayInputStream(bytes), mockSs); return SerializationUtil.readNullableBoolean(in); } private class InvalidSerializer implements Serializer { @Override public int getTypeId() { return 0; } @Override public void destroy() { } } private class DummyVersionedPortable implements VersionedPortable { @Override public int getClassVersion() { return -1; } @Override public int getFactoryId() { return 0; } @Override public int getClassId() { return 0; } @Override public void writePortable(PortableWriter writer) throws IOException { } @Override public void readPortable(PortableReader reader) throws IOException { } } }
<gh_stars>0 //! This crate contain utilities for working with xcb-dl. #[cfg(feature = "xcb_render")] pub mod cursor; pub mod error; pub mod format; pub mod hint; #[cfg(feature = "xcb_xinput")] pub mod input; pub mod log; pub mod property; #[cfg(feature = "xcb_render")] pub mod render; pub mod void; pub mod xcb_box;
<gh_stars>0 /* * Date:2021-05-18 20:28 * filename:06_mylist.h * */ template <typename T> class ListItem { public: T value() const { return _value; } ListItem* next() const { return _next; } private: T _value; ListItem* _next; }; template <typename T> class List { void insert_front(T value); void insert_end(T value); void display(std::ostream &os = std::cout) const; private: ListItem<T>* _end; ListItem<T>* _front; long _size; }; //我们要设计一个iterator //当我们提领(dereference)这以迭代器时,传回的应该是个ListItem对象;当我们递增该迭代器时,它应该指向下一个ListItem对象. //为了让该迭代器适用于任何型态的节点,而不只限于ListItem,我们可以将它设计为一个class template:06.cpp