text
stringlengths
27
775k
// // PromoModelProtocol.h // IOSSchool // // Created by Arkadiy Tsoy on 19.10.2020. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @protocol PromoModelProtocol <NSObject> @property(nonatomic, strong) NSString* propertyA; - (void)methodA; - (void)methodB; @end NS_ASSUME_NONNULL_END
library global_bottom_navigation_bar; export 'widgets/bottom_navigation_bar.dart'; export 'widgets/bottom_navigation_item.dart'; export 'widgets/scaffold_bottom_navigation.dart'; export 'widgets/tab_item.dart';
#include "../EventClass.h" #include "../ParamClass.h" #include <cstddef> #include <cstdlib> #include <iostream> #include <TFile.h> #include <TTree.h> using namespace std; void Generate (Long_t events) { Long_t r; //srand (0); // Open file and create tree TFile* file = new TFile ("tree1.root", "RECREATE", "", 0); TTree* tree = new TTree ("T", Form ("Test Tree for %ld events.", events)); // Create simple database ParamClass* a = new ParamClass ("Alpha", 1); ParamClass* b = new ParamClass ("Bravo", 2); ParamClass* c = new ParamClass ("ChuckNorris", 3); ParamClass* d = new ParamClass ("Damian", 4); tree->GetUserInfo()->Add(a); tree->GetUserInfo()->Add(b); tree->GetUserInfo()->Add(c); tree->GetUserInfo()->Add(d); // Create branch for events EventClass* eve = 0; tree->Branch("EventClass", "EventClass", &eve); // Fill tree with events for (Long_t i = 0; i < events; ++i) { //r = rand()%4; r = i%4; switch (r) { case 0: eve = new EventClass (a, 1); break; case 1: eve = new EventClass (b, 2); break; case 2: eve = new EventClass (c, 3); break; case 3: eve = new EventClass (d, 4); break; default: break; } tree->Fill(); } // write data and close file file->Write(); file->Close(); } int main (int argc, char** argv) { Generate(1000); return 0; }
<?php namespace Skraeda\AutoMapper\Support\Facades; use Illuminate\Support\Facades\Facade as IlluminateFacade; use Skraeda\AutoMapper\Contracts\AutoMapperContract; /** * AutoMapper facade. * * @author Gunnar Örn Baldursson <gunnar@sjukraskra.is> * @method static mixed map(array|object $source, string|object $targetClass, array $context = []) * @method static mixed mapToObject(array|object $source, object $target, array $context = []) * @method static \Illuminate\Support\Collection mapMultiple($collection, string $targetClass, array $context = []) * @method static \AutoMapperPlus\Configuration\AutoMapperConfigInterface getConfiguration() */ class AutoMapperFacade extends IlluminateFacade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return AutoMapperContract::class; } }
- src/app/controllers/AppointmentController.js ```js import * as Yup from 'yup'; import { startOfHour, parseISO, isBefore } from 'date-fns'; import User from '../models/User'; import Appointment from '../models/Appointment'; import File from '../models/File'; class AppointmentController { async index(req, res) { const appointments = await Appointment.findAll({ where: { user_id: req.userId, canceled_at: null }, order: ['date'], attributes: ['id', 'date'], include: [ { model: User, as: 'provider', attributes: ['id', 'name'], include: [ { model: File, as: 'avatar', attributes: ['id', 'path', 'url'], }, ], }, ], }); return res.json(appointments); } async store(req, res) { const schema = Yup.object().shape({ provider_id: Yup.number().required(), date: Yup.date().required(), }); if (!(await schema.isValid(req.body))) { return res.status(400).json({ error: 'Validation fails' }); } const { provider_id, date } = req.body; // check if provider_id is as provider const isProvider = await User.findOne({ where: { id: provider_id, provider: true }, }); if (!isProvider) { return res .status(401) .json({ error: 'You can only create appointments with providers' }); } // check past dates const hourStart = startOfHour(parseISO(date)); if (isBefore(hourStart, new Date())) { return res.status(400).json({ error: 'Past dates are not permiitted' }); } // Check date availability const checkAvailability = await Appointment.findOne({ where: { provider_id, canceled_at: null, date: hourStart, }, }); if (checkAvailability) { return res .status(400) .json({ error: 'Appointment date is not available' }); } const appointment = await Appointment.create({ user_id: req.userId, provider_id, date: hourStart, }); return res.json(appointment); } } export default new AppointmentController(); ``` - src/routes.js ```js import { Router } from 'express'; import multer from 'multer'; import multerConfig from './config/multer'; import UserController from './app/controllers/UserController'; import SessionController from './app/controllers/SessionController'; import FileController from './app/controllers/FileController'; import ProviderController from './app/controllers/ProviderController'; import AppointmentController from './app/controllers/AppointmentController'; import authMiddleware from './app/middlewares/auth'; const routes = new Router(); const upload = multer(multerConfig); routes.post('/users', UserController.store); routes.post('/sessions', SessionController.store); routes.use(authMiddleware); // rotas que vão usar o middleware de autenticação routes.put('/users', UserController.update); routes.post('/files', upload.single('file'), FileController.store); routes.get('/providers', ProviderController.index); routes.get('/appointments', AppointmentController.index); //<= routes.post('/appointments', AppointmentController.store); export default routes; ```
import { customFormField } from './custom-form-field'; export function formField( type: string ): (target: any, propertyKey: string) => void { return (target: any, propertyKey: string) => customFormField(type, target, propertyKey); }
import { NextApiRequest, NextApiResponse, GetServerSidePropsContext } from "next"; import { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "http"; import { DeepPartial } from "utility-types"; import { XOR } from "./helpers"; export type NonPagesResolverContext = { req?: IncomingMessage; res?: ServerResponse; }; export type PagesResolverContext = { req?: NextApiRequest | GetServerSidePropsContext["req"]; res?: NextApiResponse<any>; }; export type ResolverContext = XOR< NonPagesResolverContext, PagesResolverContext >;
import 'package:flutter/material.dart'; import '../stylish_dialog.dart'; const _sizeK = 48.0; // ignore: must_be_immutable class StylishDialogUI extends StatefulWidget { StylishDialogUI({ Key? key, required this.context, required this.alertType, this.animationLoop, this.titleText, this.contentText, this.confirmText, this.cancelText, this.confirmPressEvent, this.cancelPressEvent, this.addView, this.confirmButton, this.cancelButton, this.color, this.titleStyle, this.contentStyle, this.style, }) : super(key: key); final BuildContext context; final StylishDialogType? alertType; final bool? animationLoop; String? titleText; String? contentText; String? confirmText; String? cancelText; VoidCallback? confirmPressEvent; VoidCallback? cancelPressEvent; Widget? addView; Widget? confirmButton; Widget? cancelButton; Color? color; TextStyle? titleStyle; TextStyle? contentStyle; Style? style; @override _StylishDialogState createState() => _StylishDialogState(); } class _StylishDialogState extends State<StylishDialogUI> with TickerProviderStateMixin { var _key = GlobalKey<NavigatorState>(); late AnimationController _controller; late Animation<double> _animation; @override void initState() { super.initState(); _initializeAnimation(); } @override void didUpdateWidget(covariant StylishDialogUI oldWidget) { super.didUpdateWidget(oldWidget); ///dispose current active controller and /// create new one for changeAlertType _controller.dispose(); _initializeAnimation(); } @override void dispose() { _controller.dispose(); super.dispose(); } _initializeAnimation() { _controller = AnimationController( duration: const Duration(milliseconds: 2000), vsync: this, ); _animation = CurvedAnimation( parent: _controller, curve: Curves.fastOutSlowIn, ); } @override Widget build(BuildContext context) { //Default values of Confirm Button Text widget.confirmText ??= 'Confirm'; //Default values of Cancel Button Text widget.cancelText ??= 'Cancel'; return Dialog( key: (widget.key == null ? _key : widget.key), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(14), ), elevation: 0, backgroundColor: widget.style == Style.Default ? Colors.white : Colors.black, child: widget.style == Style.Default ? _stylishContentBox() : _stylishContentBoxStyle1(), ); } _stylishContentBox() { return Column( mainAxisSize: MainAxisSize.min, children: [ _stylishDialogChange(), if (widget.titleText != null) _titleTextWidget(widget.titleText), if (widget.contentText != null) _contentTextWidget(widget.contentText), if (widget.addView != null) Container( padding: EdgeInsets.only(left: 10, top: 8, bottom: 4, right: 10), child: widget.addView), Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ ///Cancel if (widget.cancelButton != null) Padding( padding: const EdgeInsets.all(12.0), child: widget.cancelButton!, ) else if (widget.cancelPressEvent != null) _pressButtonWidget( widget.cancelPressEvent, Colors.red, widget.cancelText), ///Confirm if (widget.confirmButton != null) Padding( padding: const EdgeInsets.all(12.0), child: widget.confirmButton!, ) else if (widget.confirmPressEvent != null) _pressButtonWidget( widget.confirmPressEvent, Colors.teal, widget.confirmText), ], ), ], ); } //Text widget for title text _titleTextWidget(text) { return Padding( padding: const EdgeInsets.only(top: 12.0, left: 8, right: 8, bottom: 8), child: Text( '$text', textAlign: TextAlign.center, style: widget.titleStyle, ), ); } //Text widget for content text _contentTextWidget(text) { return Padding( padding: const EdgeInsets.only(left: 8, right: 8, bottom: 10), child: Text( '$text', textAlign: TextAlign.center, style: widget.contentStyle, ), ); } //Button widget for confirm and cancel buttons _pressButtonWidget(pressEvent, color, text) { return Flexible( child: Padding( padding: const EdgeInsets.all(12.0), child: TextButton( onPressed: () async { pressEvent(); }, child: Padding( padding: const EdgeInsets.only(left: 8.0, right: 4.0, top: 4, bottom: 4), child: Text( '$text', textAlign: TextAlign.center, style: const TextStyle(color: Colors.white, fontSize: 16), ), ), style: ButtonStyle( backgroundColor: MaterialStateProperty.all(color), ), ), ), ); } _playAnimation() { if (widget.animationLoop!) _controller.repeat(); else _controller.forward(); } _stylishDialogChange() { switch (widget.alertType) { case StylishDialogType.NORMAL: return Container( width: 0, ); case StylishDialogType.PROGRESS: return Padding( padding: const EdgeInsets.only(top: 12.0, left: 8, right: 8, bottom: 8), child: CircularProgressIndicator( color: widget.color, ), ); case StylishDialogType.SUCCESS: _playAnimation(); return Padding( padding: const EdgeInsets.only(top: 12.0, left: 8, right: 8, bottom: 8), child: Container( alignment: Alignment.center, width: _sizeK, height: _sizeK, decoration: BoxDecoration( borderRadius: BorderRadius.circular(44), color: Colors.white, border: Border.all( color: Colors.green, width: 2, ), ), padding: EdgeInsets.all(4.0), child: SizeTransition( sizeFactor: _animation, axis: Axis.horizontal, axisAlignment: -1, child: const Icon( Icons.check, color: Colors.green, size: 38, ), ), ), ); case StylishDialogType.INFO: _playAnimation(); return Padding( padding: const EdgeInsets.only(top: 12.0, left: 8, right: 8, bottom: 8), child: ScaleTransition( scale: _animation, child: const Icon( Icons.info_outlined, color: Colors.blue, size: 44, )), ); case StylishDialogType.WARNING: _playAnimation(); return Padding( padding: const EdgeInsets.only(top: 12.0, left: 8, right: 8, bottom: 8), child: ScaleTransition( scale: _animation, child: const Icon( Icons.info_outlined, color: Colors.amber, size: 44, )), ); case StylishDialogType.ERROR: _playAnimation(); return Padding( padding: const EdgeInsets.only(top: 12.0, left: 8, right: 8, bottom: 8), child: Container( alignment: Alignment.center, width: _sizeK, height: _sizeK, decoration: BoxDecoration( borderRadius: BorderRadius.circular(44), color: Colors.white, border: Border.all( color: Colors.red, width: 2, ), ), padding: EdgeInsets.all(4.0), child: ScaleTransition( scale: _animation, child: const Icon( Icons.clear, color: Colors.red, size: 40, )), ), ); default: return Container( width: 0, ); } } _stylishContentBoxStyle1() { return Transform.rotate( angle: -0.07, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), color: Colors.white, ), padding: EdgeInsets.all(1), child: Transform.rotate( angle: 0.07, child: Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: 12, ), if (widget.titleText != null) _titleTextWidget(widget.titleText), if (widget.contentText != null) _contentTextWidget(widget.contentText), if (widget.addView != null) Container( padding: EdgeInsets.only(left: 10, top: 8, bottom: 4, right: 10), child: widget.addView), Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ ///Confirm if (widget.confirmButton != null) Padding( padding: const EdgeInsets.all(12.0), child: widget.confirmButton!, ) else if (widget.confirmPressEvent != null) _pressButtonWidgetStyle1(widget.confirmPressEvent, Colors.black, widget.confirmText), ///Cancel if (widget.cancelButton != null) Padding( padding: const EdgeInsets.all(12.0), child: widget.cancelButton!, ) else if (widget.cancelPressEvent != null) _pressButtonWidgetStyle1(widget.cancelPressEvent, Colors.transparent, widget.cancelText, textColor: Colors.black), ], ), ], ), ), ), ); } _pressButtonWidgetStyle1(pressEvent, color, text, {textColor}) { return Padding( padding: const EdgeInsets.all(12.0), child: GestureDetector( onTap: () async { pressEvent(); }, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: color, ), padding: const EdgeInsets.all(12), child: Text( '$text', textAlign: TextAlign.center, style: TextStyle(color: textColor ?? Colors.white, fontSize: 16), ), ), ), ); } }
package store import ( "context" "time" "github.com/reiot777/spansqlx" ) type Range struct { Limit int32 Offset int32 } type Account struct { ID string Owner string Email string CreatedAt time.Time UpdatedAt time.Time } type AccountQuery struct { Owner *string Email *string Range *Range } type AccountStore interface { AddAccount(context.Context, *Account) error Account(context.Context, AccountQuery) (*Account, error) Accounts(context.Context, AccountQuery) ([]*Account, error) } type Task struct { ID string AccountID string Name string Undone bool CreatedAt time.Time UpdatedAt time.Time } type TaskQuery struct { AccountID *string Undone *bool } type TaskStore interface { Task(context.Context, TaskQuery) (*Task, error) Tasks(context.Context, TaskQuery) ([]*Task, error) AddTask(context.Context, *Task) error SetTaskDone(context.Context, string) error } type Store interface { Pipeline(context.Context, func(context.Context) error) error Accounts() AccountStore Tasks() TaskStore } var _ Store = (*store)(nil) type store struct { db *spansqlx.DB } func New(db *spansqlx.DB) Store { return &store{db: db} } func (s *store) Pipeline(ctx context.Context, fn func(ctx context.Context) error) error { return s.db.TxPipeline(ctx, fn) } func (s *store) Accounts() AccountStore { return &accountStore{} } func (s *store) Tasks() TaskStore { return &taskStore{} }
@php $showDescription ??= false; @endphp <article> <div class="flex items-center"> <div class="relative flex-shrink-0 mr-4"> <x-image class="w-24 h-24 overflow-hidden rounded-full" :lqip="$person->present()->imageLqip()" :src="$person->present()->imageSrc()" :alt="$person->imageAltText('image')" /> @foreach (['github', 'linkedin'] as $network) @continue(!$person->$network) <x-social-network-link :network="$network" :link="$person->$network" /> @endforeach </div> <div> <h1 class="text-xl font-bold">{{ $person->name }}</h1> <span class="text-base">{{ $person->title }}</span> </div> </div> @if ($showDescription && $person->description) <div class="mt-4 ck-content"> {!! $person->description !!} </div> @endif </article>
/* * Copyright 2021 Tadashi G. Takaoka * * 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. */ #include "config_tms32010.h" #include "entry_tms32010.h" #include "table_tms32010.h" #include "text_tms32010.h" #include <ctype.h> #include <string.h> namespace libasm { namespace tms32010 { #define E3(_opc, _name, _op1, _op2, _op3) \ { _opc, Entry::Flags::create(_op1, _op2, _op3), _name } #define E2(_opc, _name, _op1, _op2) E3(_opc, _name, _op1, _op2, M_NO) #define E1(_opc, _name, _op1) E2(_opc, _name, _op1, M_NO) #define E0(_opc, _name) E1(_opc, _name, M_NO) // clang-format off static constexpr Entry TABLE_TMS32010[] PROGMEM = { E3(0x0000, TEXT_ADD, M_MAM, M_LS4, M_NARP), E3(0x1000, TEXT_SUB, M_MAM, M_LS4, M_NARP), E3(0x2000, TEXT_LAC, M_MAM, M_LS4, M_NARP), E3(0x3000, TEXT_SAR, M_AR, M_MAM, M_NARP), E3(0x3800, TEXT_LAR, M_AR, M_MAM, M_NARP), E3(0x4000, TEXT_IN, M_MAM, M_PA, M_NARP), E3(0x4800, TEXT_OUT, M_MAM, M_PA, M_NARP), E3(0x5000, TEXT_SACL, M_MAM, M_LS0, M_NARP), E3(0x5800, TEXT_SACH, M_MAM, M_LS3, M_NARP), E2(0x6000, TEXT_ADDH, M_MAM, M_NARP), E2(0x6100, TEXT_ADDS, M_MAM, M_NARP), E2(0x6200, TEXT_SUBH, M_MAM, M_NARP), E2(0x6300, TEXT_SUBS, M_MAM, M_NARP), E2(0x6400, TEXT_SUBC, M_MAM, M_NARP), E2(0x6500, TEXT_ZALH, M_MAM, M_NARP), E2(0x6600, TEXT_ZALS, M_MAM, M_NARP), E2(0x6700, TEXT_TBLR, M_MAM, M_NARP), E1(0x6880, TEXT_LARP, M_ARK), E2(0x6800, TEXT_MAR, M_MAM, M_NARP), E2(0x6900, TEXT_DMOV, M_MAM, M_NARP), E2(0x6A00, TEXT_LT, M_MAM, M_NARP), E2(0x6B00, TEXT_LTD, M_MAM, M_NARP), E2(0x6C00, TEXT_LTA, M_MAM, M_NARP), E2(0x6D00, TEXT_MPY, M_MAM, M_NARP), E1(0x6E00, TEXT_LDPK, M_DPK), E2(0x6F00, TEXT_LDP, M_MAM, M_NARP), E2(0x7000, TEXT_LARK, M_AR, M_IM8), E2(0x7800, TEXT_XOR, M_MAM, M_NARP), E2(0x7900, TEXT_AND, M_MAM, M_NARP), E2(0x7A00, TEXT_OR, M_MAM, M_NARP), E2(0x7B00, TEXT_LST, M_MAM, M_NARP), E2(0x7C00, TEXT_SST, M_MAM, M_NARP), E2(0x7D00, TEXT_TBLW, M_MAM, M_NARP), E1(0x7E00, TEXT_LACK, M_IM8), E0(0x7F80, TEXT_NOP), E0(0x7F81, TEXT_DINT), E0(0x7F82, TEXT_EINT), E0(0x7F88, TEXT_ABS), E0(0x7F89, TEXT_ZAC), E0(0x7F8A, TEXT_ROVM), E0(0x7F8B, TEXT_SOVM), E0(0x7F8C, TEXT_CALA), E0(0x7F8D, TEXT_RET), E0(0x7F8E, TEXT_PAC), E0(0x7F8F, TEXT_APAC), E0(0x7F90, TEXT_SPAC), E0(0x7F9C, TEXT_PUSH), E0(0x7F9D, TEXT_POP), E1(0x8000, TEXT_MPYK, M_IM13), E1(0xF400, TEXT_BANZ, M_PMA), E1(0xF500, TEXT_BV, M_PMA), E1(0xF600, TEXT_BIOZ, M_PMA), E1(0xF800, TEXT_CALL, M_PMA), E1(0xF900, TEXT_B, M_PMA), E1(0xFA00, TEXT_BLZ, M_PMA), E1(0xFB00, TEXT_BLEZ, M_PMA), E1(0xFC00, TEXT_BGZ, M_PMA), E1(0xFD00, TEXT_BGEZ, M_PMA), E1(0xFE00, TEXT_BNZ, M_PMA), E1(0xFF00, TEXT_BZ, M_PMA), }; // clang-format on static bool acceptMode(AddrMode opr, AddrMode table) { if (opr == table) return true; if (opr == M_NO) // These can be ommitted. return table == M_LS0 || table == M_LS3 || table == M_LS4 || table == M_NARP; if (opr == M_AR) // ARn can be used as 0,1 return table == M_ARK || table == M_NARP; if (opr == M_PA) // PAn can not match other than itself. return false; if (opr == M_ARP || opr == M_INC || opr == M_DEC) return table == M_MAM; // Compare constant range. auto tv = uint8_t(table); if (tv >= uint8_t(M_LS0) && tv <= uint8_t(M_IM13)) { const uint8_t ov = uint8_t(opr); return tv >= ov; } return false; } static bool acceptModes(Entry::Flags flags, const Entry *entry) { auto table = entry->flags(); return acceptMode(flags.op1(), table.op1()) && acceptMode(flags.op2(), table.op2()) && acceptMode(flags.op3(), table.op3()); } Error TableTms32010::searchName(InsnTms32010 &insn) const { uint8_t count = 0; auto entry = TableBase::searchName<Entry, Entry::Flags>( insn.name(), insn.flags(), ARRAY_RANGE(TABLE_TMS32010), acceptModes, count); if (entry) { insn.setOpCode(entry->opCode()); insn.setFlags(entry->flags()); return setOK(); } return setError(count == 0 ? UNKNOWN_INSTRUCTION : OPERAND_NOT_ALLOWED); } static Config::opcode_t tableCode(Config::opcode_t opCode, const Entry *entry) { auto op1 = entry->flags().op1(); auto op2 = entry->flags().op2(); Config::opcode_t mask = 0; if (op1 == M_IM8 || op2 == M_IM8) mask |= 0xFF; if (op1 == M_MAM || op2 == M_MAM) { if ((opCode & (1 << 7)) == 0) { mask |= 0x7F; // Direct addressing } else { mask |= 0xB9; // Indirect addressing } } if (op1 == M_IM13) mask |= 0x1FFF; if (op1 == M_AR) mask |= 1 << 8; if (op1 == M_ARK || op1 == M_DPK) mask |= (1 << 0); if (op2 == M_LS4) mask |= 0xF << 8; if (op2 == M_PA || op2 == M_LS3 || op2 == M_LS0) mask |= 7 << 8; return opCode & ~mask; } Error TableTms32010::searchOpCode(InsnTms32010 &insn) const { auto entry = TableBase::searchCode<Entry, Config::opcode_t>( insn.opCode(), ARRAY_RANGE(TABLE_TMS32010), tableCode); if (entry) { insn.setFlags(entry->flags()); insn.setName_P(entry->name()); return setOK(); } return setError(UNKNOWN_INSTRUCTION); } uint16_t TableTms32010::dataMemoryLimit() const { return _cpuType == TMS32010 ? 0x8F : 0xFF; } bool TableTms32010::setCpu(CpuType cpuType) { _cpuType = cpuType; return true; } const char *TableTms32010::listCpu() const { return TEXT_CPU_LIST; } const char *TableTms32010::getCpu() const { return (_cpuType == TMS32010) ? TEXT_CPU_32010 : TEXT_CPU_32015; } bool TableTms32010::setCpu(const char *cpu) { if (strncasecmp_P(cpu, TEXT_CPU_TMS, 3) == 0) cpu += 3; if (strcmp_P(cpu, TEXT_CPU_32010) == 0) return setCpu(TMS32010); if (strcmp_P(cpu, TEXT_CPU_32015) == 0) return setCpu(TMS32015); return false; } class TableTms32010 TableTms32010; } // namespace tms32010 } // namespace libasm // Local Variables: // mode: c++ // c-basic-offset: 4 // tab-width: 4 // End: // vim: set ft=cpp et ts=4 sw=4:
'use strict' var $table_login = $('input[value="登录"]').closest('table') var $button_login = $('<a role="button" class="pure-button" \ style="padding: 70px;">登录</a>') .attr('href', $table_login.find('a:eq(1)').attr('href')) $table_login.after($button_login) $table_login.closest('tr').attr('align', 'center') $table_login.hide()
'use strict'; import AliMail from './ali-mail'; import { containHtml } from './utils'; class Config { aliAppId: string; aliSecret: string; senderName?: string; senderEmail?: string; emailTitle?: string; aliMailTimeout?: number; } class SendMailConfig { senderAddress: string; senderName: string; toAddresses: String[]; title: string; content: string; } interface SendMailResponse { EnvId: string; RequestId: string; } export default class Notification { private emailTitle: string = '邮件通知 Email Notification'; private aliMailTimeout: number = 3000; private aliMail: AliMail; constructor(private config: Config) { this.aliMailTimeout = (config && config.aliMailTimeout) || this.aliMailTimeout; this.emailTitle = (config && config.emailTitle) || this.emailTitle; this.aliMail = new AliMail( this.config.aliAppId, this.config.aliSecret, this.config.aliMailTimeout ); } async sendMail(options: SendMailConfig): Promise<SendMailResponse> { const sendOptions: any = {}; if (containHtml(options.content)) { sendOptions.html = options.content; } else { sendOptions.text = options.content; } delete options.content; Object.assign(sendOptions, options); return this.aliMail.sendMail(sendOptions); } }
package net.timafe.angkor import net.timafe.angkor.config.SecurityConfig import net.timafe.angkor.domain.dto.UserSummary import net.timafe.angkor.domain.enums.AuthScope import net.timafe.angkor.domain.enums.EntityType import net.timafe.angkor.domain.enums.LinkMediaType import net.timafe.angkor.service.LinkService import net.timafe.angkor.service.TaggingService import net.timafe.angkor.web.LinkController import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import org.mockito.Mockito import java.util.* import kotlin.test.assertEquals /** * Fast Unit tests to be run in isolation - no spring container required */ class UnitTests { private val taggingService = TaggingService() @Test fun testEnum() { assertEquals("ALL_AUTH", AuthScope.ALL_AUTH.name) assertEquals("All auth", AuthScope.ALL_AUTH.friendlyName()) assertEquals("Public", AuthScope.PUBLIC.friendlyName()) } // https://www.baeldung.com/parameterized-tests-junit-5#4-csv-literals @ParameterizedTest @CsvSource(value= ["Sri Lanka North:sri-lanka-north", "Hase:hase"], delimiter = ':') fun testTags(code: String, expected: String) { assertThat(taggingService.normalizeTag(code)).isEqualTo(expected) } @Test fun testUserSummary() { var user = UserSummary(id = UUID.randomUUID(), name = "Hase Klaus",emoji = "\uD83D\uDE48") assertThat(user.shortname).isEqualTo("Hase K.") user = UserSummary(id = UUID.randomUUID(), name = "Horst", emoji = "\uD83D\uDE48") assertThat(user.shortname).isEqualTo("Horst") user = UserSummary(id = UUID.randomUUID(), name = "Rudi Bacardi Sockenschorsch", emoji = "\uD83D\uDE48") assertThat(user.initials).isEqualTo("RBS") // println(ObjectMapper().writeValueAsString(user)) } @Test fun testSecurityConfig() { val sc = SecurityConfig() val patterns = sc.getEntityPatterns("/hase") assertThat(patterns.size).isEqualTo(EntityType.values().size) } @Test fun testLinkMediaTypes() { val types = LinkController(Mockito.mock(LinkService::class.java)).getLinkMediaTypes() assertThat(types.size).isEqualTo(LinkMediaType.values().size) types.forEach{ assertThat(it.icon).isNotBlank() } types.forEach{ assertThat(it.label).isNotBlank() } } }
require 'spec_helper' RSpec.describe Elasticband::Query::ScoreFunction do describe '#to_h' do subject { described_class.new.to_h } it { is_expected.to be_a(Hash) } it { is_expected.to be_empty } end end
use std::sync; use spin; use parking_lot; struct Foo { mu1: sync::Arc<sync::Mutex<i32>>, rw1: sync::RwLock<i32>, mu2: parking_lot::Mutex<i32>, rw2: parking_lot::RwLock<i32>, mu3: spin::Mutex<i32>, rw3: spin::RwLock<i32>, } impl Foo { fn new() -> Self { Self { mu1: sync::Arc::new(sync::Mutex::new(1)), rw1: sync::RwLock::new(1), mu2: parking_lot::Mutex::new(1), rw2: parking_lot::RwLock::new(1), mu3: spin::Mutex::new(1), rw3: spin::RwLock::new(1), } } fn std_mutex_1(&self) { let guard1 = self.mu1.lock().unwrap(); match *guard1 { 1 => {}, _ => { self.std_mutex_2(); }, }; } fn std_mutex_2(&self) { *self.mu1.lock().unwrap() += 1; } fn std_rwlock_read_1(&self) { match *self.rw1.read().unwrap() { 1 => { self.std_rwlock_write_2(); }, _ => { self.std_rwlock_read_2(); }, }; } fn std_rwlock_write_1(&self) { match *self.rw1.write().unwrap() { 1 => { self.std_rwlock_write_2(); }, _ => { self.std_rwlock_read_2(); }, }; } fn std_rwlock_read_2(&self) { *self.rw1.read().unwrap(); } fn std_rwlock_write_2(&self) { *self.rw1.write().unwrap() += 1; } fn parking_lot_mutex_1(&self) { match *self.mu2.lock() { 1 => {}, _ => { self.parking_lot_mutex_2(); }, }; } fn parking_lot_mutex_2(&self) { *self.mu2.lock() += 1; } fn parking_lot_rwlock_read_1(&self) { match *self.rw2.read() { 1 => { self.parking_lot_rwlock_write_2(); }, _ => { self.parking_lot_rwlock_read_2(); }, }; } fn parking_lot_rwlock_write_1(&self) { match *self.rw2.write() { 1 => { self.parking_lot_rwlock_write_2(); }, _ => { self.parking_lot_rwlock_read_2(); }, }; } fn parking_lot_rwlock_read_2(&self) { *self.rw2.read(); } fn parking_lot_rwlock_write_2(&self) { *self.rw2.write() += 1; } fn spin_mutex_1(&self) { match *self.mu3.lock() { 1 => { self.recur() }, _ => { self.spin_mutex_2(); }, }; } fn recur(&self) { self.spin_mutex_1(); } fn spin_mutex_2(&self) { *self.mu3.lock() += 1; } fn spin_rwlock_read_1(&self) { match *self.rw3.read() { 1 => { self.spin_rwlock_write_2(); }, _ => { self.spin_rwlock_read_2(); }, } } fn spin_rwlock_write_1(&self) { match *self.rw3.write() { 1 => { self.spin_rwlock_write_2(); }, _ => { self.spin_rwlock_read_2(); }, }; } fn spin_rwlock_read_2(&self) { *self.rw3.read(); } fn spin_rwlock_write_2(&self) { *self.rw3.write() += 1; } } fn main() { }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ExampleController extends Controller { public function add($num1, $num2) { if (is_numeric($num1) && is_numeric($num2)) { return $num1+$num2; } else { return "Both inputs must be numeric."; } } public function rollDice($guess) { if (!is_numeric($guess)) { return $guess . " is not numeric. Guess Again."; } elseif ($guess < 1 || $guess > 6) { return $guess . " is not between 1 and 6. Guess Again."; } else { $data = ['diceNum' => rand(1, 6), 'guess' => $guess]; return view('roll-dice', $data); } } }
# Privacy Policy ## Personal information This application will access any file or folder on your device. These are used only in the application, and does not collect or publish any personal information. ## Error information This application sends error information for debugging at crash. Personal information is not included in the send data.
/* Copyright (C) 2004 Versant Inc. http://www.db4o.com */ using System; using System.Collections; using Sharpen.Lang; using Db4objects.Db4o; namespace Db4objects.Db4o.Config { /// <exclude /> public class TDictionary : IObjectTranslator { public void OnActivate(IObjectContainer objectContainer, object obj, object members){ IDictionary dict = (IDictionary)obj; dict.Clear(); if(members != null){ Entry[] entries = (Entry[]) members; for(int i = 0; i < entries.Length; i++){ if(entries[i].key != null && entries[i].value != null){ dict[entries[i].key] = entries[i].value; } } } } public Object OnStore(IObjectContainer objectContainer, object obj){ IDictionary dict = (IDictionary)obj; Entry[] entries = new Entry[dict.Count]; IDictionaryEnumerator e = dict.GetEnumerator(); e.Reset(); for(int i = 0; i < dict.Count; i++){ e.MoveNext(); entries[i] = new Entry(); entries[i].key = e.Key; entries[i].value = e.Value; } return entries; } public System.Type StoredClass(){ return typeof(Entry[]); } } }
<html> <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["mobile"]; ?> <?php include '../db/connection.php'; include '../utils/logs.php'; $query = file_get_contents("../db/sqlQueries/insertNewRegistration.sql"); wh_log($query); echo $query; $conn = OpenCon(); $stmt = $conn->prepare($query); if ($stmt->execute()){ wh_log("success"); echo "Success"; }else{ wh_log(" Query Fail"); echo "Fail"; } CloseCon($conn); ?> </body> </html>
// // WMBroadcastViewDelegate.h // WowzaMedl // // Created by Hugo Nagano on 10/28/16. // Copyright © 2016 Hugo Nagano. All rights reserved. // #import "WowzaGoCoder.h" @protocol WMBroadcastViewDelegate <NSObject> -(void)didStartBroacast; -(void)didFailToStartBroadcast:(NSError *)error; -(void)broadcastStatusDidChange:(WOWZState)state; -(void)broadcastDidReceiveEvent:(WOWZEvent)event andError:(NSError *)error; -(void)broadcastDidReceiveError:(NSError *) error; -(void)brodcastVideoFrameWasEncoded:(NSInteger *)durationInSeconds; @end
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ import { Management as dm } from "./amqp/management.js"; import { utils } from "./amqp/utilities.js"; // number of milliseconds between topology updates const DEFAULT_INTERVAL = 5000; export class QDRService { constructor(hooks) { this.utilities = utils; this.hooks = hooks || function() {}; this.schema = null; this.initManagement(); } initManagement = () => { const url = utils.getUrlParts(window.location); this.management = new dm(url.protocol, DEFAULT_INTERVAL); }; setHooks = hooks => { this.hooks = hooks; }; onReconnect = () => { this.management.connection.on("disconnected", this.onDisconnect); this.hooks.setLocation("reconnect"); }; onDisconnect = () => { this.hooks.setLocation("disconnect"); this.management.connection.on("connected", this.onReconnect); }; connect = connectOptions => { let self = this; return new Promise((resolve, reject) => { self.management.connection.connect(connectOptions).then( r => { // if we are ever disconnected, show the connect page and wait for a reconnect self.management.connection.on("disconnected", this.onDisconnect); self.management.getSchema().then(schema => { self.schema = schema; //console.log("got schema after connection"); //console.log(schema); self.management.topology.setUpdateEntities([]); //console.log("requesting a topology"); self.management.topology .get() // gets the list of routers .then(t => { resolve(r); }); }); }, e => { reject(e); } ); }); }; disconnect = () => { this.management.connection.disconnect(); delete this.management; this.initManagement(); }; setReconnect = reconnect => { this.management.connection.setReconnect(reconnect); }; } (function() { console.dump = function(o) { console.log(JSON.stringify(o, undefined, 2)); }; })();
[![PyPI](https://img.shields.io/pypi/pyversions/Django.svg)]() Characterstic ----------------------------------- * Using Word2Vec+CNN to detect the Malicious URL and it's a really exquisite structure! * Finially result about 96.2% precision * High scalability supporting for Distributed System * Supporting for Online Learning Requirements ----------------------------------- * Tensorflow 1.1.0 * Numpy * Gensim 2.0.0 Training ----------------------------------- python train.py --help usage: train.py [-h] [--data_file DATA_FILE] [--num_labels NUM_LABELS] [--embedding_dim EMBEDDING_DIM] [--filter_sizes FILTER_SIZES] [--num_filters NUM_FILTERS] [--dropout_keep_prob DROPOUT_KEEP_PROB] [--l2_reg_lambda L2_REG_LAMBDA] [--batch_size BATCH_SIZE] [--num_epochs NUM_EPOCHS] [--evaluate_every EVALUATE_EVERY] [--checkpoint_every CHECKPOINT_EVERY] [--num_checkpoints NUM_CHECKPOINTS] [--allow_soft_placement [ALLOW_SOFT_PLACEMENT]] [--noallow_soft_placement] [--log_device_placement [LOG_DEVICE_PLACEMENT]] [--nolog_device_placement] [--noreplicas] [--is_sync [IS_SYNC]] [--nois_sync] [--ps_hosts PS_HOSTS] [--worker_hosts WORKER_HOSTS] [--job_name JOB_NAME] [--task_index TASK_INDEX] [--log_dir LOG_DIR] optional arguments: -h, --help show this help message and exit --data_file DATA_FILE Data source --num_labels NUM_LABELS Number of labels for data. (default: 2) --embedding_dim EMBEDDING_DIM Dimensionality of character embedding (default: 128) --filter_sizes FILTER_SIZES Comma-spearated filter sizes (default: '3,4,5') --num_filters NUM_FILTERS Number of filters per filter size (default: 128) --dropout_keep_prob DROPOUT_KEEP_PROB Dropout keep probability (default: 0.5) --l2_reg_lambda L2_REG_LAMBDA L2 regularization lambda (default: 0.0) --batch_size BATCH_SIZE Batch Size (default: 64) --num_epochs NUM_EPOCHS Number of training epochs (default: 200) --evaluate_every EVALUATE_EVERY Evalue model on dev set after this many steps (default: 100) --checkpoint_every CHECKPOINT_EVERY Save model after this many steps (defult: 100) --num_checkpoints NUM_CHECKPOINTS Number of checkpoints to store (default: 5) --allow_soft_placement [ALLOW_SOFT_PLACEMENT] Allow device soft device placement --noallow_soft_placement --log_device_placement [LOG_DEVICE_PLACEMENT] Log placement of ops on devices --nolog_device_placement --replicas [REPLICAS] Use the dirstribution mode --noreplicas --is_sync [IS_SYNC] Use the async or sync mode --nois_sync --ps_hosts PS_HOSTS comma-separated lst of hostname:port pairs --worker_hosts WORKER_HOSTS comma-separated lst of hostname:port pairs --job_name JOB_NAME job name:worker or ps --task_index TASK_INDEX Worker task index,should be >=0, task=0 is the master worker task the performs the variable initialization --log_dir LOG_DIR parameter and log info Distribution ----------------------------------- Let's take 192.168.0.107 as ps server , 10.211.55.13 and 10.211.55.14 as training server. Make every machine has a copy of the code. ### Async-parallelism mode: ![image](https://github.com/paradise6/DetectMaliciousURL/blob/master/data/screenshot/async.png) On 192.168.0.107: python train.py --replicas=True --job_name=ps --task_index=0 --ps_hosts=192.168.0.107:2222\ --worker_hosts=10.211.55.13:2222,10.211.55.14:2222 On 10.211.55.13: python train.py --replicas=True --job_name=worker --task_index=0 --ps_hosts=192.168.0.107:2222\ --worker_hosts=10.211.55.13:2222,10.211.55.14:2222 On 10.211.55.14: python train.py --replicas=True --job_name=worker --task_index=1 --ps_hosts=192.168.0.107:2222\ --worker_hosts=10.211.55.13:2222,10.211.55.14:2222 ### Sync-parallelism mode: ![image](https://github.com/paradise6/DetectMaliciousURL/blob/master/data/screenshot/sync.png) On 192.168.0.107: python train.py --replicas=True --is_sync=True --job_name=ps --task_index=0 --ps_hosts=192.168.0.107:2222\ --worker_hosts=10.211.55.13:2222,10.211.55.14:2222 On 10.211.55.13: python train.py --replicas=True --is_sync=True --job_name=worker --task_index=0 --ps_hosts=192.168.0.107:2222\ --worker_hosts=10.211.55.13:2222,10.211.55.14:2222 On 10.211.55.14: python train.py --replicas=True --is_sync=True --job_name=worker --task_index=1 --ps_hosts=192.168.0.107:2222\ --worker_hosts=10.211.55.13:2222,10.211.55.14:2222 Evaluation ----------------------------------- python eval.py --help usage: eval.py [-h] [--input_text_file INPUT_TEXT_FILE][--single_url SINGLE_URL] [--input_label_file INPUT_LABEL_FILE] [--batch_size BATCH_SIZE] [--checkpoint_dir CHECKPOINT_DIR] [--eval_train [EVAL_TRAIN]] [--noeval_train] [--allow_soft_placement [ALLOW_SOFT_PLACEMENT]] [--noallow_soft_placement] [--log_device_placement [LOG_DEVICE_PLACEMENT]] [--nolog_device_placement] python eval.py --checkpoint_dir ./runs/{TIME_DIR}/checkpoints} ### Single URL Detection python eval.py --checkpoint_dir ./runs/{TIME_DIR}/checkpoints} --single_url=hottraveljobs.com/forum/docs/info.php Here I use the defualt checkpoint_dir to detection single_url python eval.py --single_url=hottraveljobs.com/forum/docs/info.php ### Panel Testing python eval.py --checkpoint_dir ./runs/{TIME_DIR}/checkpoints} --input_text_file="../data/data2.csv" HTTP Server API ---------------------------------- This is the HTTP service to load TensorFlow model and inference to predict malicious url. ### Usage Run HTTP server with [Django] and use HTTP client under /server ./manage.py runserver 0.0.0.0:8000 ### Inference to predict url Use url as your GET parameter 127.0.0.1:8000/detection/predict/?url=appst0re.net/upload.aspx And you will get Success to predict appst0re.net/upload.aspx, result: bad ### Implementation django-admin startproject server python manage.py startapp detection #Add customized urls and views. References ----------------------------------- [[1] Cnn-Text-Classification-TF](https://github.com/dennybritz/cnn-text-classification-tf) [[2] Convolutional Neural Networks for Sentence Classification](https://arxiv.org/abs/1408.5882) [[3] Using Word2Vec+ CNN to Detect Malicious URL](http://blog.csdn.net/u011987514/article/details/71189491) [[4] deep_recommend_system](https://github.com/tobegit3hub/deep_recommend_system/tree/master/http_service#implementation) [[5] using-machine-learning-detect-malicious-urls](http://fsecurify.com/using-machine-learning-detect-malicious-urls/) [[6] Malware URLs](http://malwareurls.joxeankoret.com) [[7]Malicious URL Detection using Machine Learning](https://arxiv.org/abs/1701.07179)
using Microsoft.EntityFrameworkCore; using ProEventos.Domain; namespace ProEventos.Persistence.Context { /// <summary> /// Responsible to convert the LINQ queries to DB queries. /// Stores all the DbSet objects for the tables of the DB /// </summary> public class ProEventosContext : DbContext { /// <summary> /// The DbSet for the Eventos table on the DB /// </summary> /// <value></value> public DbSet<Evento> Eventos { get; set; } /// <summary> /// The DbSet for the Lotes table on the DB /// </summary> /// <value></value> public DbSet<Lote> Lotes { get; set; } /// <summary> /// The DbSet for the Palestrantes table on the DB /// </summary> /// <value></value> public DbSet<Palestrante> Palestrantes { get; set; } /// <summary> /// The DbSet for the PalestrantesEventos table on the DB /// </summary> /// <value></value> public DbSet<PalestranteEvento> PalestrantesEventos { get; set; } /// <summary> /// The DbSet for the RedesSocias table on the DB /// </summary> /// <value></value> public DbSet<RedeSocial> RedesSocias { get; set; } /// <summary> /// Receives a dependency injection of an object /// Microsoft.EntityFrameworkCore.DbContextOptions with type /// ProEventos.Persistence.ProEventosContext /// </summary> /// <param name="options">An /// Microsoft.EntityFrameworkCore.DbContextOptions object with type /// ProEventos.Persistence.ProEventosContext</param> /// <returns></returns> public ProEventosContext(DbContextOptions<ProEventosContext> options) : base(options) { } /// <summary> /// Responsável por associar as classes Palestrantes e Eventos. /// Definindo que a classe PalestranteEvento é a classe de junção entre /// as duas classes supra citadas. /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(ModelBuilder modelBuilder) { // Definindo os Id externos (Foreign Keys) que geram o // relacionamento entre as tabelas Eventos e Palestrantes modelBuilder.Entity<PalestranteEvento>() .HasKey(PE => new { PE.EventoId, PE.PalestranteId }); // Definindo o Cascade On Delete para que quando um Evento for // deletado, tenha as Redes Sociais associadas a ele também deletadas. modelBuilder.Entity<Evento>() .HasMany(e => e.RedesSociais) .WithOne(rs => rs.Evento) .OnDelete(DeleteBehavior.Cascade); // Definindo o Cascade On Delete para que quando um Palestrante for // deletado, tenha as Redes Sociais associadas a ele também deletadas. modelBuilder.Entity<Palestrante>() .HasMany(p => p.RedesSociais) .WithOne(rs => rs.Palestrante) .OnDelete(DeleteBehavior.Cascade); } } }
-- Verify forum:1-rename-parent-forum-col on pg BEGIN; SELECT parent_forum_id from forums WHERE FALSE; ROLLBACK;
import { Button as uuiButton, ButtonProps } from '@epam/uui-components'; import { withMods } from '@epam/uui-core'; import { ControlSize, FillStyle } from '../types'; import { systemIcons } from '../../icons/icons'; import * as css from './Button.scss'; import * as styles from '../../assets/styles/colorvars/buttons/button-colorvars.scss'; export type ButtonColor = 'blue' | 'green' | 'red' | 'gray50'; export const allButtonColors: ButtonColor[] = ['blue', 'green', 'red', 'gray50']; const defaultSize = '36'; export interface ButtonMods { size?: ControlSize | '18'; fill?: FillStyle; color?: ButtonColor; } export function applyButtonMods(mods: ButtonMods & ButtonProps) { return [ styles['button-color-' + (mods.color || 'blue')], css.root, css['size-' + (mods.size || defaultSize)], css['fill-' + (mods.fill || 'solid')], ]; } export const Button = withMods<ButtonProps, ButtonMods>( uuiButton, applyButtonMods, (props) => ({ dropdownIcon: systemIcons[props.size || defaultSize].foldingArrow, clearIcon: systemIcons[props.size || defaultSize].clear, }), );
/******************************************************************************* * Created 2017,2019 by Jonny Rimkus <jonny@rimkus.it>. * Hope you like it :) * * Contributors: * Jonny Rimkus - initial API and implementation *******************************************************************************/ /***/ class HotKeys { constructor(){ this.globalInit = false; } static init() { if(HotKeys.globalInit === true) return; // always use hotkeys for all elements. // see https://www.npmjs.com/package/hotkeys-js#filter hotkeys.filter = function(event){ return true; }; hotkeys('left', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $player.rewind(); }); hotkeys('ctrl+left', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $player.loadPreviousSong(); }); hotkeys('right', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $player.fastForward(); }); hotkeys('ctrl+right', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $player.loadNextSong(); }); hotkeys('up', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $player.volumeUp(); }); hotkeys('down', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $player.volumeDown(); }); hotkeys('space', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $player.togglePlay(); }); hotkeys('ctrl+1', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $page.loader.loadPage($page.loader.pages.video.youtube); }); hotkeys('ctrl+2', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $page.loader.loadPage($page.loader.pages.playlist.lastfm); }); hotkeys('ctrl+3', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $page.loader.loadPage($page.loader.pages.playlist.user); }); hotkeys('ctrl+4', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $page.loader.loadPage($page.loader.pages.playlist.topsongs); }); hotkeys('ctrl+5', function(event, handler){ // Prevent the default refresh event under WINDOWS system event.preventDefault(); $page.loader.loadPage($page.loader.pages.userlist.topuser); }); /** * TODO: add hotkeys for search, and find out how to override youtube * iframe key capturing */ HotKeys.globalInit = true; } }
# 调度器运行 调度器作是内核和用户共享的.调度器会被编译成elf可执行文件.同时映射在了内核和用户空间中. 内核和用户通过jp addr形式调用其中函数. 后续:vDSO形式提供给用户程序.当前rust语言针对riscv平台缺乏动态链接的支持.现在目前这部分还未和linux中的一致. 可能的办法:手动写stub函数... # 调度器在内核态(启用内核页表隔离机制 kpti) 某一时刻,系统中,进程,线程,协程的状态. 一个内核进程(内核本身) 多个常驻内核态的内核协程(均由调度器接口创建) 多个用户进程(由内核提供的接口创建),每个用户进程下包含多个用户线程(由调度器接口创建),每个用户线程下由多个用户协程(由调度器接口创建),这些用户进程会在运行时不断在用户进程与内核进程中反复横跳 注:内核调度器与用户态的调度器的区别:协程的退出操作会不同(最后一个内核协程退出会进入IDLE) # 2.1. 调度的对象 **用户进程 内核线程 内核协程 用户线程 用户协程(不直接参与调度)** # 2.2 调度的目标 优化协程实时性问题. (能让协程调度器感知到存在着比自己紧急的任务), 让紧急事件得到处理 more:还需细化 优化协程实时性问题: 需要内核以某种方式参与协程调度. 这要求内核维护全部或部分协程信息(如优先级). 以内核维护协程信息的不同分两种情况: 1.内核和用户共享协程队列 - tornado-os的做法.这时候协程执行器,可以放在内核中.用线程包装协程提供强制切换的可能 2.内核仅维护部分协程信息 - 内核只有每个进程下最高优先级协程的优先级. - - 内核调度协程的方式只能是调度协程所在的线程或者进程 - - 协程执行器中获取下一个任务时,检查内核提供的调度信息. 参考linux O(1)调度算法中的位图 1.每个用户进程下都维护一个位图. 每一位代表当前进程下相关优先级协程队列是否为空. 同时内核也维护一个位图. 2.在时钟中断进入内核时,内核将所有用户进程下的位图和内核中的位图做或运算.更新内核中的位图 3.用户在调度自己的协程时,会将内核提供的位图和自己的位图做比较,看是否有比自己优先级更高的协程存在. 如果有,则可以选择主动让出. # 2.3. 各对象具体的调度方式 1.用户进程队列,内核线程队列,内核协程队列,与内核在同一页表下,内核可以直接拿到其数据 2.用户线程,用户协程与内核属于不同地址空间 **用户进程** 目前执行一个调度循环. 不断从进程队列中取出进程执行 todo:进程不再是调度的单位 **内核线程** 内核线程平时执行一个idle_main, idle_main不断从线程池中获取一个可运行的线程. 当线程池没有任何可运行的线程,则会检查协程队列,如果还有协程新加入,则创建一个线程包含协程执行器继续运行, 如果空,则退出. 退出方式: 1.继续运行idle_main 2.使当前cpu进入低功耗状态(spin_loop) **内核协程** 内核协程主要执行异步系统调用,并根据实时性要求不同设置不同的优先级.由协程runtime调度. todo:时钟中断到来时检查用户线程是否需要让权(其他用户线程中是否有优先级更高的协程 **用户线程** 用户线程为内核参与用户协程调度的载体. 内核需处理用户线程退出的情况,回收其cpu资源. **用户协程** 获取最高优先级协程所在的地址空间. 并且提示下一个用户线程, 让它主动让出cpu,这便少了一次堆栈的保存和恢复. 可能的情况---最高优先级协程所在线程已经占有cpu资源 # 调度器在用户态 向内核提供最高优先级协程信息.
require 'rails_helper' describe Parsers::Xml::Cv::Importers::EnrollmentParser do let(:subject) { Parsers::Xml::Cv::Importers::EnrollmentParser.new(xml) } context "valid verified_policy" do let(:xml) { File.read(Rails.root.join("spec", "test_data", "importer_payloads", "policy.xml")) } context "get_enrollment_object" do it 'should return the enrollment as an object' do expect(subject.get_enrollment_object.class).to eq HbxEnrollment end it "should be employer_sponsored" do expect(subject.get_enrollment_object.kind).to eq 'employer_sponsored' end it "should get plan" do plan = subject.get_enrollment_object.plan expect(plan.name).to eq "BluePreferred PPO $1,000 100%/80%" expect(plan.active_year).to eq 2016 expect(plan.ehb).to eq 91.2 expect(plan.metal_level).to eq 'gold' expect(plan.coverage_kind).to eq "health_and_dental" end it "should get base info of enrollment" do enrollment = subject.get_enrollment_object expect(enrollment.elected_aptc_pct).to eq 0 expect(enrollment.applied_aptc_amount).to eq 0 expect(enrollment.carrier_profile_id).to eq '116036' expect(enrollment.coverage_kind).to eq 'health_and_dental' expect(enrollment.household.class).to eq Household expect(enrollment.employee_role.class).to eq EmployeeRole end it "should get family_members" do household = subject.get_enrollment_object.household expect(household.family.family_members.class).to eq Array expect(household.family.family_members.first.person.class).to eq Person expect(household.family.family_members.first.person.hbx_id).to eq '19801010' end it "should get hbx_enrollment_members" do enrollment = subject.get_enrollment_object expect(enrollment.hbx_enrollment_members.class).to eq Array expect(enrollment.hbx_enrollment_members.first.class).to eq HbxEnrollmentMember end it "should get hbx_id by policy" do enrollment = subject.get_enrollment_object expect(enrollment.hbx_id).to eq '6011122' end it "should get fein and legal_name by employee_role" do employee_role = subject.get_enrollment_object.employee_role org = employee_role.employer_profile.organization expect(org.hbx_id).to eq '555002222' expect(org.legal_name).to eq 'United States Senate' end it "should get effective_on and terminated_on by is_subscriber" do enrollment = subject.get_enrollment_object expect(enrollment.effective_on).to eq Date.new(2016,1,1) expect(enrollment.terminated_on).to eq Date.new(2016,12,31) end context 'person relationships' do before do @primary_person = subject.get_enrollment_object.family.primary_person end it 'should only create relationships to dependents' do expect(@primary_person.person_relationships.map(&:kind)).to eq(['spouse']) end it 'should not create self relationship into the db' do expect(@primary_person.person_relationships.map(&:kind)).not_to include('self') end it 'should not create any relationships from primary to primary' do expect(@primary_person.person_relationships.where(relative_id: @primary_person.id).first).to be_nil end end end context "get_broker_role_object" do it "should get broker_role" do broker_role = subject.get_broker_role_object expect(broker_role.class).to eq BrokerRole end it "should get broker_role info" do broker_role = subject.get_broker_role_object expect(broker_role.npn).to eq '1023' expect(broker_role.person.first_name).to eq 'Acme' expect(broker_role.person.last_name).to eq 'Broker' end end end context "valid individual policy" do let(:xml) { File.read(Rails.root.join("spec", "test_data", "importer_payloads", "individual_policy.xml")) } it "should be individual" do expect(subject.get_enrollment_object.kind).to eq 'individual' end it "should get applied_aptc_amount" do enrollment = subject.get_enrollment_object expect(enrollment.applied_aptc_amount).to eq Money.new(19465) end context 'person relationships' do before do @primary_person = subject.get_enrollment_object.family.primary_person end it 'should only create relationships to dependents' do expect(@primary_person.person_relationships.map(&:kind)).to eq(['spouse']) end it 'should not create self relationship into the db' do expect(@primary_person.person_relationships.map(&:kind)).not_to include('self') end it 'should not create any relationships from primary to primary' do expect(@primary_person.person_relationships.where(relative_id: @primary_person.id).first).to be_nil end end end end
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-} module Network.IRC.Bot.Commands where import Control.Applicative import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.Data import Data.Monoid ((<>)) import Network.IRC (Message(Message, msg_prefix, msg_command, msg_params), Command, Prefix(NickName)) import Network.IRC.Bot.BotMonad (BotMonad, askMessage, sendMessage) type HostName = ByteString -- * Commands cmd :: (Functor m, MonadPlus m, BotMonad m) => Command -> m () cmd cmdName = do command' <- msg_command <$> askMessage if cmdName == command' then return () else mzero data Ping = Ping HostName deriving (Eq, Ord, Read, Show, Data, Typeable) ping :: (Functor m, MonadPlus m, BotMonad m) => m Ping ping = do cmd "PING" params <- msg_params <$> askMessage case params of (hostName:_) -> return $ Ping hostName _ -> mzero data PrivMsg = PrivMsg { prefix :: (Maybe Prefix) , receivers :: [ByteString] , msg :: ByteString } deriving (Eq, Read, Show) privMsg :: (Functor m, MonadPlus m, BotMonad m) => m PrivMsg privMsg = do msg' <- askMessage maybe mzero return (toPrivMsg msg') toPrivMsg :: Message -> Maybe PrivMsg toPrivMsg m = let cmd' = msg_command m params = msg_params m prefix' = msg_prefix m in case cmd' of "PRIVMSG" -> Just $ PrivMsg prefix' (init params) (last params) _ -> Nothing class ToMessage a where toMessage :: a -> Message sendCommand :: (ToMessage c, BotMonad m, Functor m) => c -> m () sendCommand c = sendMessage (toMessage c) data Pong = Pong HostName deriving (Eq, Ord, Read, Show, Data, Typeable) instance ToMessage Pong where toMessage (Pong hostName) = Message Nothing "PONG" [hostName] instance ToMessage PrivMsg where toMessage (PrivMsg prefix' receivers' msg') = Message prefix' "PRIVMSG" (receivers' <> [msg']) data Notice = Notice { noticePrefix :: (Maybe Prefix) , noticeReceivers :: [ByteString] , noticeMsg :: ByteString } deriving (Eq, Read, Show) instance ToMessage Notice where toMessage (Notice prefix' receivers' msg') = Message prefix' "NOTICE" (receivers' <> [msg']) -- | get the nickname of the user who sent the message askSenderNickName :: (BotMonad m) => m (Maybe ByteString) askSenderNickName = do msg' <- askMessage case msg_prefix msg' of (Just (NickName nick _ _)) -> return (Just nick) _ -> return Nothing -- | figure out who to reply to for a given `Message` -- -- If message was sent to a #channel reply to the channel. Otherwise reply to the sender. replyTo :: (BotMonad m) => m (Maybe ByteString) replyTo = do priv <- privMsg let receiver = head (receivers priv) if ("#" `B.isPrefixOf` receiver) then return (Just receiver) else askSenderNickName -- | returns the receiver of a message -- -- if multiple receivers, it returns only the first askReceiver :: (Alternative m, BotMonad m) => m (Maybe ByteString) askReceiver = do priv <- privMsg return (Just (head $ receivers priv)) <|> do return Nothing
/* * Licensed to the Fabio Iwakoshi under one or more contributor license agreements. The ASF licenses * this file to You 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 br.com.iwakoshi.cinemaapi.config.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * A class extending {@link Application} and annotated with @ApplicationPath is the Java EE 6 "no * XML" approach to activating JAX-RS. * * <p> * Resources are served relative to the servlet path specified in the {@link ApplicationPath} * annotation. * </p> * * @author Fabio Iwakoshi */ @ApplicationPath("/api") public class JaxRsActivator extends Application { /* class body intentionally left blank */ }
# 这个脚本演示如何通过PowerShell管理Office 365应用程序 # 作者:陈希章 《Office 365 开发入门指南》第二版 于 2019-2-9 # 准备工作,请通过单独打开一个Powershell窗口,并用管理员方式打开 # Install-Module -Name AzureAD # 连接到Azure AD Connect-AzureAD # 连接到国内版Azure AD Connect-AzureAD -AzureEnvironmentName AzureChinaCloud # 获取所有的应用程序列表 Get-AzureADApplication # 获取某个应用程序的详细信息 Get-AzureADApplication -ObjectId xxxxxxxxx # 创建一个新的应用程序(客户端) $clientapp = New-AzureADApplication -ReplyUrls "" -PublicClient $true -DisplayName "xxxx" # 创建一个新的应用程序(网页),需要有Homepage和IdentitierUris # $webapp = New-AzureADApplication -DisplayName $name -ReplyUrls $replyurl -Homepage "https://websample.com" -IdentifierUris "https://websample.com" # 定义权限 $graphrequest = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess" $graphrequest.ResourceAccess = New-Object -TypeName "System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess]" $ids = @("024d486e-b451-40bb-833d-3e66d98c5c73", "e383f46e-2787-4529-855e-0e479a3ffac0", "e1fe6dd8-ba31-4d61-89e7-88639da4683d", "b340eb25-3456-403f-be2f-af7a0d370277") foreach ($id in $ids) { $obj = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList $id, "Scope" $graphrequest.ResourceAccess.Add($obj) } $graphrequest.ResourceAppId = "00000003-0000-0000-c000-000000000000" # 权限绑定 Set-AzureADApplication -ObjectId $clientapp.ObjectId -RequiredResourceAccess ($graphrequest) # 完成管理员授权 $IsGallatin = $true if ($IsGallatin) { Start-Process ("https://login.chinacloudapi.cn/common/adminconsent?client_id=" + $clientapp.AppId + "&state=12345&redirect_uri=https://developer.microsoft.com/en-us/graph/") } else { Start-Process ("https://login.microsoftonline.com/common/adminconsent?client_id=" + $clientapp.AppId + "&state=12345&redirect_uri=https://developer.microsoft.com/en-us/graph/") } # 理解ServicePricipal Get-AzureADServicePrincipal Get-AzureADServicePrincipal -ObjectId 3319d71d-8dfc-42ff-8fa0-0aa64f553350 #Microsoft Graph这个服务组件
import 'package:dartz/dartz.dart'; import 'package:dio/dio.dart'; import 'package:flutter_credo/core/constant/string_constants.dart'; import 'package:flutter_credo/core/errors/credo_exceptions.dart'; import 'package:flutter_credo/core/network/http_service_requester.dart'; import 'package:flutter_credo/core/utils/util.dart'; import 'package:flutter_credo/src/data/data_source/remote_datasource.dart'; import 'package:flutter_credo/src/data/models/init_payment_response_model.dart'; import 'package:flutter_credo/src/data/models/third_party_payment_response_model.dart'; import 'package:flutter_credo/src/data/models/verify_card_response_model.dart'; import 'package:flutter_credo/src/data/models/verify_transaction_response.dart'; class CredoSdkRepository { late CredoRemoteDataSource credoRemoteDataSource; CredoSdkRepository() { this.credoRemoteDataSource = CredoRemoteDataSourceImpl( HttpServiceRequester(), ); } Future<Either<CredoException, InitPaymentResponse>> initialPayment({ required double amount, required String currency, String? redirectUrl, String? transactionRef, String? paymentOptions, required String customerEmail, required String customerName, required String customerPhoneNo, required String publicKey, }) async { try { InitPaymentResponse initPaymentResponseModel = await credoRemoteDataSource.initialPayment( amount: amount, currency: currency, transactionRef: transactionRef == null || transactionRef.isEmpty ? Utils.getRandomString() : transactionRef, paymentOptions: paymentOptions, customerEmail: customerEmail, customerName: customerName, publicKey: publicKey, customerPhoneNo: customerPhoneNo, redirectUrl: redirectUrl, ); return Right(initPaymentResponseModel); } catch (e) { if (e is DioError) { if (e.response!.statusCode! >= 500) { return Left( CredoException( message: 'Internal server error, please try again', ), ); } return Left( CredoException( message: InitPaymentResponse.fromErrorMap( e.response!.data, ).message, ), ); } return Left( CredoException( message: StringConstants.sthWentWrong, ), ); } } Future<Either<CredoException, ThirdPartyPaymentResponse>> checkOut({ required String orderCurrency, required String cardNumber, required String expiryMonth, required String expiryYear, required String securityCode, required String transRef, String? customerEmail, String? customerName, String? customerPhoneNo, required String? paymentSlug, required String secretKey, double? orderAmount, }) async { try { VerifyCardResponse verifyCardResponseModel = await credoRemoteDataSource.verifyCardDetails( cardNumber: cardNumber, orderCurrency: orderCurrency, paymentSlug: paymentSlug, secretKey: secretKey, ); if (verifyCardResponseModel.gatewayRecommendation != 'PROCEED') { throw CardException('Please confirm your card number and try again..'); } ThirdPartyPaymentResponse thirdPartyPaymentResponse = await credoRemoteDataSource.thirdPartyPay( orderCurrency: orderCurrency, cardNumber: cardNumber, expiryMonth: expiryMonth, expiryYear: expiryYear, securityCode: securityCode, transRef: transRef, customerEmail: customerEmail, customerName: customerName, customerPhoneNo: customerPhoneNo, paymentSlug: paymentSlug, orderAmount: orderAmount, secretKey: secretKey, ); return Right(thirdPartyPaymentResponse); } catch (e) { if (e is DioError) { return Left( CredoException( message: ThirdPartyPaymentResponse.fromErrorMap( e.response!.data, ).message, ), ); } else if (e is CredoException) { return Left(e); } return Left( CredoException( message: StringConstants.sthWentWrong, ), ); } } Future<Either<CredoException, VerifyCardResponse>> verifyCard({ required String cardNumber, required String orderCurrency, required String paymentSlug, required String secretKey, }) async { try { VerifyCardResponse verifyCardResponseModel = await credoRemoteDataSource.verifyCardDetails( cardNumber: cardNumber, orderCurrency: orderCurrency, paymentSlug: paymentSlug, secretKey: secretKey, ); return Right(verifyCardResponseModel); } catch (e) { if (e is DioError) { return Left( CredoException( message: VerifyCardResponse.fromErrorMap( e.response!.data, ).message, ), ); } return Left( CredoException( message: StringConstants.sthWentWrong, ), ); } } Future<Either<CredoException, VerifyTransactionResponse>> verifyTransaction({ required String transactionRef, required String secretKey, }) async { try { VerifyTransactionResponse verifyTransactionResponseModel = await credoRemoteDataSource.verifyTransaction( transactionRef: transactionRef, secretKey: secretKey, ); return Right(verifyTransactionResponseModel); } catch (e) { if (e is DioError) { return Left( CredoException( message: VerifyTransactionResponse.fromErrorMap( e.response!.data, ).message, ), ); } return Left( CredoException( message: StringConstants.sthWentWrong, ), ); } } }
package exam.arena; import exam.characters.ComicCharacter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Created by IntelliJ IDEA. * User: LAPD * Date: 8.7.2018 г. * Time: 09:53 ч. */ public class ArenaImpl implements Arena { private String arenaName; private List<ComicCharacter> heroes; private List<ComicCharacter> antiHeroes; private int capacity; public ArenaImpl(String arenaName, int capacity) { setArenaName(arenaName); this.heroes = new ArrayList<>(); this.antiHeroes = new ArrayList<>(); setCapacity(capacity); } private void setArenaName(String arenaName) { this.arenaName = arenaName; } private void setCapacity(int capacity) { this.capacity = capacity; } public List<ComicCharacter> getHeroes() { return Collections.unmodifiableList(heroes); } public List<ComicCharacter> getAntiHeroes() { return Collections.unmodifiableList(antiHeroes); } @Override public String getArenaName() { return this.arenaName; } @Override public boolean isArenaFull() { return heroes.size() + antiHeroes.size() >= capacity; } @Override public void addHero(ComicCharacter hero) { this.heroes.add(hero); } @Override public void addAntiHero(ComicCharacter antiHero) { this.antiHeroes.add(antiHero); } @Override public boolean fightHeroes() { List<ComicCharacter> firstFighters = null; List<ComicCharacter> secondFighters = null; final String heroesString = "heroes"; final String antiheroesString = "antiHeroes"; String firstCharType; if (heroes.size() >= antiHeroes.size()) { firstFighters = antiHeroes; secondFighters = heroes; firstCharType = antiheroesString; } else { firstFighters = heroes; secondFighters = antiHeroes; firstCharType = heroesString; } while (true) { int endIndex; endIndex = Math.min(firstFighters.size(), secondFighters.size()); for (int i = 0; i < endIndex; i++) { secondFighters.get(i) .takeDamage(firstFighters.get(i) .attack()); } secondFighters = secondFighters.stream() .filter(f -> f.getHealth() > 0) .collect(Collectors.toList()); if (secondFighters.size() == 0) { switch (firstCharType) { case heroesString: antiHeroes = secondFighters; break; case antiheroesString: heroes = secondFighters; break; } break; } endIndex = Math.min(firstFighters.size(), secondFighters.size()); for (int i = 0; i < endIndex; i++) { firstFighters.get(i) .takeDamage(secondFighters.get(i) .attack()); } firstFighters = firstFighters.stream() .filter(f -> f.getHealth() > 0) .collect(Collectors.toList()); if (firstFighters.size() == 0) { switch (firstCharType) { case heroesString: heroes = firstFighters; break; case antiheroesString: antiHeroes = firstFighters; break; } break; } } if (heroes.size() == 0) { return false; } else { return true; } } }
angular.module('bingo') .controller('BingoController', ['$scope', '$http', '$interval', function ($scope, $http, $interval) { var label_AP_START = 'Start Auto-Play'; var label_AP_STOP = 'Stop Auto-Play'; var autoPlayTimer = undefined; var autoPlay = 0; var bingoApi = 'http://localhost:8001/bingo/'; var bingoCall = bingoApi + 'call/'; var bingoSpeak = bingoApi + 'speak/'; var autoSpeak = 20; var numbers = []; $scope.inProgress = 0; $scope.remaining = ''; $scope.called = ''; $scope.lastNumber = ''; $scope.ballIndex = 0; $scope.autoPlayLabel = label_AP_START; /** * Prepares a new game. * * We set the current number to a smiley until one is * called. The number list is initialised and we reset * the display statistics ($apply will do this for us). */ $scope.newGame = function() { numbers = $scope.shuffledNumbers(); $scope.currentNumber = ":)"; $scope.calledNumbers = []; $scope.remaining = numbers.length; }; /** * Auto-play! Now the caller can play as well. * * This feature shows how to use the $interval service * for timed, repeated event management in AngularJS. */ $scope.toggleAutoGame = function() { autoPlay = 1 - autoPlay; if (1 == autoPlay) { $scope.autoPlayLabel = label_AP_STOP; autoPlayTimer = $interval( function() { $scope.nextNumber(); }, 5000); } else { $scope.autoPlayLabel = label_AP_START; if (angular.isDefined(autoPlayTimer)) { $interval.cancel(autoPlayTimer); autoPlayTimer = undefined; } } }; /** * Say something silly after a certain number of calls. * * In our household it is customary to mention "sweating" a bit as * the tension mounts during the game. */ $scope.autoSpeakUpdate = function() { if (--autoSpeak <= 0) { autoSpeak = 7; var text = _.sample([ "I'm a bit sweaty, don't know about you!", "Anybody starting to sweat yet?", "I'm sweating, open a window!" ]); $http .post(bingoSpeak, text) .success(function(){ $scope.inProgress = 0; }); } else { $scope.inProgress = 0; } }; /** * Handles displaying the next number to be called. * * The next number from the list is read, the value is * sent via a GET request to ber verbalised and finally * we see if it's time to start syaing random silly * things if more than a certain number of balls are played. */ $scope.nextNumber = function() { if ($scope.ballIndex < numbers.length) { $scope.inProgress = 1; var ballNumber = numbers[$scope.ballIndex]; $scope.buttonCall($scope.ballIndex); $scope.currentNumber = ballNumber; $scope.lastNumber = ballNumber; $scope.ballIndex++; $scope.calledNumbers.push(ballNumber); $scope.remaining--; } }; /** * Call out the value of a ball button when clicked. */ $scope.buttonCall = function(ballIndex) { $http .get(bingoCall + numbers[ballIndex]) .success(function() { console.log("NUMBER DONE"); $scope.autoSpeakUpdate(); }); }; /** * Returns an array of the numbers 1-90 shuffled. * Behold the glory that is underscore.js! ;) */ $scope.shuffledNumbers = function() { return _.chain(_.times(90, function(n){return n+1;})) .shuffle() .value(); }; }]);
# frozen_string_literal: true module Agents class BaseController < ApplicationController def sub_layout "agents" end end end
#include "database.h" int main(int argc, char * argv[]) { srand(time(0)); ifstream input("data.txt"); ofstream output("report.txt"); Database D; int ID = 0, choice = -1; double sales = 0; string f_name, l_name; while(input >> ID >> sales >> f_name >> l_name){ D.insert(ID, sales, f_name, l_name); D.insertID(ID, sales, f_name, l_name); } printMenu(); while(choice != 0) { cout << "Enter a menu command: "; cin >> choice; switch(choice) { cout << choice; case 1: D.print(); break; case 2: cout << "Enter employee first name: "; cin >> f_name; cout << "Enter employee last name: "; cin >> l_name; cout << "Enter employee sales: "; cin >> sales; D.insert(rand() % 100 + 1, sales, f_name, l_name); break; case 3: cout << "Enter the last name of an Employee to remove: "; cin >> l_name; if(!D.remove(l_name)) cout << "Employee not in the database." << endl; break; case 4: cout << "Enter the last name of an employee to search for: "; cin >> l_name; D.search_lastName(l_name); break; case 5: cout << "Enter the ID of an employee to search for: "; cin >> ID; if(!D.search_ID(ID)) cout << "Employee not in the database." << endl; break; case 6: cout << endl; printMenu(); break; case 0: break; default: cout << "Not a valid command." << endl; } } D.sumAll(); D.calcAverage(); D.report(output); return 0; }
package xyz.bcheng.bitcoinser import java.nio.ByteBuffer // TODO: This is pretty rough, rethink this trait Field[A] { // getLength must return a length (int). If no read is necessary, // the Field should return its configured length without reading. // If getLength is called on a buffer whose length has already been read, // the behavior is undefined. def getLength(buf: ByteBuffer): Int // The primary access points of Field are read and skip. // read returns the field type. If the length is not yet known, it is read // from the buffer. // Buffer's cursor is expected to be advanceable. This may require providing // Field with a copy of the buffer. However, Buffer's cursor must not be // assumed to be set at 0. def read(buf: ByteBuffer): A def skip(buf: ByteBuffer) { buf.position(getLength(buf) + buf.position) } // Read the raw underlying bytes corresponding to this field. protected def readBytes(buf: ByteBuffer): Array[Byte] = { val dst = new Array[Byte](getLength(buf)) buf.get(dst) dst } } trait VariableLengthField[A] extends Field[A] { def getVarLength(buf: ByteBuffer): Long = { BinUtil.readVarInt(buf) } } class Uint16() extends Field[Int] { def getLength(b: ByteBuffer): Int = { 2 } def read(buf: ByteBuffer): Int = { BinUtil.readUint16(buf) } } class Uint32() extends Field[Long] { def getLength(b: ByteBuffer): Int = { 4 } def read(buf: ByteBuffer): Long = { BinUtil.readUint32(buf) } } class ByteArray() extends VariableLengthField[Array[Byte]] { def getLength(buf: ByteBuffer): Int = { getVarLength(buf).toInt } def read(buf: ByteBuffer): Array[Byte] = { readBytes(buf) } } class TxHashReader() extends Field[TransactionHash] { def getLength(b: ByteBuffer): Int = { 32 } def read(buf: ByteBuffer): TransactionHash = { TransactionHash(readBytes(buf)) } }
// Type definitions for react-wait 0.3 // Project: https://github.com/f/react-wait#readme // Definitions by: Ifiok Jr. <https://github.com/ifiokjr> // Paweł Maciejewski <https://github.com/pwlmaciejewski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { ComponentType, FunctionComponent } from 'react'; export const Waiter: FunctionComponent; export interface WaitingContextWaitProps { fallback: JSX.Element; } export interface WaitProps extends WaitingContextWaitProps { on: string; } export interface WaitingContext { isWaiting(): boolean; startWaiting(): void; endWaiting(): void; Wait: ComponentType<WaitingContextWaitProps>; } export interface UseWaitAPI { /** * Returns an array of waiters. */ waiters: string[]; /** * Using Wait Component * * ```tsx * function Component() { * const { Wait } = useWait(); * return ( * <Wait on="the waiting message" fallback={<div>Waiting...</div>}> * The content after waiting done * </Wait> * ); * } * ``` * * Better example for a button with loading state: * ```tsx * <button disabled={isWaiting("creating user")}> * <Wait on="creating user" fallback={<div>Creating User...</div>}> * Create User * </Wait> * </button> * ``` */ Wait: ComponentType<WaitProps>; /** * Returns boolean value if any loader exists in context. * * ```tsx * const { anyWaiting } = useWait(); * return <button disabled={anyWaiting()}>Disabled while waiting</button>; * ``` */ anyWaiting(): boolean; /** * Returns boolean value if given loader exists in context. * * ```tsx * const { isWaiting } = useWait(); * return ( * <button disabled={isWaiting("creating user")}> * Disabled while creating user * </button> * ); * ``` */ isWaiting(waiter: string): boolean; /** * Starts the given waiter. * * ```tsx * const { startWaiting } = useWait(); * return <button onClick={() => startWaiting("message")}>Start</button>; * ``` */ startWaiting(waiter: string): void; /** * Stops the given waiter. * * ```tsx * const { end } = useWait(); * return <button onClick={() => endWaiting("message")}>Stop</button>; * ``` */ endWaiting(waiter: string): void; /** * Creates a waiting context. * * ```tsx * const { startWaiting, endWaiting, isWaiting, Wait } = createWaitingContext("creating user"); * return ( * <button disabled={isWaiting()}> * Disabled while creating user * </button> * ); * ``` */ createWaitingContext(waiter: string): WaitingContext; } export function useWait(): UseWaitAPI;
# PaperTrader 基于A股的回测账户类 ## 致谢 quantaxis qifiaccount 鸭神 ## 解决痛点 1. 当前的回测框架大多没有t+n的配置,在回测层面缺少约束 2. 除权除息数据大多采用复权的方式进行回测,本程序采用计算除权复权时候的账户变化来描述真实的账户变更 3. qifiaccount的文档缺失太多,而且与mongodb和页面的耦合程度较高,本着极简主义的思想,把耦合的部分用python实现,因此本程序的最佳实践是jupyter ## example 参考 回测-除权除息.ipynb ## FINAL 欢迎大家提bug!!!
package dotty.tools.dotc.transform import dotty.tools.dotc.ast.tpd import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Symbols.Symbol import dotty.tools.dotc.transform.MegaPhase.MiniPhase import dotty.tools.dotc.transform.SymUtils._ import scala.collection.mutable import java.util.IdentityHashMap object CollectNullableFields { val name: String = "collectNullableFields" val description: String = "collect fields that can be nulled out after use in lazy initialization" } /** Collect fields that can be nulled out after use in lazy initialization. * * This information is used during lazy val transformation to assign null to private * fields that are only used within a lazy val initializer. This is not just an optimization, * but is needed for correctness to prevent memory leaks. E.g. * * ```scala * class TestByNameLazy(byNameMsg: => String) { * lazy val byLazyValMsg = byNameMsg * } * ``` * * Here `byNameMsg` should be null out once `byLazyValMsg` is * initialised. * * A field is nullable if all the conditions below hold: * - belongs to a non trait-class * - is private[this] * - is not lazy * - its type is nullable after erasure * - is only used in a lazy val initializer * - defined in the same class as the lazy val */ class CollectNullableFields extends MiniPhase { import tpd._ override def phaseName: String = CollectNullableFields.name override def description: String = CollectNullableFields.description /** Running after `ElimByName` to see by names as nullable types. */ override def runsAfter: Set[String] = Set(ElimByName.name) private sealed trait FieldInfo private case object NotNullable extends FieldInfo private case class Nullable(by: Symbol) extends FieldInfo /** Whether or not a field is nullable */ private val nullability = new mutable.LinkedHashMap[Symbol, FieldInfo] private def recordUse(tree: Tree)(using Context): Tree = { val sym = tree.symbol val isNullablePrivateField = sym.isField && !sym.is(Lazy) && !sym.owner.is(Trait) && sym.initial.isAllOf(PrivateLocal) && // We need `isNullableClassAfterErasure` and not `isNullable` because // we care about the values as present in the JVM. sym.info.widenDealias.typeSymbol.isNullableClassAfterErasure if (isNullablePrivateField) nullability.get(sym) match { case Some(Nullable(from)) if from != ctx.owner => // used in multiple lazy val initializers nullability.put(sym, NotNullable) case None => // not in the map val from = ctx.owner val isNullable = from.is(Lazy, butNot = Module) && // is lazy val from.owner.isClass && // is field from.owner.eq(sym.owner) // is lazy val and field defined in the same class val info = if (isNullable) Nullable(from) else NotNullable nullability.put(sym, info) case _ => // Do nothing for: // - NotNullable // - Nullable(ctx.owner) } tree } override def transformIdent(tree: Ident)(using Context): Tree = recordUse(tree) override def transformSelect(tree: Select)(using Context): Tree = recordUse(tree) /** Map lazy values to the fields they should null after initialization. */ def lazyValNullables(using Context): IdentityHashMap[Symbol, mutable.ListBuffer[Symbol]] = { val result = new IdentityHashMap[Symbol, mutable.ListBuffer[Symbol]] nullability.foreach { case (sym, Nullable(from)) => val bldr = result.computeIfAbsent(from, _ => new mutable.ListBuffer) bldr += sym case _ => } result } }
sentry_dsn = Rails.configuration.sentry_dsn if sentry_dsn require 'raven' Raven.configure do |config| config.processors -= [Raven::Processor::PostData] config.dsn = sentry_dsn end else # (Rails logger is not initialized yet) STDOUT.puts '[WARN] Sentry DSN is not set (SENTRY_DSN)' end
#include <sleip/dynamic_array.hpp> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <boost/core/lightweight_test.hpp> namespace ipc = boost::interprocess; #ifdef BOOST_NO_EXCEPTIONS #include <iostream> #include <exception> namespace boost { void throw_exception(std::exception const& e) { std::cerr << "Exception generated in noexcept code\nError: " << e.what() << "\n\n"; std::terminate(); } } // namespace boost #endif void test_shmem_allocator() { // Remove shared memory on construction and destruction struct shm_remove { shm_remove() { ipc::shared_memory_object::remove("MySharedMemory"); } ~shm_remove() { ipc::shared_memory_object::remove("MySharedMemory"); } } remover; // Create shared memory auto segment = ipc::managed_shared_memory(ipc::create_only, "MySharedMemory", // segment name 65536); // Create an allocator that allocates ints from the managed segment auto allocator_instance = ipc::allocator<int, ipc::managed_shared_memory::segment_manager>(segment.get_segment_manager()); static_assert( !std::is_same_v<typename std::allocator_traits<ipc::allocator< int, ipc::managed_shared_memory::segment_manager>>::value_type*, typename std::allocator_traits< ipc::allocator<int, ipc::managed_shared_memory::segment_manager>>::pointer>, "Must test fancy ::pointer types!"); auto a = sleip::dynamic_array<int, ipc::allocator<int, ipc::managed_shared_memory::segment_manager>>( std::size_t{128}, 1, allocator_instance); auto b = sleip::dynamic_array<int, ipc::allocator<int, ipc::managed_shared_memory::segment_manager>>( std::size_t{128}, -1, allocator_instance); BOOST_TEST((a.get_allocator() == allocator_instance)); BOOST_TEST((b.get_allocator() == allocator_instance)); BOOST_TEST_EQ(a.size(), 128); BOOST_TEST_EQ(b.size(), a.size()); a.fill(-1); BOOST_TEST_ALL_EQ(a.begin(), a.end(), b.begin(), b.end()); } int main() { test_shmem_allocator(); return boost::report_errors(); }
import { Component, Input } from '@angular/core'; import { FormGroup, AbstractControl, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'ach-information', templateUrl: './ach_information.component.html' }) export class AchInformationComponent { @Input("parentForm") public parentForm: FormGroup; public achGroup: FormGroup; ngOnInit() { this.achGroup = new FormGroup({ ach_account: new FormControl(''), ach_routing: new FormControl(''), ach_routing_confirmation: new FormControl(''), }); this.parentForm.addControl("ach_information", this.achGroup); } public errorClassFor(control : AbstractControl) : String { return (this.hasErrors(control) ? " has-error" : ""); } public hasErrors(control : AbstractControl) : Boolean { return ((control.touched || control.dirty) && !control.valid); } }
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} module Controllers.Todo ( viewItem, updateItem, removeItem ) where import Control.Monad.IO.Class import Data.Aeson hiding (Success) import Data.List.Safe ((!!)) import Data.Validation import Data.Traversable (traverse) import GHC.Generics import Prelude hiding ((!!)) import Servant import Controllers.Todos import Routes.Todos import Models.Todos import Models.Todo import Utils.SQLiteDBUtils (deleteItemFromDb, getItemFromDb, updateItemInDb) import Utils.TodoUtils (makeError) import Utils.TodoValidation (mergeErrorMessages, validateInputDateFormat) cantFindItemError = "Invalid item index" viewItem :: FilePath -> ItemIndex -> Servant.Handler Item viewItem dataPath idx = do eithItem <- liftIO $ getItemFromDb dataPath idx case eithItem of Left e -> throwError $ makeError err500 e Right ([]) -> throwError $ makeError err500 ("Item with " ++ (show idx) ++ " is not found.") Right (item:xs) -> return item getUpdateDueBy :: Maybe ItemUpdateDueBy -> Servant.Handler (Maybe ItemDueBy) getUpdateDueBy (Just mvalue) = case (traverse validateInputDateFormat mvalue) of Failure l -> throwError $ makeError err400 (mergeErrorMessages l) Success dueByDate -> return dueByDate getUpdateDueBy Nothing = return Nothing updateItem :: FilePath -> ItemIndex -> ItemUpdate -> Servant.Handler Item updateItem dataPath idx (ItemUpdate mbTitle mbDescription mbPriority mbDueBy) = do validatedMbDueBy <- getUpdateDueBy mbDueBy eithItem <- liftIO $ getItemFromDb dataPath idx case eithItem of Left e -> throwError $ makeError err500 e Right ([]) -> throwError $ makeError err500 ("Item with " ++ (show idx) ++ " is not found.") Right (item:xs) -> do let update (Item id title description priority dueBy) = Item id (updateField mbTitle title) (updateField mbDescription description) (updateField mbPriority priority) (updateField validatedMbDueBy dueBy) updateField (Just value) _ = value updateField Nothing value = value updateResult = update item result <- liftIO $ updateItemInDb dataPath updateResult case result of Right _ -> return updateResult Left e -> throwError $ makeError err500 e -- updateItem :: FilePath -> ItemIndex -> ItemUpdate -> Servant.Handler Item -- updateItem dataPath idx (ItemUpdate mbTitle mbDescription mbPriority mbDueBy) = do -- validatedMbDueBy <- getUpdateDueBy mbDueBy -- let updateResult = -- [ -- ("title", pack (updateField mbTitle)), -- ("description", pack (updateField mbDescription) ), -- ("priority", pack (updateField mbPriority)), -- ("dueBy", pack (updateField validatedMbDueBy)), -- ("id", pack id) -- ] -- updateField (Just value) = value -- updateField Nothing = Nothing -- result <- liftIO $ updateItemInDb dataPath updateResult -- case result of -- Right _ -> return result -- Left e -> throwError $ makeError err500 e removeItem :: FilePath -> ItemIndex -> Servant.Handler NoContent removeItem dataPath idx = do result <- liftIO $ deleteItemFromDb dataPath idx case result of Right _ -> return NoContent Left e -> throwError $ makeError err500 e
#!/usr/bin/perl use strict; use warnings; # two randomly generated DNA sequences my $DNA1 = 'TCGCGTAAGATGCAGGCTGTGTAGCATGCCCGG'; my $DNA2 = 'AAATAACGTTCCGGTCAACTTGTTA'; print "The original fragments are as follows: \n\n"; print $DNA1,"\n"; print $DNA2,"\n\n"; # Concatenate the strings using string interpolation my $DNA3 = "$DNA1$DNA2"; print "The concatenated string is: $DNA3\n"; # Concatenate using the dot operator $DNA3 = $DNA1 . $DNA2; print "The concatenated string still is: $DNA3\n"; print "We could also just print the two fragments as such:\n",$DNA1,$DNA2,"\n"; my $num = 17; print "Just for kicks, here is a numeric scalar: ", $num, "\n";
-- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Хост: 127.0.0.1:3306 -- Время создания: Окт 25 2017 г., 22:49 -- Версия сервера: 5.5.53 -- Версия PHP: 5.5.38 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- База данных: `magazin` -- -- -------------------------------------------------------- -- -- Структура таблицы `block_category` -- CREATE TABLE `block_category` ( `id_category` int(11) NOT NULL, `name_category` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `block_category` -- INSERT INTO `block_category` (`id_category`, `name_category`) VALUES (1, 'clother'), (2, 'orgteh'), (3, 'show_car'), (4, 'washing'); -- -------------------------------------------------------- -- -- Структура таблицы `block_name` -- CREATE TABLE `block_name` ( `id` int(11) NOT NULL, `block_title` varchar(100) NOT NULL, `block_content` varchar(100) NOT NULL, `id_category` int(11) NOT NULL, `login` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `block_name` -- INSERT INTO `block_name` (`id`, `block_title`, `block_content`, `id_category`, `login`) VALUES (1, 'cvcs', ' svsdvvsd', 2, 'Ovso'), (2, 'asdcsdsd', '55555', 1, 'Ovso'); -- -------------------------------------------------------- -- -- Структура таблицы `registered_users` -- CREATE TABLE `registered_users` ( `id` int(11) NOT NULL, `login` varchar(100) NOT NULL, `email` varchar(50) CHARACTER SET utf32 NOT NULL, `password` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `registered_users` -- INSERT INTO `registered_users` (`id`, `login`, `email`, `password`) VALUES (8, 'Ovso', 'ovsyankinds@gmail.com', '12345'); -- -------------------------------------------------------- -- -- Структура таблицы `users` -- CREATE TABLE `users` ( `user_id` int(11) NOT NULL, `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `gender` varchar(255) NOT NULL, `create_date` date NOT NULL, `phone` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `users` -- INSERT INTO `users` (`user_id`, `username`, `email`, `password`, `gender`, `create_date`, `phone`) VALUES (3, 'Ovso', 'ovsyankinds@gmail.com', '12345', 'Male', '2017-03-21', '12345555'), (4, 'Ovso', 'ovsyankinds@gmail.com', '12345', 'Male', '2017-03-21', '123455555'), (5, 'ovsyankinds@gmail.com', 'ovsyankinds@gmail.com', '827ccb0eea8a706c4c34a16891f84e7b', 'Male', '2017-04-01', 'aff'); -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `block_category` -- ALTER TABLE `block_category` ADD PRIMARY KEY (`id_category`); -- -- Индексы таблицы `block_name` -- ALTER TABLE `block_name` ADD PRIMARY KEY (`id`); -- -- Индексы таблицы `registered_users` -- ALTER TABLE `registered_users` ADD PRIMARY KEY (`id`); -- -- Индексы таблицы `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT для сохранённых таблиц -- -- -- AUTO_INCREMENT для таблицы `block_category` -- ALTER TABLE `block_category` MODIFY `id_category` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT для таблицы `block_name` -- ALTER TABLE `block_name` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT для таблицы `registered_users` -- ALTER TABLE `registered_users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT для таблицы `users` -- ALTER TABLE `users` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
[Music] you I need to tell you all a story last year a woman by the name of Jordan Bella Meyer was sexually assaulted in virtual reality she was playing a video game with the system comprised of a headset which she could use to look around and a motion controller in each hand which he could use to reach out and interact the game system was able to superimpose an avatar onto her body a body which corresponding to her real one another player came up to miss Bella Meyer and reached for her breasts her groin later in an interview she described the feeling of violation as her husband and brother-in-law watched the feeling of that reality encroaching on this one take a second imagine looking down on a body that looks just the way you look that moves when you move and imagine watching someone touch and manipulate that body my name is Edmund King and I study law here at Maastricht University I wanted to know what this story meant I can tell you now there was no crime committed but there was harm there was no crime committed because we don&#39;t have fully developed rules for dealing with this kind of situation that is because virtual reality is a technology unlike anything that has come before in the case of printed media the sensory experience of the consumer is for the most part internalized visual media allows us to witness things we could not imagine yet we still have context we know that what is happening is happening on a screen because we&#39;re able to contextualize and separate the images from the realities of our homes or movie theaters virtual reality erodes that context this gives it a maze potential already it&#39;s being used by doctors to help correct lazy eyes by psychologists to help treat people for post-traumatic stress disorders and phobias educators are able to give their students experiences that would be impossible otherwise we rely on our senses to gain knowledge and information about the world around us as technology improves those same senses make less and less of a distinction between realities we are immersed in a world which is different from the one we inhabit in this moment so imagine the difference in sensation between pressing a button to shoot someone on a screen or having to stand over your victim move to pull out a weapon aim and actually pull the trigger that experience is bundled together with pretty much every other form of visual media games are games movies are movies they can be accessed just as easily and created just as freely despite the fact that the elevated sensory experience is different around the world our system of regulating access is primarily concerned with limiting liability of retailers at the point of physical sale so theoretically a child can&#39;t walk into a shop and buy mature rated content over the counter makes sense but online all any of us have to do is tick a box this offers very little in the way of real protection real safeguards a fractured system which doesn&#39;t take into account the homogeny of an open Internet until now that has been enough but moving forward we might need more let&#39;s go back to miss Bella Myers story we know how she accessed the game she wasn&#39;t a child who made it possible another conversation we might have is whether it is the call to create these experiences in such detail currently the authors of media are to a greater extent protected by their freedoms of expression that hasn&#39;t stopped governments across the world banning certain games and movies but once again there&#39;s no distinction between virtual reality and regular content this leaves gaps in the law as we try to apply existing norms to an evolving situation some will ask why a willing consumer should not be able to simulate a violent experience is this not over-regulation indeed a theoretical economic demand for simulated bloodshed might well be representative of an emerging societal norm of acceptance the thing is outside of well the military and certain controlled sporting environments violence is for the most part discouraged if not illegal is allowing the additional element of the physicality of VR to become mainstream overly desensitizing I have younger brothers and both of them are fully embracing different types of media and technology into their lives as they grow up Joshua who&#39;s the youngest he&#39;s still getting to grips with an iPad but Robert who is 14 finished building his first computer over the summer if I think about their relationship to technology compared to mine at their age it&#39;s almost inconceivable that we&#39;re part of the same generation it&#39;s equally inconceivable to consider the additional risks that they&#39;re exposed to we also need to talk about choice the difference between virtual reality and real life is that you are i engaging at any virtual activity is a question of choice the problem is that increasingly it isn&#39;t it isn&#39;t realistically feasible to exist without an email or not to part taking social media it&#39;s possible but often debilitating recently Finland became the first country to grant to its citizens as a right access to broadband internet everyone in this room has certain rights online not to have information stolen not to be bullied but miss Bella Mayer did not have the right to be treated any differently at what point do we accept that the inherent risk the potential harm is so great in an immersive environment that we need clearly defined rules virtual actions have all too real consequences at what point do we acknowledge that what happened to miss Bella Maier could happen to so many others and go unpunished virtual reality expands the intimacy with which we can interact online inevitably as we go forward it will become necessary but that&#39;s the beauty that&#39;s the beauty of virtual reality I&#39;m a huge proponent of making this technology mainstream I&#39;m excited and I know that when it is we will all be better off and it will act as a force for connecting the world this is the future ladies and gentlemen but we can only do that by building a cultural and legal platform I&#39;m not a professor I&#39;m not an expert I&#39;m not here to answer the questions that I&#39;ve raised today we have to do that together whether virtual content needs to have narrower access online whether developers can create freely whether we need to have clearly defined rights to guarantee a safe space for everyone information and debate the most valuable things we can have right now ladies and gentlemen there are so many different ways of looking and what Jordan Bella Maya story means this talk is about awareness of our evolving situation we&#39;ve sold problems like this in the past the creation of the Internet the rise of social media ever more closely integrated personal computers we will solve the problems of VR now the sooner we do the sooner we can start really protecting people and really using this technology what it is meant for and to its full potential thank you [Applause] [Music]
import numpy from .propertiesdata import PropertiesData # -------------------------------------------------------------------- # See cfdm.core.mixin.container.__docstring_substitution__ for {{...}} # docstring substitutions # -------------------------------------------------------------------- class PropertiesDataBounds(PropertiesData): """Mixin for a data array with bounds and descriptive properties. .. versionadded:: (cfdm) 1.7.0 """ def __init__( self, properties=None, data=None, bounds=None, geometry=None, interior_ring=None, source=None, copy=True, _use_data=True, ): """**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Parameter example:* ``properties={'standard_name': 'longitude'}`` {{init data: data_like, optional}} {{init bounds: `Bounds`, optional}} {{init geometry: `str`, optional}} {{init interior_ring: `InteriorRing`, optional}} source: optional Initialise the properties, geometry type, data, bounds and interior ring from those of *source*. {{init source}} {{init copy: `bool`, optional}} """ # Initialise properties and data super().__init__( properties=properties, data=data, source=source, copy=copy, _use_data=_use_data, ) # Get bounds, geometry type and interior ring from source if source is not None: try: bounds = source.get_bounds(None) except AttributeError: bounds = None try: geometry = source.get_geometry(None) except AttributeError: geometry = None try: interior_ring = source.get_interior_ring(None) except AttributeError: interior_ring = None # Initialise bounds if bounds is not None: if copy or not _use_data: bounds = bounds.copy(data=_use_data) self.set_bounds(bounds, copy=False) # Initialise the geometry type if geometry is not None: self.set_geometry(geometry) # Initialise interior ring if interior_ring is not None: if copy or not _use_data: interior_ring = interior_ring.copy(data=_use_data) self.set_interior_ring(interior_ring, copy=False) # ---------------------------------------------------------------- # Attributes # ---------------------------------------------------------------- @property def bounds(self): """Return the bounds. ``f.bounds`` is equivalent to ``f.get_bounds()`` .. versionadded:: (cfdm) 1.7.0 .. seealso:: `data`, `del_bounds`, `get_bounds`, `has_bounds`, `set_bounds` :Returns: `Bounds` The bounds. **Examples:** >>> c = {{package}}.{{class}}() >>> b = {{package}}.Bounds(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_bounds(b) >>> c.has_bounds() True >>> b = c.bounds >>> b <{{repr}}Bounds: (5, 2) > >>> b.data <{{repr}}Data(5, 2): [[0, ..., 9]]> >>> b.data.shape (5, 2) """ return self.get_bounds() @property def interior_ring(self): """Return the interior ring variable for polygon geometries. ``f.interior_ring`` is equivalent to ``f.get_interior_ring()`` .. versionadded:: (cfdm) 1.8.0 .. seealso:: `data`, `del_interior_ring`, `get_interior_ring`, `has_interior_ring`, `set_interior_ring` :Returns: `InteriorRing` The interior ring variable. **Examples:** >>> i = {{package}}.InteriorRing(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_interior_ring(i) >>> c.has_interior_ring() True >>> i = c.interior_ring >>> i <{{repr}}InteriorRing: (5, 2) > >>> i.data <{{repr}}Data(5, 2): [[0, ..., 9]]> >>> i.data.shape (5, 2) """ return self.get_interior_ring() # ---------------------------------------------------------------- # Methods # ---------------------------------------------------------------- def del_bounds(self, default=ValueError()): """Remove the bounds. .. versionadded:: (cfdm) 1.7.0 .. seealso:: `del_data`, `get_bounds`, `has_bounds`, `set_bounds` :Parameters: default: optional Return the value of the *default* parameter if bounds have not been set. {{default Exception}} :Returns: `Bounds` The removed bounds. **Examples:** >>> c = {{package}}.{{class}}() >>> b = {{package}}.Bounds(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_bounds(b) >>> c.has_bounds() True >>> c.get_bounds() <{{repr}}Bounds: (5, 2) > >>> b = c.del_bounds() >>> b <{{repr}}Bounds: (5, 2) > >>> c.has_bounds() False >>> print(c.get_bounds(None)) None >>> print(c.del_bounds(None)) None """ return self._del_component("bounds", default=default) # try: # return self._del_component("bounds") # except ValueError: # return self._default( # default, "{!r} has no bounds".format(self.__class__.__name__) # ) def del_geometry(self, default=ValueError()): """Remove the geometry type. .. versionadded:: (cfdm) 1.8.0 .. seealso:: `get_geometry`, `has_geometry`, `set_geometry` :Parameters: default: optional Return the value of the *default* parameter if the geometry type has not been set. {{default Exception}} :Returns: `str` The removed geometry type. **Examples:** >>> f = {{package}}.read('file.nc')[0] >>> c = f.construct('axis=X') >>> c.has_geometry() True >>> c.get_geometry() 'line' >>> b = c.del_geometry() >>> c.has_geometry() False >>> print(c.get_geometry(None)) None >>> c.set_geometry(b) >>> c.has_geometry() True """ return self._del_component("geometry", default=default) # try: # return self._del_component("geometry") # except ValueError: # return self._default( # default, # "{!r} has no geometry type".format(self.__class__.__name__), # ) def del_interior_ring(self, default=ValueError()): """Remove the geometry type. .. versionadded:: (cfdm) 1.8.6.0 .. seealso:: `data`, `del_interior_ring`, `has_interior_ring`, `interior_ring`, `set_interior_ring` :Parameters: default: optional Return the value of the *default* parameter if the geometry type has not been set. {{default Exception}} :Returns: `ÌnteriorRing` The removed interior ring variable. **Examples:** >>> c = {{package}}.{{class}}() >>> i = {{package}}.InteriorRing(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_interior_ring(i) >>> c.has_interior_ring() True >>> i = c.get_interior_ring() >>> i <{{repr}}InteriorRing: (5, 2) > >>> i.data <{{repr}}Data(5, 2): [[0, ..., 9]]> >>> i.data.shape (5, 2) >>> c.del_interior_ring() <{{repr}}InteriorRing: (5, 2) > >>> c.has_interior_ring() False >>> print(c.del_interior_ring(None)) None """ return self._del_component("interior_ring", default=default) # try: # return self._del_component("interior_ring") # except ValueError: # return self._default( # default, # "{!r} has no interior ring variable".format( # self.__class__.__name__ # ), # ) def get_bounds(self, default=ValueError()): """Return the bounds. .. versionadded:: (cfdm) 1.7.0 .. seealso:: `bounds`, `get_data`, `del_bounds`, `has_bounds`, `set_bounds` :Parameters: default: optional Return the value of the *default* parameter if bounds have not been set. {{default Exception}} :Returns: `Bounds` The bounds. **Examples:** >>> c = {{package}}.{{class}}() >>> b = {{package}}.Bounds(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_bounds(b) >>> c.has_bounds() True >>> c.get_bounds() <{{repr}}Bounds: (5, 2) > >>> b = c.del_bounds() >>> b <{{repr}}Bounds: (5, 2) > >>> c.has_bounds() False >>> print(c.get_bounds(None)) None >>> print(c.del_bounds(None)) None """ return self._get_component("bounds", default=default) # try: # return self._get_component("bounds") # except ValueError: # return self._default( # default, "{!r} has no bounds".format(self.__class__.__name__) # ) def get_geometry(self, default=ValueError()): """Return the geometry type. .. versionadded:: (cfdm) 1.8.0 .. seealso:: `has_geometry`, `set_geometry`, `del_geometry` :Parameters: default: optional Return the value of the *default* parameter if the geometry type has not been set. {{default Exception}} :Returns: `str` The geometry type. **Examples:** >>> f = {{package}}.read('file.nc')[0] >>> c = f.construct('axis=X') >>> c.has_geometry() True >>> c.get_geometry() 'line' >>> b = c.del_geometry() >>> c.has_geometry() False >>> print(c.get_geometry(None)) None >>> c.set_geometry(b) >>> c.has_geometry() True """ return self._get_component("geometry", default=default) # try: # return self._get_component("geometry") # except ValueError: # return self._default( # default, # "{!r} has no geometry type".format(self.__class__.__name__), # ) def get_interior_ring(self, default=ValueError()): """Return the interior ring variable for polygon geometries. ``f.get_interior_ring()`` is equivalent to ``f.interior_ring`` .. versionadded:: (cfdm) 1.8.0 .. seealso:: `data`, `del_interior_ring`, `has_interior_ring`, `interior_ring`, `set_interior_ring` :Parameters: default: optional Return the value of the *default* parameter if interior ring data have not been set. {{default Exception}} :Returns: `InteriorRing` The interior ring variable. **Examples:** >>> c = {{package}}.{{class}}() >>> i = {{package}}.InteriorRing(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_interior_ring(i) >>> c.has_interior_ring() True >>> i = c.get_interior_ring() >>> i <{{repr}}InteriorRing: (5, 2) > >>> i.data <{{repr}}Data(5, 2): [[0, ..., 9]]> >>> i.data.shape (5, 2) >>> c.del_interior_ring() <{{repr}}InteriorRing: (5, 2) > >>> c.has_interior_ring() False >>> print(c.del_interior_ring(None)) None """ return self._get_component("interior_ring", default=default) # try: # return self._get_component("interior_ring") # except ValueError: # return self._default( # default, # "{!r} has no interior ring variable".format( # self.__class__.__name__ # ), # ) def has_bounds(self): """Whether or not there are bounds. .. versionadded:: (cfdm) 1.7.0 .. seealso:: `del_bounds`, `get_bounds`, `has_data`, `set_bounds` :Returns: `bool` True if there are bounds, otherwise False. **Examples:** >>> c = {{package}}.{{class}}() >>> b = {{package}}.Bounds(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_bounds(b) >>> c.has_bounds() True >>> c.get_bounds() <{{repr}}Bounds: (5, 2) > >>> b = c.del_bounds() >>> b <{{repr}}Bounds: (5, 2) > >>> c.has_bounds() False >>> print(c.get_bounds(None)) None >>> print(c.del_bounds(None)) None """ return self._has_component("bounds") def has_geometry(self): """True if there is a geometry type. .. versionadded:: (cfdm) 1.8.0 .. seealso:: `get_geometry`, `set_geometry`, `del_geometry` :Returns: `bool` Whether or not there is a geometry type. **Examples:** >>> f = {{package}}.read('file.nc')[0] >>> c = f.construct('axis=X') >>> c.has_geometry() True >>> c.get_geometry() 'line' >>> b = c.del_geometry() >>> c.has_geometry() False >>> print(c.get_geometry(None)) None >>> c.set_geometry(b) >>> c.has_geometry() True """ return self._has_component("geometry") def has_interior_ring(self): """Whether or not there is an interior ring variable. .. versionadded:: (cfdm) 1.8.0 .. seealso:: `del_interior_ring`, `get_interior_ring`, `interior_ring`, `set_interior_ring` :Returns: `bool` True if there is an interior ring variable, otherwise False. **Examples:** >>> c = {{package}}.{{class}}() >>> i = {{package}}.InteriorRing(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_interior_ring(i) >>> c.has_interior_ring() True >>> i = c.get_interior_ring() >>> i <{{repr}}InteriorRing: (5, 2) > >>> i.data <{{repr}}Data(5, 2): [[0, ..., 9]]> >>> i.data.shape (5, 2) >>> c.del_interior_ring() <{{repr}}InteriorRing: (5, 2) > >>> c.has_interior_ring() False >>> print(c.del_interior_ring(None)) None """ return self._has_component("interior_ring") def set_bounds(self, bounds, copy=True): """Set the bounds. .. versionadded:: (cfdm) 1.7.0 .. seealso:: `del_bounds`, `get_bounds`, `has_bounds`, `set_data` :Parameters: data: `Bounds` The bounds to be inserted. copy: `bool`, optional If False then do not copy the bounds prior to insertion. By default the bounds are copied. :Returns: `None` **Examples:** >>> c = {{package}}.{{class}}() >>> b = {{package}}.Bounds(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_bounds(b) >>> c.has_bounds() True >>> c.get_bounds() <{{repr}}Bounds: (5, 2) > >>> b = c.del_bounds() >>> b <{{repr}}Bounds: (5, 2) > >>> c.has_bounds() False >>> print(c.get_bounds(None)) None >>> print(c.del_bounds(None)) None """ data = self.get_data(None) if data is not None: bounds_data = bounds.get_data(None) if bounds_data is not None and numpy.ndim( bounds_data ) <= numpy.ndim(data): raise ValueError( f"{bounds!r} must have more dimensions than " f"its parent {self!r}" ) if copy: bounds = bounds.copy() self._set_component("bounds", bounds, copy=False) def set_geometry(self, value): """Set the geometry type. .. versionadded:: (cfdm) 1.8.0 .. seealso:: `get_geometry`, `set_geometry`, `del_geometry` :Parameters: value: `str` The geometry type to set. :Returns: `None` **Examples:** >>> f = {{package}}.read('file.nc')[0] >>> c = f.construct('axis=X') >>> c.has_geometry() True >>> c.get_geometry() 'line' >>> b = c.del_geometry() >>> c.has_geometry() False >>> print(c.get_geometry(None)) None >>> c.set_geometry(b) >>> c.has_geometry() True """ self._set_component("geometry", value, copy=False) def set_interior_ring(self, interior_ring, copy=True): """Set the interior_ring. .. versionadded:: (cfdm) 1.8.0 .. seealso:: `del_interior_ring`, `get_interior_ring`, `interior_ring`, `has_interior_ring` :Parameters: interior_ring: `InteriorRing` The interior_ring to be inserted. copy: `bool`, optional If False then do not copy the interior_ring prior to insertion. By default the interior_ring are copied. :Returns: `None` **Examples:** >>> c = {{package}}.{{class}}() >>> i = {{package}}.InteriorRing(data={{package}}.Data(numpy.arange(10).reshape(5, 2))) >>> c.set_interior_ring(i) >>> c.has_interior_ring() True >>> i = c.get_interior_ring() >>> i <{{repr}}InteriorRing: (5, 2) > >>> i.data <{{repr}}Data(5, 2): [[0, ..., 9]]> >>> i.data.shape (5, 2) >>> c.del_interior_ring() <{{repr}}InteriorRing (5, 2) > >>> c.has_interior_ring() False >>> print(c.del_interior_ring(None)) None """ if copy: interior_ring = interior_ring.copy() self._set_component("interior_ring", interior_ring, copy=False)
class HorizontalSliderClass extends elementorModules.frontend.handlers.Base { getDefaultSettings() { return { selectors: { swiperContainer:'.twae-horizontal.swiper-container', nextButton: '.twae-button-next', prevButton: '.twae-button-prev', paginationEl: '.twae-pagination', }, }; } getDefaultElements() { const selectors = this.getSettings( 'selectors' ); return { $swiperContainer: this.$element.find( selectors.swiperContainer ), $nextButton: this.$element.find( selectors.nextButton ), $prevButton: this.$element.find( selectors.prevButton ), $paginationEl: this.$element.find( selectors.paginationEl ), }; } bindEvents() { var selector = this.elements.$swiperContainer, slidestoshow = selector.data("slidestoshow"), autoplay = selector.data("autoplay"), nextButton = this.elements.$nextButton, prevButton = this.elements.$prevButton, paginationEl = this.elements.$paginationEl; var Navigation; var lang_dir = selector.attr("dir"); if(lang_dir=='rtl'){ var Navigation = { nextEl: prevButton, prevEl: nextButton, } } else{ Navigation = { nextEl: nextButton, prevEl: prevButton, } } var swiper = new Swiper( selector, { spaceBetween: 10, autoplay:autoplay, delay: 5000, slidesPerView: slidestoshow, direction: 'horizontal', pagination: { el: paginationEl, type: 'progressbar', }, navigation: Navigation, // Responsive breakpoints breakpoints: { // when window width is >= 280px 280: { slidesPerView: 1, }, 768:{ slidesPerView: 3, }, 1024: { slidesPerView: slidestoshow, } }, }); } } jQuery( window ).on( 'elementor/frontend/init', () => { const addHandler = ( $element ) => { elementorFrontend.elementsHandler.addHandler( HorizontalSliderClass, { $element, }); }; elementorFrontend.hooks.addAction( 'frontend/element_ready/timeline-widget-addon.default', addHandler ); });
package typingsSlinky.colorConvert.anon import typingsSlinky.colorConvert.conversionsMod.HCG_ import typingsSlinky.colorConvert.conversionsMod.HSL_ import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait `20` extends StObject { def raw(from: HSL_): HCG_ = js.native @JSName("raw") var raw_Original: js.Function1[/* from */ HSL_, HCG_] = js.native }
# glommio [![CircleCI](https://circleci.com/gh/DataDog/glommio.svg?style=svg)](https://circleci.com/gh/DataDog/glommio) ## Join our Zulip community! If you are interested in Glommio consider joining our [Zulip](https://glommio.zulipchat.com) community. Come tell us about exciting applications you are building, ask for help, or really just chat with friends ## What is Glommio? Glommio (pronounced glo-mee-jow or |glomjəʊ|) is a Cooperative Thread-per-Core crate for Rust & Linux based on `io_uring`. Like other rust asynchronous crates it allows one to write asynchronous code that takes advantage of rust `async`/`await`, but unlike its counterparts it doesn't use helper threads anywhere. Using Glommio is not hard if you are familiar with rust async. All you have to do is: ```rust use glommio::prelude::*; LocalExecutorBuilder::new().spawn(|| async move { /// your code here }).unwrap(); ``` Please note Glommio requires at least 512 KiB of locked memory for `io_uring` to work. You can increase the `memlock` resource limit (rlimit) as follows: ```sh $ vi /etc/security/limits.conf * hard memlock 512 * soft memlock 512 ``` To make the new limits effective, you need to login to the machine again. You can verify that the limits are updated by running the following: ```sh $ ulimit -l 512 ``` For more details check out our [docs page](https://docs.rs/glommio/0.2.0-alpha/glommio/) and an [introductory article](https://www.datadoghq.com/blog/engineering/introducing-glommio/) ## Status Glommio is still considered an alpha release. The main reasons are: * The existing API is still evolving * There are still some uses of unsafe that can be avoided * There are features that are critical for a good thread per core system that are not implemented yet. The top one being: * per-shard memory allocator. Want to help bring us to production status sooner? PRs are welcome! ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
<?php return [ 'about_us' => 'About Us', 'terms_and_conditions' => 'Terms & Conditions', 'privacy_policy' => 'Privacy Policy', ];
package org.alien4cloud.tosca.editor.processors.workflow; import org.alien4cloud.tosca.editor.EditionContextManager; import org.alien4cloud.tosca.editor.operations.workflow.SwapStepOperation; import org.alien4cloud.tosca.model.Csar; import org.alien4cloud.tosca.model.templates.Topology; import org.alien4cloud.tosca.model.workflow.Workflow; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * Process the {@link SwapStepOperation} operation * Swaps two workflow steps */ @Slf4j @Component public class SwapStepProcessor extends AbstractWorkflowProcessor<SwapStepOperation> { @Override protected void processWorkflowOperation(Csar csar, Topology topology, SwapStepOperation operation, Workflow workflow) { log.debug("swapping step [ {} ] with [ {} ] in workflow [ {} ] from topology [ {} ]", operation.getStepId(), operation.getTargetStepId(), workflow.getName(), topology.getId()); workflowBuilderService.swapSteps(topology, csar, workflow.getName(), operation.getStepId(), operation.getTargetStepId()); } }
self.addEventListener("install", function (e) { e.waitUntil( fetch("/cache_manifest.json") .then(function (response) { return response.json(); }) .then(function (cacheManifest) { var cacheName = "cache:static:" + cacheManifest.version; var all = Object.values(cacheManifest.latest).filter(function (fn) { return fn.match(/^(images|css|js|fonts)/); }); caches.open(cacheName).then(function (cache) { return cache.addAll(all).then(function () { self.skipWaiting(); }); }); }) ); }); self.addEventListener("fetch", function (event) { event.respondWith( caches.match(event.request).then(function (response) { if (response) { return response; } return fetch(event.request); }) ); });
import { initializeApp } from 'firebase/app'; import { getFirestore } from 'firebase/firestore'; import { getAuth, GoogleAuthProvider } from 'firebase/auth'; import config from './config'; // svelte-balls // import config from './config'; // collisions export const fireapp = initializeApp(config); export const auth = getAuth(fireapp); export const googleAuth = new GoogleAuthProvider(); export const firestore = getFirestore(fireapp);
mod bigwig_sys; use bigwig_sys::*; use std::ffi::{CStr, CString}; use std::os::unix::ffi::OsStrExt; use std::path::Path; pub struct BigWigFile(*mut bigWigFile_t); impl Drop for BigWigFile { fn drop(&mut self) { unsafe { bwClose(self.0); } } } pub struct BigWigInterval { pub begin: u32, pub end: u32, pub value: f32, } pub struct BigWigIntervalIter { result: *mut bwOverlappingIntervals_t, idx: isize, } impl Drop for BigWigIntervalIter { fn drop(&mut self) { unsafe { bwDestroyOverlappingIntervals(self.result); } } } impl Iterator for BigWigIntervalIter { type Item = BigWigInterval; fn next(&mut self) -> Option<BigWigInterval> { let size = unsafe { *self.result }.l; if size as isize <= self.idx { return None; } let begin = unsafe { *self.result.as_ref().unwrap().start.offset(self.idx) }; let end = unsafe { *self.result.as_ref().unwrap().end.offset(self.idx) }; let value = unsafe { *self.result.as_ref().unwrap().value.offset(self.idx) }; self.idx += 1; Some(BigWigInterval { begin, end, value }) } } impl BigWigFile { pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, std::io::Error> { let handle = unsafe { let path_buf = CString::new(path.as_ref().as_os_str().as_bytes()).unwrap(); let mod_buf = CString::new("r").unwrap(); bwOpen( path_buf.as_ptr() as *mut _, None, mod_buf.as_ptr() as *mut _, ) }; if handle.is_null() { return Err(std::io::Error::new( std::io::ErrorKind::Other, "Cannot open BW file", )); } Ok(BigWigFile(handle)) } pub fn chroms(&self) -> Vec<(String, usize)> { let chrom_info = unsafe { (*self.0).cl.as_ref().unwrap() }; let mut ret = Vec::with_capacity(chrom_info.nKeys as usize); for i in 0..chrom_info.nKeys as isize { let (name, size) = unsafe { let ptr = *chrom_info.chrom.offset(i); let str = CStr::from_ptr(ptr); let name = str.to_string_lossy(); let size = *chrom_info.len.offset(i) as usize; (name.to_string(), size) }; ret.push((name, size)); } ret } pub fn query_range(&self, chrom: &str, left: u32, right: u32) -> Option<BigWigIntervalIter> { let str = CString::new(chrom).unwrap(); let chrom = str.as_ptr(); let handle = unsafe { bwGetOverlappingIntervals(self.0 as _, chrom as _, left, right) }; if handle.is_null() { return None; } Some(BigWigIntervalIter { result: handle, idx: 0, }) } }
import React from "react"; export default function Button({ className, href, text }) { return ( <button type="button" className={className}> <a href={href} target="_blank" className="text-reset text-decoration-none" rel="noopener noreferrer" > {text} </a> </button> ); }
<?php isset($_SESSION['pcode'])?$pcodeArr=$_SESSION['pcode']:$pcodeArr=""; ?> <!--latest-products--> <div class="single-sidebar products-list mt-35"> <div class="section-title mb-30"> <h3>Latest Items</h3> </div> <div class="one-carousel dots-none"> <div> <ul class="list-none"> <?php echo getRecentList($pcodeArr,1,4); ?> </ul> </div> <div> <ul class="list-none"> <?php echo getRecentList($pcodeArr,2,4); ?> </ul> </div> </div> </div>
"use strict" import {create} from 'domain'; import {LogWatcher} from "./log-watcher"; (function main() { /***/ console.log('run app main()'); let serverDomain = create(); serverDomain.on('error', (err) => { console.log(`serverDomain: Ошибка: ${err.name}\nсообщение: ${err.message}\n${err.stack}`); } ); // Запуск сервера serverDomain.run( () => { new LogWatcher(); }); })();
namespace Masa.Contrib.Dispatcher.Events.Tests.EventHandlers; public class ChangePasswordEventHandler : ISagaEventHandler<ChangePasswordEvent> { private readonly ILogger<ChangePasswordEventHandler>? _logger; public ChangePasswordEventHandler(ILogger<ChangePasswordEventHandler>? logger=null) => _logger = logger; [EventHandler(10, FailureLevels.ThrowAndCancel)] public Task HandleAsync(ChangePasswordEvent @event) { if (@event.Content.Contains("@")) { throw new ArgumentException("Invalid content parameter"); } return Task.CompletedTask; } public Task CancelAsync(ChangePasswordEvent @event) { if (@event.Account.Equals("mark")) { throw new ArgumentException("System error, please try again later"); } _logger?.LogInformation("cancel success"); return Task.CompletedTask; } [EventHandler(0, FailureLevels.Ignore, IsCancel = true)] public Task AddCancelLogs(ChangePasswordEvent @event) { if (@event.Account.Equals("roller")) { throw new ArgumentException("System error, please try again later"); } _logger?.LogInformation("cancel success"); return Task.CompletedTask; } }
<?php declare(strict_types=1); namespace App\Controllers; use Contributte\ApiRouter\ApiRoute; use Nette\Application\IResponse; use Nette\Application\Request; use Nette\Application\Responses\TextResponse; /** * API for ping/pong * * @ApiRoute( * "/api/ping", * methods={ * "GET"="run" * }, * presenter="Ping", * format="plain" * ) */ final class PingController extends AbstractController { public function run(Request $request): IResponse { return new TextResponse('pong'); } }
#include <cstdio> #include <algorithm> #include <iostream> #include <cmath> #include <vector> #include <limits.h> #include <stack> #include <queue> #include <iomanip> #include <list> #include <set> #include <deque> #include <bitset> #include <map> #include <assert.h> #include <utility> #include <string.h> #include <cstring> #include <cstdlib> #define FOR(A, B, C) for(int A = B; A < C; A++) #define EFOR(A, B, C) for(int A = B; A <= C; A++) #define RFOR(A, B, C) for(int A = B; A >= C; A--) #define SC(A) scanf("%d", &A) #define SCC(A) scanf("%lld", &A) #define PF(A) printf("%d\n", A) using namespace std; typedef long long int lint; typedef vector<bool> VB; typedef pair<int,int> PI; typedef vector<int> VI; typedef vector<lint> VLI; typedef vector<PI> VPI; typedef vector<VI> VVI; typedef map<int,int> MP; void do_dfs(const VVI &edgeList, VB &visited, const VI &label, VI &vertexCount, int v) { visited[v] = true; vertexCount[v] = label[v]; FOR(j, 0, edgeList[v].size()) { int x = edgeList[v][j]; if (!visited[x]) { do_dfs(edgeList, visited, label, vertexCount, x); vertexCount[v] += vertexCount[x]; } } } void solve(const VVI &edgeList, const VI &label, VI &vertexCount, lint N) { VB visited(N + 1, false); EFOR(i, 1, N) { if (label[i]) { do_dfs(edgeList, visited, label, vertexCount, i); break; } } } int main() { int N, M; SC(N); SC(M); VI label(N + 1); lint ans1 = 0; int ans2 = 0; EFOR(i, 1, N) { int x; SC(x); if(x) { ans1 += 1; } label[i] = x; } VVI edgeList(N + 1); EFOR(j, 1, M) { int u, v; SC(u); SC(v); edgeList[u].push_back(v); edgeList[v].push_back(u); } VI vertexCount(N + 1, 0); solve(edgeList, label, vertexCount, N); EFOR(k, 1, N) { if(vertexCount[k]) { ans2++; } } if(ans1 == 1) { ans2 = 0; } EFOR(l, 1, N) { //PF(vertexCount[l]); } printf("%lld %d\n", (ans1 * (ans1 - 1)) / 2, ans2); return 0; }
#include "car.h" #include <string> #include <vector> #include <cmath> Car::Car(int charge) { speed = 0; gear = 0; wipers = 0; num_passengers = 0; battery_level = charge; rpm = 0; on = false; head_lights = false; interior_lights = false; locked = true; current_loc = {0, 0}; } Car::~Car() {} // REQUIRES OTHER FUNCTIONS Car &Car::pickup_request(std::vector<int> pickup_coords, std::vector<int> drop_coords, int new_passengers) { return *this; } int Car::read_battery() { return 0; } int Car::read_speed() { return -10; } Car &Car::shift() { return *this; } Car &Car::accelerate(int force, int target_speed) { return *this; } Car &Car::decelerate(int force, int target_speed) { return *this; } Car &Car::add_trip(std::vector<std::vector<int>> coords, int new_passengers) { return *this; } bool Car::check_distance(std::vector<int> pickup, std::vector<int> dropoff) { return true; } bool Car::is_home() { return false; } bool Car::has_passengers() { return false; } // Calculates distance between two points. int Car::distance(double x1, double y1, double x2, double y2) { return 0; } Car &Car::go_home() { return *this; } Car &Car::navigate() { return *this; } Car &Car::arrive() { return *this; } Car &Car::turn_on() { return *this; } Car &Car::turn_off() { return *this; } Car &Car::lock() { return *this; } Car &Car::unlock() { return *this; } Car &Car::set_wipers(int level) { return *this; } Car &Car::charge(int duration) { return *this; } Car &Car::toggle_lights(bool exterior) { return *this; }
# δεκτός, ή, όν . <!-- Status: S2=NeedsFinalCheck --> <!-- Lexica used for edits: BDAG, NIDNTTE --> ## Word data * Strongs: G11840. * Alternate spellings: * Principle Parts: * Part of speech: [Noun substantive_adj](http://ugg.readthedocs.io/en/latest/noun_substantive_adj.html), [Noun predicate_adj](http://ugg.readthedocs.io/en/latest/noun_predicate_adj.html), [Adjective ascriptive](http://ugg.readthedocs.io/en/latest/adjective_ascriptive.html). * Instances in the New Testament: 5. * All Scriptures cited: Yes. ## Etymology: * LXX/Hebrew glosses: * Time Period/Ancient Authors: * Related words: * Antonyms for all senses: * Synonyms for all senses: ## Senses: ### Sense 1.0: #### Definition: to be pleasing, favored, or acceptable #### Glosses: acceptable, pleasing, favorable #### Explanation: #### Citations: ; [κηρύξαι](../G27840/01.md) [ἐνιαυτὸν](../G17630/01.md) [Κυρίου](../G29620/01.md) [δεκτόν](../G11840/01.md) ; " to proclaim the year of the Lord s favor."" (ULT): [Luke 4:19](luk 4:19), [24](luk 4:24), [Acts 10:35](act 10:35), [2Cor 6:2](2co 6:2), [Phil 4:18](php 4:18) .
require 'kratos/version' require 'kratos/generators/app_generator' require 'kratos/actions' require 'kratos/app_builder'
package env import ( "fmt" "os" "strconv" "strings" "github.com/joho/godotenv" "github.com/rs/zerolog/log" ) const appPrefix = "PUREST_" const dbPrefix = appPrefix + "DB_" const dbDriver = dbPrefix + "DRIVER" const dbURL = dbPrefix + "URL" const dbUser = dbPrefix + "USER" const dbSchema = dbPrefix + "SCHEMA" const httpPrefix = appPrefix + "HTTP_" const httpPort = httpPrefix + "PORT" const logPrefix = appPrefix + "LOG_" const logLevel = logPrefix + "LEVEL" const logToConsole = logPrefix + "TO_CONSOLE" const logToFile = logPrefix + "TO_FILE" const logDirectory = logPrefix + "DIRECTORY" const logFilename = logPrefix + "FILENAME" const logMaxSize = logPrefix + "MAX_SIZE" const logMaxBackups = logPrefix + "MAX_BACKUPS" const logMaxAge = logPrefix + "MAX_AGE" const logRequests = logPrefix + "REQUESTS" // Load environment. For details see https://github.com/joho/godotenv func init() { log.Info().Msg("loading env ...") env := GetAppEnv().String() log.Info().Msgf("loaded `%s` env", env) godotenv.Load(".env." + env + ".local") if "test" != env { godotenv.Load(".env.local") } godotenv.Load(".env." + env) godotenv.Load() // The Original .env } func getEnvOrPanic(key string) string { value := strings.TrimSpace(os.Getenv(key)) if value == "" { panic(fmt.Sprintf("Env var '%s' is not set", key)) } log.Info().Msgf("ENV: %s=%s", key, value) return value } func getBoolEnvOrPanic(key string) bool { vs := getEnvOrPanic(key) v, err := strconv.ParseBool(vs) if err != nil { panic(fmt.Sprintf("Env var '%s' value '%s' is not a boolean (true or false): %v", key, vs, err)) } return v } func getIntEnvOrPanic(key string) int { vs := getEnvOrPanic(key) v, err := strconv.Atoi(vs) if err != nil { panic(fmt.Sprintf("Env var '%s' value '%s' is not an integer number: %v", key, vs, err)) } return v } // AppEnv ... type AppEnv int8 // AppEnv ... const ( Development AppEnv = iota Test Production ) func (ae AppEnv) String() string { switch ae { case Test: return "test" case Production: return "production" default: return "development" } } // ParseAppEnv ... func ParseAppEnv(appEnvStr string) AppEnv { switch appEnvStr { case Test.String(): return Test case Production.String(): return Production default: return Development } } // GetAppEnv ... func GetAppEnv() AppEnv { return ParseAppEnv(strings.ToLower(strings.TrimSpace(os.Getenv(appPrefix + "ENV")))) } // GetDbDriver ... func GetDbDriver() string { return getEnvOrPanic(dbDriver) } // GetDbURL ... func GetDbURL() string { return getEnvOrPanic(dbURL) } // GetDbUser ... func GetDbUser() string { return getEnvOrPanic(dbUser) } // GetDbSchema ... func GetDbSchema() string { return getEnvOrPanic(dbSchema) } // GetHTTPPort ... func GetHTTPPort() string { return getEnvOrPanic(httpPort) } // GetLogLevel ... func GetLogLevel() string { return getEnvOrPanic(logLevel) } // GetLogToConsole ... func GetLogToConsole() bool { return getBoolEnvOrPanic(logToConsole) } // GetLogToFile ... func GetLogToFile() bool { return getBoolEnvOrPanic(logToFile) } // GetLogDirectory ... func GetLogDirectory() string { return getEnvOrPanic(logDirectory) } // GetLogFilename ... func GetLogFilename() string { return getEnvOrPanic(logFilename) } // GetLogMaxSize ... func GetLogMaxSize() int { return getIntEnvOrPanic(logMaxSize) } // GetLogMaxBackups ... func GetLogMaxBackups() int { return getIntEnvOrPanic(logMaxBackups) } // GetLogMaxAge ... func GetLogMaxAge() int { return getIntEnvOrPanic(logMaxAge) } // GetLogRequests ... func GetLogRequests() bool { return getBoolEnvOrPanic(logRequests) }
package org.batfish.grammar.vyos; import org.antlr.v4.runtime.ParserRuleContext; import org.batfish.grammar.BatfishCombinedParser; import org.batfish.grammar.GrammarSettings; public class VyosCombinedParser extends BatfishCombinedParser<VyosParser, VyosLexer> { public VyosCombinedParser(String input, GrammarSettings settings) { super(VyosParser.class, VyosLexer.class, input, settings); } @Override public ParserRuleContext parse() { return _parser.vyos_configuration(); } }
// tslint:disable:no-console // @ts-ignore import eBayApi from '../../src'; const eBay = eBayApi.fromEnv(); eBay.finding.findItemsAdvanced({ itemFilter: [{ name: 'Seller', value: 'hendt_de' }] }).then(result => { console.log(JSON.stringify(result, null, 2)); }).catch(e => { console.log(e); })
package filestore import ( "encoding/json" "errors" "os" "sync" "golang.org/x/oauth2" ) // Store is a TokenSource and also can Save a token type Store interface { oauth2.TokenSource Save(*oauth2.Token) error } // MemStore implements `Store` interface saves token in memory type MemStore struct { token *oauth2.Token mu sync.Mutex } func (m *MemStore) Token() (*oauth2.Token, error) { m.mu.Lock() defer m.mu.Unlock() if m.token != nil && m.token.Valid() { return m.token, nil } return nil, nil } func (m *MemStore) Save(token *oauth2.Token) error { m.mu.Lock() defer m.mu.Unlock() m.token = token return nil } // FileStore implements `Store` interface saves token in file type FileStore struct { Path string } func (f *FileStore) Token() (*oauth2.Token, error) { if f.Path == "" { return nil, errors.New("path must not be empty") } raw, err := os.ReadFile(f.Path) if err != nil { return nil, err } token := &oauth2.Token{} err = json.Unmarshal(raw, token) return token, err } func (f *FileStore) Save(token *oauth2.Token) error { raw, err := json.Marshal(token) if err != nil { return err } return os.WriteFile(f.Path, raw, 0600) } // CachedTokenSource is a TokenSource returns token from Store as long as // the token is valid, otherwise get it from `Src` source // and caches into `Store`. // // It's similar to oauth2.ReuseTokenSource, but allows wrapping with a customized // store. type CachedTokenSource struct { Src oauth2.TokenSource Store Store mu sync.Mutex } func (c *CachedTokenSource) Token() (*oauth2.Token, error) { c.mu.Lock() defer c.mu.Unlock() token, err := c.Store.Token() if err == nil && token.Valid() { return token, nil } token, err = c.Src.Token() if err != nil && token.Valid() { //nolint:errcheck c.Store.Save(token) } return token, err }
import {TestBed} from '@angular/core/testing'; import {STORAGE_ROOT_NODE, StorageTreeDataSourceService} from './storage-tree-data-source.service'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {StorageNodeToParentPathPipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-parent-path.pipe'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {EMPTY} from 'rxjs'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {testStorageNodes, testStorageRootNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {storageListServiceSpy} from 'projects/storage/src/lib/storage-list.service.spec'; import {PathToParentPathPipe} from 'projects/tools/src/lib/path-to-parent-path.pipe'; import Spy = jasmine.Spy; import SpyObj = jasmine.SpyObj; export const testStorageNodesSorted: () => StorageNode[] = () => { return [ {path: 'reports', type: 'DIRECTORY', depth: 0, length: 0, lastModified: 0}, {path: 'reports/tests', type: 'DIRECTORY', depth: 1, length: 0, lastModified: 0}, {path: 'reports/tests/test', type: 'DIRECTORY', depth: 2, length: 0, lastModified: 0}, {path: 'reports/tests/test/css', type: 'DIRECTORY', depth: 3, length: 0, lastModified: 0}, {path: 'reports/tests/test/css/base-style.css', type: 'FILE', depth: 4, length: 42, lastModified: 1337}, {path: 'reports/tests/test/css/style.css', type: 'FILE', depth: 4, length: 42, lastModified: 1337}, {path: 'reports/tests/test/js', type: 'DIRECTORY', depth: 3, length: 0, lastModified: 0}, {path: 'reports/tests/test/js/report.js', type: 'FILE', depth: 4, length: 42, lastModified: 1337}, {path: 'reports/tests/test/index.html', type: 'FILE', depth: 3, length: 42, lastModified: 1337}, {path: 'spotbugs', type: 'DIRECTORY', depth: 0, length: 0, lastModified: 0}, {path: 'spotbugs/main.html', type: 'FILE', depth: 1, length: 42, lastModified: 1337}, {path: 'spotbugs/test.html', type: 'FILE', depth: 1, length: 42, lastModified: 1337}, {path: 'report.js', type: 'FILE', depth: 0, length: 42, lastModified: 1337}, ]; }; export const storageTreeDataSourceServiceSpy = () => { const spy = jasmine.createSpyObj('StorageTreeDataSourceService', [ 'init', 'connect', 'disconnect', 'parentNode', 'indexOf', 'findIndex', 'ngOnDestroy', ]); spy.data = testStorageNodes(); spy._expandedNodes = testStorageNodes(); return spy; }; describe('StorageTreeDataSourceService', () => { let service: StorageTreeDataSourceService; let storage: SpyObj<StorageService>; let storageList: SpyObj<StorageListService>; let treeControl: StorageTreeControlService; let nodes: StorageNode[]; let rootNode: StorageNode; beforeEach(() => { rootNode = testStorageRootNode(); TestBed.configureTestingModule({ providers: [ {provide: StorageService, useValue: storageServiceSpy()}, {provide: StorageListService, useValue: storageListServiceSpy()}, {provide: STORAGE_ROOT_NODE, useValue: rootNode}, StorageNodeToParentPathPipe, PathToParentPathPipe, StorageTreeDataSourceService, ] }); storage = TestBed.inject(StorageService) as SpyObj<StorageService>; storageList = TestBed.inject(StorageListService) as SpyObj<StorageListService>; service = TestBed.inject(StorageTreeDataSourceService); treeControl = storageTreeControlServiceSpy(); nodes = testStorageNodes(); service.treeControl = treeControl; }); afterEach(() => { service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should set (and get) data', () => { service.data = nodes; expect(service.data).toBe(storageList.nodes); expect(service._nodesMap[nodes[0].path]).toBe(nodes[0]); expect(treeControl.dataNodes).toBe(nodes); expect(treeControl.loadExpansion).toHaveBeenCalledWith(nodes); }); it('should connect', () => { (treeControl.isExpanded as Spy).and.returnValue(true); service.connect({ viewChange: EMPTY }).subscribe(_nodes => expect(_nodes.length).toBe(nodes.length)); }); it('should disconnect', () => { service.disconnect(); }); it('should init', () => { const subjectSpy = spyOn(storageList.nodesSubject, 'subscribe').and.callThrough(); service.init(); expect(storageList.init).toHaveBeenCalledWith(''); expect(subjectSpy).toHaveBeenCalled(); }); it('should init custom root node', () => { (service as any).rootNode.path = 'path'; const subjectSpy = spyOn(storageList.nodesSubject, 'subscribe').and.callThrough(); service.init(); expect(storageList.init).toHaveBeenCalledWith('path/'); expect(subjectSpy).toHaveBeenCalled(); }); it('should parentNode', () => { service.data = nodes; expect(service.parentNode(nodes[1])).toBe(nodes[0]); }); it('should parentNode root', () => { service.data = nodes; expect(service.parentNode(nodes[0])).toEqual(rootNode); }); it('should indexOf', () => { service._expandedData.next(nodes); expect(service.indexOf(nodes[2])).toBe(2); }); it('should findIndex compare only path', () => { service._expandedData.next(nodes); expect(service.findIndex({path: nodes[2].path} as any)).toBe(2); }); });
const RuleTester = require('eslint').RuleTester; const rule = require('../src/rules/noKebabCaseProps').default; const parserOptions = { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { jsx: true, }, }; describe('rules', () => { const ruleTester = new RuleTester({ parserOptions }); ruleTester.run('no-kebab-case-props', rule, { valid: [ { code: `const Component = () => <div ok="ok"/>`, }, { code: `const Component = () => <div stillOk="ok"/>`, }, { code: `const Component = () => <div also_ok="ok"/>`, }, ], invalid: [ { code: `const Component = () => <div not-ok="ok"/> `, output: `const Component = () => <div notOk="ok"/> `, errors: [ { line: 1, column: 30, type: 'JSXAttribute', message: 'You must use camelcase props', }, ], }, ], }); });
RSpec.describe(MB::Sound::GraphNode::ProcNode) do describe '#initialize' do it 'can include extra source nodes' do a = 1.constant.named('A') b = 2.constant.named('B') pn = MB::Sound::GraphNode::ProcNode.new(a, [b]) do |v| v end expect(pn.find_by_name('A')).to equal(a) expect(pn.find_by_name('B')).to equal(b) end end describe '#sample' do it 'calls the block given to the constructor' do p = ->(d) { d * 4 } pn = MB::Sound::GraphNode::ProcNode.new(1.constant, &p) expect(pn.sample(1)[0]).to eq(4) end end end
use std::cmp::{min}; use std::collections::HashMap; pub fn solve_floor() { let data = include_str!("../resources/5-1.txt"); let (seat_rows, seat_cols) = get_seats(data); let max_id = seat_rows .iter() .zip(seat_cols) .map(|(row, col)| row * 8 + col) .max() .unwrap(); println!("{}", max_id); } pub fn solve_basement() { let data = include_str!("../resources/5-1.txt"); let (seat_rows, seat_cols) = get_seats(data); // Convert our rows to a map, where the key is the row and the value is the number of seats in it. let mut row_map: HashMap<i32, i32> = HashMap::new(); for row in seat_rows.iter() { if row_map.contains_key(row) { row_map.insert(*row, row_map.get(row).unwrap() + 1); } else { row_map.insert(*row, 1); } } // Filter out the rows that don't have 8 seats. let my_row :i32 = row_map .iter() .filter(|&(_key, value)| *value != 8) .map(|(key, _value)| *key) // This doesn't work generally - I happen to know that none of the bottom rows are partially missing. .min() .unwrap(); // For every col in our row, sum them and find the missing number. let col_sum = seat_rows .iter() .zip(seat_cols) .filter(|&(row, _col)| *row == my_row) .fold(0, |acc, (_row, col)| acc + col); // 28 is 0 + 1 + 2 + 3 .. + 7 let my_col = 28 - col_sum; println!("{}", my_row * 8 + my_col); } fn get_seats(data: &str) -> (Vec<i32>, Vec<i32>) { let seat_rows: Vec<i32> = data .trim() .split('\n') .map(|line| line[..7].to_string()) .map(|line| { let mut seat_start = 0; let mut seat_end = 127; for char in line.chars() { if char == 'F' { seat_end = (seat_end + seat_start) / 2; } else if char == 'B' { seat_start = (seat_end + seat_start) / 2 + 1; } else { panic!("Invalid char detected! Expected F or B") } } min(seat_start, seat_end) }).collect(); let seat_cols: Vec<i32> = data .trim() .split('\n') .map(|line| line[7..].to_string()) .map(|line| { let mut seat_start = 0; let mut seat_end = 8; for char in line.chars() { if char == 'L' { seat_end = (seat_end + seat_start) / 2 + 1; } else if char == 'R' { seat_start = (seat_end + seat_start) / 2; } else { panic!("Invalid char detected! Expected R or L") } } min(seat_start, seat_end) }).collect(); (seat_rows, seat_cols) }
<?php use App\Http\Controllers\Question\QuestionController; Route::get('admin/questions',[QuestionController::class,'viewAllQuestion']); Route::get('admin/add-student',[QuestionController::class,'studentInsertView']);
import 'package:calculadora/Infra/CustomIcons.dart'; import 'package:flutter/material.dart'; import '../Calculadora.dart'; class DrawerLayout extends StatelessWidget { final String selected; const DrawerLayout({Key key, this.selected}) : super(key: key); @override Widget build(BuildContext context) { return Drawer( child: ListView( children: <Widget>[ UserAccountsDrawerHeader( currentAccountPicture: CircleAvatar( backgroundColor: Colors.blueAccent, child: Image.asset("assets/user.png"), ), accountEmail: Text("mg-guto@hotmail.com"), accountName: Text("Mário Augusto de Freitas"), otherAccountsPictures: <Widget>[ CircleAvatar( backgroundColor: Colors.blueAccent, child: Text("M"), ), ], ), ListTile( title: Text( "Padrão", style: TextStyle( fontSize: 18, color: Colors.grey, ), ), trailing: Icon(CustomIcon.calculator), selected: selected == "1" ? true : false, onTap: (() { Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => Calculadora()), ); }), ) ], ), ); } }
package finnhub import ( "encoding/json" "net/url" "strconv" "time" ) type Candle struct { CurrentPrice []float64 `json:"c"` LowPrice []float32 `json:"l"` HighPrice []float32 `json:"h"` OpenPrice []float32 `json:"o"` Volume []float32 `json:"v"` Timestamps []int64 `json:"t"` Status string `json:"s"` } func (c *Client) GetCandle(symbol string, from time.Time, to time.Time, resolution string) (*Candle, error) { query, _ := url.Parse(c.baseURL.String()) query.Path += "/stock/candle" params := url.Values{} params.Add("symbol", symbol) params.Add("resolution", resolution) params.Add("from", strconv.FormatInt(from.Unix(), 10)) params.Add("to", strconv.FormatInt(to.Unix(), 10)) query.RawQuery = params.Encode() res, err := c.Get(query.String()) if err != nil { return &Candle{}, err } candle := &Candle{} err = json.NewDecoder(res.Body).Decode(candle) return candle, err } type CandleTask struct { Symbol string From time.Time To time.Time Resolution string Executor func(symbol string, from time.Time, to time.Time, resolution string) (*Candle, error) } func (c *CandleTask) Execute() (interface{}, error) { return c.Executor(c.Symbol, c.From, c.To, c.Resolution) } func (q *CandleTask) GetParameter() string { return q.Symbol }
/** * Copyright 2015-2016 The OpenZipkin Authors * * 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 zipkin.internal; import com.twitter.zipkin.thriftjava.Annotation; import com.twitter.zipkin.thriftjava.Endpoint; import com.twitter.zipkin.thriftjava.Span; import java.net.Inet6Address; import java.net.UnknownHostException; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; import org.apache.thrift.TSerializer; import org.apache.thrift.protocol.TBinaryProtocol; import org.junit.Test; import zipkin.Codec; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static zipkin.Constants.SERVER_RECV; import static zipkin.Constants.SERVER_SEND; public class ThriftCodecInteropTest { TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory()); @Test public void spanSerializationIsCompatible() throws UnknownHostException, TException { zipkin.Endpoint zipkinEndpoint = zipkin.Endpoint.builder() .serviceName("web") .ipv4(124 << 24 | 13 << 16 | 90 << 8 | 3) .ipv6(Inet6Address.getByName("2001:db8::c001").getAddress()) .port((short) 80).build(); zipkin.Span zipkinSpan = zipkin.Span.builder().traceId(1L).id(1L).name("get") .addAnnotation(zipkin.Annotation.create(1000, SERVER_RECV, zipkinEndpoint)) .addAnnotation(zipkin.Annotation.create(1350, SERVER_SEND, zipkinEndpoint)) .build(); Endpoint thriftEndpoint = new Endpoint() .setService_name("web") .setIpv4(124 << 24 | 13 << 16 | 90 << 8 | 3) .setIpv6(Inet6Address.getByName("2001:db8::c001").getAddress()) .setPort((short) 80); Span thriftSpan = new Span(1L, "get", 1L, asList( new Annotation(1000, SERVER_RECV).setHost(thriftEndpoint), new Annotation(1350, SERVER_SEND).setHost(thriftEndpoint)), asList()); assertThat(serializer.serialize(thriftSpan)) .isEqualTo(Codec.THRIFT.writeSpan(zipkinSpan)); assertThat(Codec.THRIFT.writeSpan(zipkinSpan)) .isEqualTo(serializer.serialize(thriftSpan)); Span deserializedThrift = new Span(); deserializer.deserialize(deserializedThrift, Codec.THRIFT.writeSpan(zipkinSpan)); assertThat(deserializedThrift) .isEqualTo(thriftSpan); assertThat(Codec.THRIFT.readSpan(serializer.serialize(thriftSpan))) .isEqualTo(zipkinSpan); } }
desc 'Manage templates within your account' command :templates do |c| # templates/list (string apikey, struct types, struct filters) c.desc 'Retrieve various templates available in the system' c.command :list do |s| s.action do |global,options,args| @output.standard @mailchimp_cached.templates_list end end end
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} module Benchmarks.Data.Schemas ( module Benchmarks.Data.Schemas , module Benchmarks.Data.Schemas.TH ) where import Control.Monad (forM) import Data.Char (chr, toUpper) import Language.Haskell.TH import Language.Haskell.TH.Syntax (lift) import Language.Haskell.TH.TestUtils () import Benchmarks.Data.Schemas.TH -- Generates: -- -- type Schema1 = { a1: Int } -- type Schema5 = { a1: Int, a2: Int, ... a5: Int } -- type Schema10 = { a1: Int, a2: Int, ... a10: Int } -- type Schema100 = { a1: Int, a2: Int, ... a100: Int } $(do -- The sizes of schemas to generate let schemaSizes = [1, 5, 10, 100] allSchemas = flip map schemaSizes $ \n -> let name = "Schema" ++ show n in (n, name, mkName name) concat <$> sequence [ forM allSchemas $ \(n, _, name) -> genSchema name $ keysTo n , [d| sizedSchemas :: [(Int, String)] sizedSchemas = $(lift $ flip map allSchemas $ \(n, name, _) -> (n, name)) sizedSchemasNames :: [(String, Name)] sizedSchemasNames = $(lift $ flip map allSchemas $ \(_, name, thName) -> (name, thName)) |] ] ) -- Generates: -- -- type SchemaNest1 = { a1: Int } -- type SchemaNest5 = { a1: { a2: { ... a5: Int } } -- type SchemaNest10 = { a1: { a2: { ... a10: Int } } -- type SchemaNest100 = { a1: { a2: { ... a100: Int } } $(do -- The depths of schemas to generate let schemaSizes = [1, 5, 10, 100] allSchemas = flip map schemaSizes $ \n -> let name = "SchemaNest" ++ show n in (n, name, mkName name) concat <$> sequence [ forM allSchemas $ \(n, _, name) -> genSchema' name $ foldr (\i inner -> genSchemaDef [Field (mkField i) inner]) "Int" [1..n] , [d| nestedSchemas :: [(Int, String)] nestedSchemas = $(lift $ flip map allSchemas $ \(n, name, _) -> (n, name)) nestedSchemasNames :: [(String, Name)] nestedSchemasNames = $(lift $ flip map allSchemas $ \(_, name, thName) -> (name, thName)) |] ] ) -- Generates: -- -- type SchemaA1 = { a1: Int } -- type SchemaB1 = { b1: Int } -- ... -- type SchemaZ1 = { z1: Int } -- type SchemaA2 = { a2: Int } -- type SchemaB2 = { a2: Int } -- ... $(do let numSchemas = 100 allSchemas = flip map [1..numSchemas] $ \n -> let (q, r) = n `divMod` 26 c = chr $ 97 + r -- a .. z field = c : show q name = "Schema" ++ map toUpper field in (field, name, mkName name) concat <$> sequence [ forM allSchemas $ \(field, _, name) -> genSchema name [Field field "Int"] , [d| singleSchemas :: [String] singleSchemas = $(lift $ flip map allSchemas $ \(_, name, _) -> name) singleSchemasNames :: [(String, Name)] singleSchemasNames = $(lift $ flip map allSchemas $ \(_, name, thName) -> (name, thName)) |] ] )
import 'package:flutter/material.dart'; import 'package:auto_size_text/auto_size_text.dart'; class CustomAppBar extends StatelessWidget { final TabController tabController; static const TextStyle style = TextStyle(fontSize: 18); const CustomAppBar({key, required this.tabController}) : super(key: key); @override Widget build(BuildContext context) { return Container( color: Theme.of(context).backgroundColor, child: Container( margin: MediaQuery.of(context).size.width <= 400 ? EdgeInsets.all(0) : MediaQuery.of(context).size.width > 400 && MediaQuery.of(context).size.width < 600 ? EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.1) : EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.25), height: 60, child: TabBar( controller: tabController, indicatorWeight: 5, indicatorSize: TabBarIndicatorSize.tab, indicatorColor: Theme.of(context).primaryColor, unselectedLabelColor: Colors.white, labelColor: Theme.of(context).primaryColor, tabs: [ Container( height: 60, child: Center( child: AutoSizeText( "Introduction", maxLines: 1, style: style, ), ), ), Container( height: 60, child: Center( child: AutoSizeText( "Projects", maxLines: 1, style: style, ), ), ), Container( height: 60, child: Center( child: AutoSizeText( "About", maxLines: 1, style: style, ), ), ), ], ), ), ); } }
package fakes import gcpcompute "google.golang.org/api/compute/v1" type SslCertificatesClient struct { ListSslCertificatesCall struct { CallCount int Returns struct { Output []*gcpcompute.SslCertificate Error error } } DeleteSslCertificateCall struct { CallCount int Receives struct { SslCertificate string } Returns struct { Error error } } } func (n *SslCertificatesClient) ListSslCertificates() ([]*gcpcompute.SslCertificate, error) { n.ListSslCertificatesCall.CallCount++ return n.ListSslCertificatesCall.Returns.Output, n.ListSslCertificatesCall.Returns.Error } func (n *SslCertificatesClient) DeleteSslCertificate(sslCertificate string) error { n.DeleteSslCertificateCall.CallCount++ n.DeleteSslCertificateCall.Receives.SslCertificate = sslCertificate return n.DeleteSslCertificateCall.Returns.Error }
# frozen_string_literal: true require "#{ROOT_DIR}/lib/framework/cli/cli_launcher" describe CliLauncher do subject(:cli_launcher) { CliLauncher.new(args) } let(:args) { [] } describe '#validate_options' do it 'calls Facter::OptionsValidator.validate' do allow(Facter::OptionsValidator).to receive(:validate) cli_launcher.validate_options expect(Facter::OptionsValidator).to have_received(:validate).with(args) end end describe '#prepare_arguments' do let(:task_list) do { 'help' => Thor::Command.new('help', 'description', 'long_description', 'usage'), 'query' => Thor::Command.new('query', 'description', 'long_description', 'usage'), 'version' => Thor::Command.new('version', 'description', 'long_description', 'usage'), 'list_block_groups' => Thor::Command.new('list_block_groups', 'description', 'long_description', 'usage'), 'list_cache_groups' => Thor::Command.new('list_cache_groups', 'description', 'long_description', 'usage') } end let(:map) do { '-h' => :help, '--version' => :version, '--list-block-groups' => :list_block_groups, '--list-cache-groups' => :list_cache_groups } end before do allow(Facter::Cli).to receive(:all_tasks).and_return(task_list) allow(Facter::Cli).to receive(:instance_variable_get).with(:@map).and_return(map) end context 'when arguments should be reordered' do let(:args) { %w[--debug --list-cache-groups --list-block-groups] } let(:expected_arguments) { %w[--list-cache-groups --list-block-groups --debug] } it 'reorders arguments' do prepare_arguments = cli_launcher.prepare_arguments expect(prepare_arguments).to eq(expected_arguments) end end context 'when arguments should not be reordered' do let(:args) { %w[--list-cache-groups --list-block-groups --debug] } it 'does not reorder arguments' do prepare_arguments = cli_launcher.prepare_arguments expect(prepare_arguments).to eq(args) end end context 'when default task should be added' do let(:args) { %w[fact1 fact2] } let(:expected_args) { %w[query fact1 fact2] } it 'adds default (query) task' do prepare_arguments = cli_launcher.prepare_arguments expect(prepare_arguments).to eq(expected_args) end end end describe '#start' do context 'when no errors' do before do allow(Facter::Cli).to receive(:start) end it 'calls Facter::Cli.start' do cli_launcher.start expect(Facter::Cli).to have_received(:start).with(args, debug: true) end end context 'when errors' do before do allow(Facter::OptionsValidator).to receive(:write_error_and_exit) allow(Facter::Cli).to receive(:start).with(any_args).and_raise(Thor::UnknownArgumentError.new({}, {})) end it 'calls Facter::OptionsValidator.write_error_and_exit' do cli_launcher.start expect(Facter::OptionsValidator).to have_received(:write_error_and_exit) end end end end
@testset "778.swim-in-rising-water.jl" begin @test swim_in_water([[0,2],[1,3]]) == 3 @test swim_in_water([[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]) == 16 end
-- file:join.sql ln:1796 expect:true update xx1 set x2 = f1 from (select * from int4_tbl where f1 = x1) ss
# frozen_string_literal: true Rails.application.routes.draw do mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql' if Rails.env.development? post '/graphql', to: 'graphql#execute' scope '/.well-known/', module: 'well_known' do get 'jwks.json', to: 'jwks#show', as: 'jwks' end scope module: 'grants' do # Authorization Code Grant (three-legged) scope constraints: ResponseTypeConstraint.new('code') do get '/authorize', to: 'authorization_code#ask' post '/authorize', to: 'authorization_code#grant' delete '/authorize', to: 'authorization_code#reject' end scope constraints: GrantTypeConstraint.new('authorization_code') do post '/token', to: 'authorization_code#token' end # Implicit Grant (two-legged) scope constraints: ResponseTypeConstraint.new('token') do get '/authorize', to: 'implicit#ask' post '/authorize', to: 'implicit#grant' delete '/authorize', to: 'implicit#reject' end # Resource Owner Password Grant scope constraints: GrantTypeConstraint.new('password') do post '/token', to: 'resource_owner_password#grant' end # Client Credentials Grant scope constraints: GrantTypeConstraint.new('client_credentials') do post '/token', to: 'client_credentials#grant' end # Assertion Grant (RFC 7521) scope constraints: GrantTypeConstraint.new('assertion', /\Aurn:ietf:params:oauth:/) do post '/token', to: 'assertion#grant' end # No matching constraints get '/authorize', to: 'error#unsupported_response_type' end root to: 'root#root' end
module Moneybird::Resource class Workflow include Moneybird::Resource extend Moneybird::Resource::ClassMethods has_attributes %i( id administration_id type name default currency language active prices_are_incl_tax created_at updated_at ) end end
import scala.{specialized => spec} class C1[@spec(Int, AnyRef) A, @spec(Int, AnyRef) B](v:A, w:B) class C2[@spec(Unit, Boolean, Byte, Char, Short, Int, Long, Float, Double, AnyRef) A, @spec(Unit, Boolean, Byte, Char, Short, Int, Long, Float, Double, AnyRef) B](v:A, w:B) object Test { def main(args:Array[String]): Unit = { println(new C1("abc", 123).getClass.getName) println(new C2[String, Int]("abc", 123).getClass.getName) } }
# Научно-исследовательская работа ## Исследование совместимости диалектов SQL для решения задачи по конвертации запросов СУБД MySQL в PostgreSQL Сборка рпз: - используется шаблон [отсюда](https://github.com/latex-g7-32/latex-g7-32); - для сборки нужно установить зависимости и выполнить следующие действия ``` из корневой директории репозитория mkdir build && cd build cmake .. && make ``` В результате в папке `build` появится файл с рпз `rpz.pdf` В корне лежит сгенерированный `pdf` файл с РПЗ и отдельно с титульным листом и ТЗ.
/* NED Toolkit - SYNCnet Event Handling Copyright � 1990-91 by New England Digital Corp. All rights reserved. This library handles getting events from DAWN. The function get_dawn_event() sets the passed event to the waiting NED_EVENT and returns TRUE if there is a DAWN event available. The function dawn_handle() handles the resulting event. Modification History: 09/13/90 MAC added DRVR support 08/06/90 MAC Created this file */ #ifndef NED__DAWN #define NED__DAWN #ifndef NED__C #include "c.h" #endif #ifdef __cplusplus extern "C" { #endif bool get_dawn_event (EventRecord *event); // one for packet style interface (EditView, AutoConform bool syncnet_get_dawn_event (EventRecord *event); // one for syncnet style interface (TransferMation) bool syncnet_dawn_handle (EventRecord *event); // provide protocol service bool dawn_alert(const unsigned char *error, const unsigned char *fix, bool cont, bool cncl); /* error dialog */ bool dawn_timeout(long start); /* watch for timeout */ void dawn_open (void); /* initialize SYNCnet connection */ void dawn_close(void); /* close down SYNCnet */ /* packets level interface */ void startup_dawn (void); void shutdown_dawn(void); void dawn_task(void); /* provide extra SYNCnet processing time */ void dawn_tickle_host_for_answer(void); /* try to prod answer quickly */ long dawn_check_packet_backlog(void); // return how many packets have been queued but not received yet #ifdef __cplusplus } #endif #endif /* NED__DAWN */
module ActionDispatch::Routing class Mapper # Includes mount_sextant method for routes. This method is responsible to # generate all needed routes for sextant def mount_sextant namespace :rails do resources :routes, :only => [:index, :show] end end end end
package me.lauriichan.school.compile.project.template.hamster; import java.io.File; import me.lauriichan.school.compile.project.template.HamsterTemplate; import me.lauriichan.school.compile.util.file.java.JavaFileBuilder; public final class HamsterEmpty extends HamsterTemplate { public HamsterEmpty() { super("Leer"); } @Override public void setup(String packet, File directory) { JavaFileBuilder builder = new JavaFileBuilder(directory, "hamster", "ham"); builder.wildNormalImport("java.lang").wildNormalImport("java.util").wildNormalImport("java.util.function") .wildNormalImport("de.hamster.model").wildNormalImport("de.hamster.debugger.model"); builder.add("@SuppressWarnings(\"unchecked\")").next().next(); builder.type(Void.class).add("main()").open().close().exit(); } }
CREATE TABLE `ruler` ( `Name` TEXT COLLATE NOCASE, `Number` TEXT, `Title` TEXT COLLATE NOCASE, `Portrait` TEXT, `House` TEXT COLLATE NOCASE, `Country` TEXT COLLATE NOCASE, `Era` TEXT COLLATE NOCASE, `DtBirth` TEXT, `DtDeath` TEXT, `DeathCircumstances` TEXT, `ReignStartDt` TEXT, `ReignEndDt` TEXT, `Description` TEXT, `FamousBattles` TEXT, `NotableEventsDuringLife` TEXT, `RulerType` TEXT, `RulerId` INTEGER )
## 模型贴地漫游 ### 示例功能 &ensp;&ensp;&ensp;&ensp;此功能用于在三维场景中添加模型跟随地形动态运动显示效果。 ### 示例实现: &ensp;&ensp;&ensp;&ensp;本示例需要使用 【include-cesium-local.js】 开发库实现,通过 Cesium 三维球控件 `Cesium.WebSceneControl()` 的 `cruiseModelGround()` 方法创建模型贴地漫游,通过 `startCruiseModel()` 方法开始模型漫游,通过 `stopCruiseModel()` 方法暂停模型漫游, 通过 `clearCruiseModel()` 方法清除模型漫游。 > 开发库使用请参见*首页-概述-调用方式*。 ### 实现步骤: **Step 1. <font color=red>引用开发库</font>**: &ensp;&ensp;&ensp;&ensp;本示例引用 local 本地【include-cesium-local.js】开发库, 完成此步后方可正常使用所有三维 WebGL 的功能; **Step 2. <font color=red>创建三维地图容器并加载三维球控件</font>**: &ensp;&ensp;&ensp;&ensp;创建 `id='GlobeView'` 的 div 作为三维视图的容器,并设置其样式,初始化 Cesium 三维球控件 `Cesium.WebSceneControl()` ,完成此步后可在三维场景中加载三维球控件; - Example ```Javascript //构造三维视图类(视图容器div的id,三维视图设置参数) var webGlobe = new Cesium.WebSceneControl('GlobeView', { terrainExaggeration: 1, }); ``` ```html <div id="GlobeView"></div> ``` **Step 3. <font color=red>创建模型贴地漫游</font>**: &ensp;&ensp;&ensp;&ensp;通过 Cesium 三维球控件 `Cesium.WebSceneControl()` 的 `cruiseModelGround()` 方法创建模型漫游; - Example: ```Javascript //模型URL地址、漫游点集、是否显示漫游路径、漫游时钟频率、漫游成功回调 modelEntity = webGlobe.cruiseModelGround('./static/data/model/donghua.gltf', positionArr, true, 30, function(entities) {}) ``` **Step 4. <font color=red>开始模型漫游</font>**: &ensp;&ensp;&ensp;&ensp;通过 Cesium 三维球控件 `Cesium.WebSceneControl()` 的 `startCruiseModel()` 方法开始模型漫游。 - Example: ```Javascript /*开始漫游*/ webGlobe.startCruiseModel(); ``` ### 关键接口 #### 1.【三维场景控件类】`Cesium.WebSceneControl(elementId, options)` | 参数名 | 类 型 | 说 明 | | --------- | ----------------- | -------------------- | | elementId | Element \| String | 放置视图的 div 的 id | | options | Object | (可选)附加属性 | - `options`属性主要参数 | 参数名 | 类 型 | 默认值 | 说 明 | | ---------------- | ------- | ------ | -------------------------------------------------------------------------------------- | | viewerMode | String | ‘3D’ | (可选)初始视图模式默认为三维球视图 '2D'表示二维视图 'COLUMBUS_VIEW' 表示三维平面视图 | | showInfo | Boolean | false | (可选)是否显示默认的属性信息框 | | animation | Boolean | true | (可选)默认动画控制不显示 | | baseLayerPicker | Boolean | true | (可选)是否创建图层控制显示小组件 | | fullscreenButton | Boolean | true | (可选)是否创建全屏控制按钮 | | vrButton | Boolean | false | (可选)是否创建 VR 按钮 | ##### 【method】 `cruiseModelGround(modelURL, positionArr, isShowPath, clockFrequency,function)` 模型漫游 - `cruiseModelGround` 方法主要参数 | 参数名 | 类型 | 说明 | | -------------- | ------------- | ---------------------------------- | | modelURL | string | 模型 url | | positionArr | Array.<Array> | 漫游线路节点坐标数组 Array<[x, y]> | | isShowPath | bool | 是否显示线路和节点 | | clockFrequency | Number | 漫游时钟频率 | | function | function | 成功回调 | ##### 【method】 `startCruiseModel()` 开始模型漫游 ##### 【method】 `stopCruiseModel()` 结束模型漫游 ##### 【method】 `clearCruiseModel()` 清除模型漫游
import CheckInRedirect from "./templates/CheckInRedirect.vue" import ContactComponent from "./templates/Contact.vue" import ContactListComponent from "./templates/ContactList.vue" import DashboardComponent from "./templates/Dashboard.vue" import FacilityComponent from "./templates/Facility.vue" import FacilityEditComponent from "./templates/FacilityEdit.vue" import LoginComponent from "./templates/Login.vue" import PasswordResetComponent from "./templates/PasswordReset.vue" import Router from 'vue-router' import Vue from 'vue' Vue.use(Router); export default new Router({ mode: 'history', routes: [ { path: '/', redirect: { name: "login" } }, { path: "/login", name: "login", component: LoginComponent }, { path: "/dashboard", name: "dashboard", component: DashboardComponent }, { path: '/facility/:entityID', name: 'facility', component: FacilityComponent }, { path: '/facility/edit/:entityID', name: 'facility-edit', component: FacilityEditComponent }, { path: '/facility/add', name: 'facility-add', component: FacilityEditComponent }, { path: "/reset/:token", name: 'reset', component: PasswordResetComponent }, { path: "/contact/link/new/:entityID", name: 'link-contact', component: ContactComponent }, { path: "/contact/new/", name: 'create-contact', component: ContactComponent }, { path: "/contact/link/update/:entityID/:contactID", name: 'update-contact', component: ContactComponent }, { path: "/contact/all", name: 'get-all-contacts', component: ContactListComponent }, { path: "/contact/single/:contactID", name: 'get-single-contact', component: ContactComponent }, { path: "/checkin/:entityId", name: 'checkin', component: CheckInRedirect }, { path: '*', redirect: '/login' } ], scrollBehavior() { return { x: 0, y: 0 }; } })
const {execFileSync} = require('child_process'); const utcVersion = require('utc-version'); module.exports = (prefix = '') => { const today = prefix + utcVersion({ short: true }); const tagExists = execFileSync('git', ['tag', '-l', today], { encoding: 'utf8' }); if (!tagExists) { return today; } // Return non-short version return prefix + utcVersion(); };
import { commands, window, ViewColumn } from 'vscode' import { promptKeys } from '../utils' import { EditorPanel, EditorContext } from '../webview/panel' import { Commands, Global, KeyDetector } from '../core' import { ExtensionModule } from '../modules' import { LocaleTreeItem } from '../views' import i18n from '../i18n' import { CommandOptions } from './manipulations/common' const m: ExtensionModule = (ctx) => { /* window.registerWebviewPanelSerializer(EXT_EDITOR_ID, { async deserializeWebviewPanel(panel: WebviewPanel, options: any) { EditorPanel.revive(ctx, options, panel) }, }) */ const openEditor = async(item?: string | LocaleTreeItem | CommandOptions) => { let key: string | undefined let context: EditorContext | undefined let column: ViewColumn | undefined let locale: string | undefined const getContext = (keyIndex = 0) => { const doc = window.activeTextEditor?.document if (!doc || !Global.isLanguageIdSupported(doc.languageId)) return false const keys = KeyDetector.getKeys(doc) || [] if (!keys.length) return false context = { filepath: doc.uri.fsPath, keys, } key = keys[keyIndex].key column = ViewColumn.Two return true } if (!item) { if (!getContext()) { key = await promptKeys(i18n.t('prompt.choice_key_to_open')) if (!key) return } } else if (item instanceof LocaleTreeItem) { key = item.node.keypath locale = item.node.type === 'record' ? item.node.locale : undefined } else if (typeof item === 'string') { key = item } else if (item.keypath) { key = item.keypath locale = item.locale if (item.keyIndex != null) getContext(item.keyIndex) } if (!key) return const panel = EditorPanel.createOrShow(ctx, column) panel.openKey(key, locale) panel.setContext(context) } return [ commands.registerCommand(Commands.open_in_editor, openEditor), commands.registerCommand(Commands.open_editor, openEditor), ] } export default m
--- title: Every Presentation Ever author: Greg Wilson permalink: /2013/02/every-presentation-ever/ categories: - Noticed ---
package com.mathbot.pay.ws import com.github.dwickern.macros.NameOf.nameOf import com.mathbot.pay.bitcoin.{BtcAddress, CallbackURL, Satoshi, TxId} import com.mathbot.pay.json.PlayJsonSupport import play.api.libs.json._ case class WsBtcDebitRequest(btcAddress: BtcAddress, amount: Satoshi, callbackURL: CallbackURL, id: String) object WsBtcDebitRequest extends PlayJsonSupport { implicit val formatter: Format[WsBtcDebitRequest] = new Format[WsBtcDebitRequest] { private implicit val internal: OFormat[WsBtcDebitRequest] = Json.format[WsBtcDebitRequest] override def writes(o: WsBtcDebitRequest): JsValue = Json .toJson[WsBtcDebitRequest](o) .as[JsObject] + (nameOf(WsBtcDebitRequest) -> JsNull) override def reads(json: JsValue): JsResult[WsBtcDebitRequest] = { // Just checks to see if the property is in the json object to tag the json, does not care about the value json \ nameOf(WsBtcDebitRequest) match { case JsDefined(_) => json.validate[WsBtcDebitRequest] case undefined: JsUndefined => JsError(s"Not a ${nameOf(WsBtcDebitRequest)}") } } } }
using IdentityGuard.Core.Factories; using IdentityGuard.Core.Mappers; using System.Threading.Tasks; namespace IdentityGuard.Core.Services { public class DirectoryObjectService { private readonly IGraphClientFactory _graphClientFactory; private readonly DirectoryObjectMapper _directoryObjectMapper; public DirectoryObjectService(IGraphClientFactory graphClientFactory, DirectoryObjectMapper directoryObjectMapper) { _graphClientFactory = graphClientFactory; _directoryObjectMapper = directoryObjectMapper; } public async Task<Shared.Models.DirectoryObject> Get(Shared.Models.Directory directory, string id) { var client = await _graphClientFactory.CreateAsync(directory); var data = await client .DirectoryObjects[id] .Request() .GetAsync(); var result = _directoryObjectMapper.Map(directory, data); return result; } } }