text
stringlengths
27
775k
package WebService::Toggl; use Module::Runtime qw(use_package_optimistically); use Moo; with 'WebService::Toggl::Role::Base'; use namespace::clean; our $VERSION = "0.11"; has 'me' => (is =>'ro', lazy => 1, builder => 1); sub _build_me { shift->_new_thing('::API::Me') } sub workspace { shift->_new_thing_by_id('::API::Workspace', @_) } sub client { shift->_new_thing_by_id('::API::Client', @_) } sub project { shift->_new_thing_by_id('::API::Project', @_) } sub project_user { shift->_new_thing_by_id('::API::ProjectUser', @_) } sub tag { shift->_new_thing_by_id('::API::Tag', @_) } sub task { shift->_new_thing_by_id('::API::Task', @_) } sub time_entry { shift->_new_thing_by_id('::API::TimeEntry', @_) } sub user { shift->_new_thing_by_id('::API::User', @_) } sub workspace_user { shift->_new_thing_by_id('::API::WorkspaceUser', @_) } sub details { shift->_new_thing('::Report::Details', @_) } sub summary { shift->_new_thing('::Report::Summary', @_) } sub weekly { shift->_new_thing('::Report::Weekly', @_) } sub _new_thing { my ($self, $class, $args) = @_; return use_package_optimistically('WebService::Toggl' . $class) ->new({_request => $self->_request, %{$args || {}}}); } sub _new_thing_by_id { shift->_new_thing(shift, {id => shift}) } 1; __END__ =encoding utf-8 =head1 NAME WebService::Toggl - Wrapper for the toggl.com task logging API =head1 SYNOPSIS use WebService::Toggl; my $toggl = WebService::Toggl->new({api_key => $ENV{API_KEY}}); my $me = $toggl->me(); say "Me: " . $me->fullname . " <" . $me->email . ">:"; say "My Workspaces:"; for my $ws ($me->workspaces->all) { say " " . $ws->name . " (" . $ws->id . ")"; say " Projects:"; say " " . $_->name . " (" . $_->id . ") " for ($ws->projects->all); } =head1 DESCRIPTION B<< NB: This is a new module, and the API is still under development. While I'm pretty happy with the current interface, expect the internals to be heavily refactored before v1.0. This version currently only supports read access to the API, but I plan to add write access in the near future. >> L<WebService::Toggl> is a perl interface to the L<Toggl|http://www.toggl.com> API, as described at L<https://github.com/toggl/toggl_api_docs>. When a new C<WebService::Toggl> object is created, it is associated with a particulars user's credentials via their API token. The API token can be found at the bottom of your 'My Profile' on Toggl. Any new objects created by the C<WebService::Toggl> object will inherit its credentials. =head2 Laziness All C<Webservice::Toggl::API::> and C<WebService::Toggl::Report::> objects are created lazily. If you ask for a particular C<::API::Workspace> object by id, no GET request against the Toggl API will be issued until you request an attribute that has not yet been set. E.g. my $workspace = $toggl->workspace(1234); say $workspace->id; # prints 1234, no GET yet issued say $workspace->name; # name is not yet set, will issue GET request =head2 Raw data Each C<API::> and C<Report::> object stores the raw response received from Toggl in an attribute called C<raw>. If you want to force the object to fill itself in with data from the API, calling C<< $object->raw() >> will do so. =head2 Set objects Each C<API::> class has a corresponding class that represents a set of the objects. These set objects store the raw response query and will return a list of the objects it comprises via the C<< ->all() >> method. =head2 Additional queries You can make other requests against the Toggle API via the C<api_{get,post,put,delete}()> methods provided by L<WebService::Toggl::Role::Base>. For instance, if you had a L<WebService::Toggl::API::Tag> object that you wanted to delete, you could write: $tag->api_delete( $tag->my_url ); =head1 METHODS =head2 API objects =head3 me() Returns the L<WebService::Toggl::API::Me> object representing the authorized user. =head3 workspace($id) Returns the L<WebService::Toggl::API::Workspace> object with the given id. =head3 workspace_user( $id ) Returns the L<WebService::Toggl::API::WorkspaceUser> object with the given id. =head3 client( $id ) Returns the L<WebService::Toggl::API::Client> object with the given id. =head3 project( $id ) Returns the L<WebService::Toggl::API::Project> object with the given id. =head3 project_user( $id ) Returns the L<WebService::Toggl::API::ProjectUser> object with the given id. =head3 tag( $id ) Returns the L<WebService::Toggl::API::Tag> object with the given id. =head3 task( $id ) Returns the L<WebService::Toggl::API::Task> object with the given id. =head3 time_entry( $id ) Returns the L<WebService::Toggl::API::TimeEntry> object with the given id. =head3 user( $id ) Returns the L<WebService::Toggl::API::User> object with the given id. =head2 Reports =head3 details( $args ) Returns the L<WebService::Toggl::Report::Details> object with the given arguments. =head3 summary( $args ) Returns the L<WebService::Toggl::Report::Summary> object with the given arguments. =head3 weekly( $args ) Returns the L<WebService::Toggl::Report::Weekly> object with the given arguments. =head1 LICENSE Copyright (C) Fitz Elliott. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 AUTHOR Fitz Elliott E<lt>felliott@fiskur.orgE<gt> =cut
using System.Net.Http; namespace TfsDeploymentChecker.BusinessLogic.Abstractions { public interface ITfsClient { HttpClient GetClient(); } }
package testutils // TestLogger a logger that logs to a generic format function, used with testing.T.Logf type TestLogger struct { F func(format string, args ...interface{}) } // Debugf debug format func (l *TestLogger) Debugf(format string, args ...interface{}) { l.F("DEBUG: "+format, args...) } // Infof info format func (l *TestLogger) Infof(format string, args ...interface{}) { l.F("INFO : "+format, args...) } // Errorf error format func (l *TestLogger) Errorf(format string, args ...interface{}) { l.F("ERROR: "+format, args...) } // Warnf warning format func (l *TestLogger) Warnf(format string, args ...interface{}) { l.F("WARN: "+format, args...) }
#!/bin/bash SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" cd "$SCRIPT_DIR/.." # TODO: This should be rewritten in rust, a Makefile, or some platform-independent language fuzzers=$(find ./fuzzers -maxdepth 1 -type d) backtrace_fuzzers=$(find ./fuzzers/backtrace_baby_fuzzers -maxdepth 1 -type d) libafl=$(pwd) for fuzzer in $(echo $fuzzers $backtrace_fuzzers); do cd $fuzzer # Clippy checks if [ "$1" != "--no-fmt" ]; then echo "[*] Checking fmt for $fuzzer" cargo fmt --all -- --check || exit 1 echo "[*] Running clippy for $fuzzer" cargo clippy || exit 1 else echo "[+] Skipping fmt and clippy for $fuzzer (--no-fmt specified)" fi if [ -e ./Makefile.toml ]; then echo "[*] Testing $fuzzer" cargo make test || exit 1 echo "[+] Done testing $fuzzer" else echo "[*] Building $fuzzer" cargo build || exit 1 echo "[+] Done building $fuzzer" fi # Save disk space cargo clean cd $libafl echo "" done
#include <stdio.h> int main() { float i = 1; float n; printf("Watch out! Here come a bunch of fractions! \n"); while (i<30) { i = i+1; n = 1/i; printf("%f", n);} printf(" That's all, folks!\n"); return 0; }
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'AuthController@ReadLoginPage')->name('login.read'); Route::get('/home', 'HomeController@ReadDashboard')->name('home'); Route::get('/datatable', 'DataController@ReadDataTable')->name('datatable.read'); Route::get('/datatable/{id}', 'DataController@DetailDataTable')->name('datatable.detail'); Route::get('/editdatatable/{id}', 'DataController@EditDataTable')->name('datatable.edit'); Route::post('/datatable/edit/post', 'DataController@PostEditDataTable')->name('datatable.edit.post'); Route::post('/datatable/delete', 'DataController@DeleteDataTable')->name('datatable.delete'); Route::post('/datatable/post', 'DataController@PostDataTable')->name('datatable.post'); Route::get('/datagrafik', 'DataController@ReadDataGrafik')->name('datagrafik.read'); Route::get('/datamaps', 'DataController@ReadDataMaps')->name('datamaps.read'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home');
import { Document } from 'mongoose'; export interface Test extends Document { id: string; title: string; date: number; coefficient: number; shown: boolean; lessonId: string; gradesId: string[]; }
<?php namespace Oro\Bundle\MarketingListBundle\Tests\Unit\Datagrid; use Oro\Bundle\MarketingListBundle\Datagrid\ConfigurationProvider; use Oro\Bundle\SegmentBundle\Entity\Segment; class ConfigurationProviderTest extends \PHPUnit\Framework\TestCase { /** * @var \PHPUnit\Framework\MockObject\MockObject */ protected $chainConfigurationProvider; /** * @var \PHPUnit\Framework\MockObject\MockObject */ protected $configProvider; /** * @var \PHPUnit\Framework\MockObject\MockObject */ protected $helper; /** * @var ConfigurationProvider */ protected $provider; protected function setUp(): void { $this->chainConfigurationProvider = $this ->getMockBuilder('Oro\Bundle\DataGridBundle\Provider\ConfigurationProviderInterface') ->getMock(); $this->configProvider = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider') ->disableOriginalConstructor() ->getMock(); $this->helper = $this->getMockBuilder('Oro\Bundle\MarketingListBundle\Model\MarketingListHelper') ->disableOriginalConstructor() ->getMock(); $this->provider = new ConfigurationProvider( $this->chainConfigurationProvider, $this->configProvider, $this->helper ); } public function testIsApplicable() { $gridName = ConfigurationProvider::GRID_PREFIX . '1_postfix'; $this->helper->expects($this->once()) ->method('getMarketingListIdByGridName') ->with($gridName) ->will($this->returnValue(1)); $this->assertTrue($this->provider->isApplicable($gridName)); } public function testGetConfigurationException() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Marketing List with id "1" not found.'); $gridName = ConfigurationProvider::GRID_PREFIX . '1_postfix'; $this->helper->expects($this->once()) ->method('getMarketingListIdByGridName') ->with($gridName) ->will($this->returnValue(1)); $this->helper->expects($this->once()) ->method('getMarketingList') ->with(1) ->will($this->returnValue(null)); $this->provider->getConfiguration($gridName); } public function testGetConfigurationManualExceptionNoConfiguration() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Grid not found for entity "\stdClass"'); $gridName = ConfigurationProvider::GRID_PREFIX . '1_postfix'; $entityName = '\stdClass'; $marketingList = $this->getMockBuilder('Oro\Bundle\MarketingListBundle\Entity\MarketingList') ->disableOriginalConstructor() ->getMock(); $marketingList->expects($this->once()) ->method('isManual') ->will($this->returnValue(true)); $marketingList->expects($this->once()) ->method('getEntity') ->will($this->returnValue($entityName)); $this->helper->expects($this->once()) ->method('getMarketingListIdByGridName') ->with($gridName) ->will($this->returnValue(1)); $this->helper->expects($this->once()) ->method('getMarketingList') ->with(1) ->will($this->returnValue($marketingList)); $this->configProvider->expects($this->once()) ->method('hasConfig') ->will($this->returnValue(false)); $this->configProvider->expects($this->never()) ->method('getConfig'); $this->provider->getConfiguration($gridName); } public function testGetConfigurationManualExceptionNoConfiguredGrid() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Grid not found for entity "\stdClass"'); $gridName = ConfigurationProvider::GRID_PREFIX . '1_postfix'; $entityName = '\stdClass'; $marketingList = $this->getMockBuilder('Oro\Bundle\MarketingListBundle\Entity\MarketingList') ->disableOriginalConstructor() ->getMock(); $marketingList->expects($this->once()) ->method('isManual') ->will($this->returnValue(true)); $marketingList->expects($this->once()) ->method('getEntity') ->will($this->returnValue($entityName)); $this->helper->expects($this->once()) ->method('getMarketingListIdByGridName') ->with($gridName) ->will($this->returnValue(1)); $this->helper->expects($this->once()) ->method('getMarketingList') ->with(1) ->will($this->returnValue($marketingList)); $config = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Config\ConfigInterface') ->getMock(); $config->expects($this->once()) ->method('get') ->with('grid_name') ->will($this->returnValue(null)); $this->configProvider->expects($this->once()) ->method('hasConfig') ->will($this->returnValue(true)); $this->configProvider->expects($this->once()) ->method('getConfig') ->with($entityName) ->will($this->returnValue($config)); $this->provider->getConfiguration($gridName); } public function testGetConfigurationManual() { $gridName = ConfigurationProvider::GRID_PREFIX . '1_postfix'; $actualGridName = 'test_grid'; $entityName = '\stdClass'; $marketingList = $this->getMockBuilder('Oro\Bundle\MarketingListBundle\Entity\MarketingList') ->disableOriginalConstructor() ->getMock(); $marketingList->expects($this->once()) ->method('isManual') ->will($this->returnValue(true)); $marketingList->expects($this->once()) ->method('getEntity') ->will($this->returnValue($entityName)); $this->helper->expects($this->once()) ->method('getMarketingListIdByGridName') ->with($gridName) ->will($this->returnValue(1)); $this->helper->expects($this->once()) ->method('getMarketingList') ->with(1) ->will($this->returnValue($marketingList)); $config = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Config\ConfigInterface') ->getMock(); $config->expects($this->once()) ->method('get') ->with('grid_name') ->will($this->returnValue($actualGridName)); $this->configProvider->expects($this->once()) ->method('hasConfig') ->will($this->returnValue(true)); $this->configProvider->expects($this->once()) ->method('getConfig') ->with($entityName) ->will($this->returnValue($config)); $configuration = $this->assertConfigurationGet($gridName, $actualGridName); $this->assertEquals($configuration, $this->provider->getConfiguration($gridName)); } public function testGetConfigurationSegment() { $gridName = ConfigurationProvider::GRID_PREFIX . '1_postfix'; $actualGridName = Segment::GRID_PREFIX . '2_postfix'; $segment = $this->getMockBuilder('Oro\Bundle\SegmentBundle\Entity\Segment') ->disableOriginalConstructor() ->getMock(); $segment->expects($this->once()) ->method('getId') ->will($this->returnValue(2)); $marketingList = $this->getMockBuilder('Oro\Bundle\MarketingListBundle\Entity\MarketingList') ->disableOriginalConstructor() ->getMock(); $marketingList->expects($this->once()) ->method('isManual') ->will($this->returnValue(false)); $marketingList->expects($this->once()) ->method('getId') ->will($this->returnValue(1)); $marketingList->expects($this->once()) ->method('getSegment') ->will($this->returnValue($segment)); $this->helper->expects($this->once()) ->method('getMarketingListIdByGridName') ->with($gridName) ->will($this->returnValue(1)); $this->helper->expects($this->once()) ->method('getMarketingList') ->with(1) ->will($this->returnValue($marketingList)); $configuration = $this->assertConfigurationGet($gridName, $actualGridName); $this->assertEquals($configuration, $this->provider->getConfiguration($gridName)); } protected function assertConfigurationGet($gridName, $actualGridName) { $configuration = $this->getMockBuilder('Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration') ->disableOriginalConstructor() ->getMock(); $configuration->expects($this->once()) ->method('setName') ->with($gridName); $this->chainConfigurationProvider->expects($this->once()) ->method('getConfiguration') ->with($actualGridName) ->will($this->returnValue($configuration)); return $configuration; } public function testDoNotProcessInvalidSegmentGridName() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Marketing List id not found in "oro_segment_grid_" gridName.'); $this->provider->getConfiguration(Segment::GRID_PREFIX); } }
require 'monitor.rb' buf = [] buf.extend(MonitorMixin) empty_cond = buf.new_cond # consumer Thread.start do loop do buf.synchronize do empty_cond.wait_while { buf.empty? } print buf.shift end end end # producer while line = ARGF.gets buf.synchronize do buf.push(line) empty_cond.signal end end
// run-pass // ignore-pretty pretty-printing is unhygienic #![feature(decl_macro)] #![allow(unused)] mod foo { pub macro m($s:tt, $i:tt) { $s.$i } } mod bar { struct S(i32); fn f() { let s = S(0); ::foo::m!(s, 0); } } fn main() {}
const isProduction = require('./is-production') const sdk = require('stellar-sdk') let host = 'https://horizon-testnet.stellar.org' if(isProduction) { host = 'https://horizon.stellar.org' } const server = new sdk.Server(host) if(isProduction) { sdk.Network.usePublicNetwork() } else { sdk.Network.useTestNetwork() } module.exports = { host, sdk, server }
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ operational_tooling::launch_swarm_with_op_tool_and_backend, test_utils::libra_swarm_utils::load_node_config, }; use libra_config::config::SecureBackend; use libra_network_address::NetworkAddress; use libra_secure_json_rpc::VMStatusView; use libra_secure_storage::{KVStorage, Storage}; use std::{convert::TryInto, str::FromStr}; #[test] fn test_consensus_observer_mode_storage_error() { let num_nodes = 4; let (env, op_tool, backend, _) = launch_swarm_with_op_tool_and_backend(num_nodes, 0); // Kill safety rules storage for validator 1 to ensure it fails on the next epoch change let (node_config, _) = load_node_config(&env.validator_swarm, 1); let safety_rules_storage = match node_config.consensus.safety_rules.backend { SecureBackend::OnDiskStorage(config) => SecureBackend::OnDiskStorage(config), _ => panic!("On-disk storage is the only backend supported in smoke tests"), }; let mut safety_rules_storage: Storage = (&safety_rules_storage).try_into().unwrap(); safety_rules_storage.reset_and_clear().unwrap(); // Force a new epoch by updating validator 0's full node address in the validator config let txn_ctx = op_tool .set_validator_config( None, Some(NetworkAddress::from_str("/ip4/10.0.0.16/tcp/80").unwrap()), &backend, false, false, ) .unwrap(); assert_eq!(VMStatusView::Executed, txn_ctx.execution_result.unwrap()); // Rotate validator 0's operator key several different times, each requiring a new transaction for _ in 0..5 { let (txn_ctx, _) = op_tool.rotate_operator_key(&backend, false).unwrap(); assert_eq!(VMStatusView::Executed, txn_ctx.execution_result.unwrap()); } // Verify validator 1 is still able to stay up to date with validator 0 (despite safety rules failing) let mut client_0 = env.get_validator_client(0, None); let sequence_number_0 = client_0 .get_sequence_number(&["sequence", &txn_ctx.address.to_string()]) .unwrap(); let mut client_1 = env.get_validator_client(1, None); let sequence_number_1 = client_1 .get_sequence_number(&["sequence", &txn_ctx.address.to_string()]) .unwrap(); assert_eq!(sequence_number_0, sequence_number_1); }
<?php namespace Fast\Gallery\Listeners; use SiteMapManager; use Fast\Gallery\Repositories\Interfaces\GalleryInterface; class RenderingSiteMapListener { /** * @var GalleryInterface */ protected $galleryRepository; /** * RenderingSiteMapListener constructor. * @param GalleryInterface $galleryRepository */ public function __construct(GalleryInterface $galleryRepository) { $this->galleryRepository = $galleryRepository; } /** * Handle the event. * * @return void * @author Imran Ali */ public function handle() { SiteMapManager::add(route('public.galleries'), '2016-10-10 00:00', '0.8', 'weekly'); $galleries = $this->galleryRepository->getDataSiteMap(); foreach ($galleries as $gallery) { SiteMapManager::add(route('public.gallery', $gallery->slug), $gallery->updated_at, '0.8', 'daily'); } } }
package com.codekoan.shellcap class Ledger { var transactions = List[Transaction]() def add(transaction: Transaction): Ledger = { transactions = transaction :: transactions this } def totals: TraversableOnce[(Address, Long)] = { transactions.flatMap(x => List((x.source, -x.amount), (x.destination, x.amount))).groupBy(_._1) .mapValues(v => v.map(_._2).reduce(_ + _)).toTraversable } } object Ledger { def apply(transactions: List[Transaction]): Ledger = { val l = new Ledger() l.transactions = transactions l } }
ALTER TABLE `address` ADD COLUMN `postal_code` VARCHAR(45) NULL AFTER `flat`; ALTER TABLE `person` ADD COLUMN `alternative_phone` VARCHAR(255) NULL AFTER `phone`; ALTER TABLE `student` ADD COLUMN `photos_authorization` TINYINT(4) NULL DEFAULT NULL AFTER `judicial_restriction`, ADD COLUMN `withdrawal_authorization` TINYINT(4) NULL DEFAULT NULL AFTER `photos_authorization`; CREATE TABLE `family_relationship` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(100) NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC)); CREATE TABLE `authorized_person` ( `id` INT NOT NULL AUTO_INCREMENT, `person_id` INT NULL, `family_relationship_id` INT NULL, PRIMARY KEY (`id`)); ALTER TABLE `authorized_person` ADD INDEX `index2` (`person_id` ASC); ALTER TABLE `authorized_person` ADD INDEX `index3` (`family_relationship_id` ASC); ALTER TABLE `authorized_person` ADD CONSTRAINT `fk_authorized_person_1` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; ALTER TABLE `authorized_person` ADD CONSTRAINT `fk_authorized_person_2` FOREIGN KEY (`family_relationship_id`) REFERENCES `family_relationship` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; CREATE TABLE `student_authorized_person` ( `id` INT NOT NULL AUTO_INCREMENT, `authorized_person_id` INT NOT NULL, `student_id` INT NOT NULL, PRIMARY KEY (`id`)); ALTER TABLE `student_authorized_person` ADD INDEX `index2` (`authorized_person_id` ASC); ALTER TABLE `student_authorized_person` ADD INDEX `index3` (`student_id` ASC); ALTER TABLE `student_authorized_person` ADD CONSTRAINT `fk_student_authorized_person_1` FOREIGN KEY (`authorized_person_id`) REFERENCES `authorized_person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; ALTER TABLE `student_authorized_person` ADD CONSTRAINT `fk_student_authorized_person_2` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; insert into sf_guard_permission (name, description) values ('show_authorized_person' , 'Listar y ver detalle de personas autorizadas a retirar al alumno'); insert into sf_guard_permission (name, description) values ('edit_authorized_person' , 'Editar personas autorizadas a retirar al alumno'); insert into sf_guard_permission (name, description) values ('delete_authorized_person' , 'Eliminar personas autorizadas a retirar al alumno'); insert into sf_guard_permission (name, description) values ('print_student_card' , 'Imprimir planilla personal del alumno'); insert into sf_guard_permission (name, description) values ('edit_family_relationship' , 'Editar y dar de alta tipos de parentesco');
package utils import ( "context" "errors" bolt "github.com/coreos/bbolt" ) // CheckUserNameExists Checks if the given username exists in database. // The calling function is responsible to close the DB connection! func CheckUserNameExists(userName string, db *bolt.DB) bool { userNameFound := false db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("Users")) entry := b.Get([]byte(userName)) if entry != nil { // Whoops! Username is already taken. Set flag accordingly. userNameFound = true // Stop execution return nil } return nil }) return userNameFound } // https://medium.com/@matryer/context-keys-in-go-5312346a868d type contextKey string func (c contextKey) String() string { return "gamecharacters context key " + string(c) } var ( contextKeyAuthenticated = contextKey("authenticated") contextKeyAuthUserName = contextKey("username") ) // AuthData holds auth data from context type AuthData struct { UserName string Authenticated bool } // PutContextAuthData puts auth data into a context func PutContextAuthData(ctx context.Context, authenticated bool, userName string) context.Context { contextWithValues := context.WithValue(ctx, contextKeyAuthUserName, userName) contextWithValues = context.WithValue(contextWithValues, contextKeyAuthenticated, authenticated) return contextWithValues } // GetContextAuthData gets AuthData from a context object func GetContextAuthData(ctx context.Context) (AuthData, error) { authenticated, ok := ctx.Value(contextKeyAuthenticated).(bool) if !ok { return AuthData{}, errors.New("Error getting AuthData") } userName, ok := ctx.Value(contextKeyAuthUserName).(string) if !ok { return AuthData{}, errors.New("Error getting AuthData") } return AuthData{Authenticated: authenticated, UserName: userName}, nil }
$INCLUDE(port_cpu.inc) ;.NAME ?bsp_vect .EXTERN _int_dummy .EXTERN _krhino_tick_proc .PUBLIC _SOC_WDTI .PUBLIC _SOC_LVI .PUBLIC _SOC_P0 .PUBLIC _SOC_P1 .PUBLIC _SOC_P2 .PUBLIC _SOC_P3 .PUBLIC _SOC_P4 .PUBLIC _SOC_P5 .PUBLIC _SOC_ST2_CSI20_IIC20 .PUBLIC _SOC_SR2_CSI20_IIC21 .PUBLIC _SOC_SRE2_TM11H .PUBLIC _SOC_DMA0 .PUBLIC _SOC_DMA1 .PUBLIC _SOC_ST0_CSI00_IIC00 .PUBLIC _SOC_ST0_CSI00_IIC00 .PUBLIC _SOC_SR0_CSI01_IIC01 .PUBLIC _SOC_SRE0_TM01H .PUBLIC _SOC_ST1_CSI10_IIC10 .PUBLIC _SOC_SR1_CSI11_IIC11 .PUBLIC _SOC_IICA0 .PUBLIC _SOC_TM00 .PUBLIC _SOC_TM01 .PUBLIC _SOC_TM02 .PUBLIC _SOC_TM03 .PUBLIC _SOC_AD .PUBLIC _SOC_RTC .PUBLIC _SOC_IT .PUBLIC _SOC_KR .PUBLIC _SOC_ST3_CSI30_IIC30 .PUBLIC _SOC_SR3_CSI31_IIC31 .PUBLIC _SOC_TM13 .PUBLIC _SOC_TM04 .PUBLIC _SOC_TM05 .PUBLIC _SOC_TM06 .PUBLIC _SOC_TM07 .PUBLIC _SOC_P6 .PUBLIC _SOC_P7 .PUBLIC _SOC_P8 .PUBLIC _SOC_P9 .PUBLIC _SOC_P10 .PUBLIC _SOC_P11 .PUBLIC _SOC_TM10 .PUBLIC _SOC_TM11 .PUBLIC _SOC_TM12 .PUBLIC _SOC_SRE3_TM13H .PUBLIC _SOC_MD .PUBLIC _SOC_IICA1 .PUBLIC _SOC_FL .PUBLIC _SOC_DMA2 .PUBLIC _SOC_DMA3 .PUBLIC _SOC_TM14 .PUBLIC _SOC_TM15 .PUBLIC _SOC_TM16 .PUBLIC _SOC_TM17 _SOC_WDTI .VECTOR 0x0004 _SOC_LVI .VECTOR 0x0006 _SOC_P0 .VECTOR 0x0008 _SOC_P1 .VECTOR 0x000A _SOC_P2 .VECTOR 0x000C _SOC_P3 .VECTOR 0x000E _SOC_P4 .VECTOR 0x0010 _SOC_P5 .VECTOR 0x0012 _SOC_ST2_CSI20_IIC20 .VECTOR 0x0014 _SOC_SR2_CSI20_IIC21 .VECTOR 0x0016 _SOC_SRE2_TM11H .VECTOR 0x0018 _SOC_DMA0 .VECTOR 0x001A _SOC_DMA1 .VECTOR 0x001C _SOC_ST0_CSI00_IIC00 .VECTOR 0x001E _SOC_ST0_CSI00_IIC00 .VECTOR 0x0020 _SOC_SR0_CSI01_IIC01 .VECTOR 0x0022 _SOC_SRE0_TM01H .VECTOR 0x0024 _SOC_ST1_CSI10_IIC10 .VECTOR 0x0026 _SOC_SR1_CSI11_IIC11 .VECTOR 0x0028 _SOC_IICA0 .VECTOR 0x002A _SOC_TM00 .VECTOR 0x002C _SOC_TM01 .VECTOR 0x002E _SOC_TM02 .VECTOR 0x0030 _SOC_TM03 .VECTOR 0x0032 _SOC_AD .VECTOR 0x0034 _SOC_RTC .VECTOR 0x0036 _SOC_IT .VECTOR 0x0038 _SOC_KR .VECTOR 0x003A _SOC_ST3_CSI30_IIC30 .VECTOR 0x003C _SOC_SR3_CSI31_IIC31 .VECTOR 0x003E _SOC_TM13 .VECTOR 0x0040 _SOC_TM04 .VECTOR 0x0042 _SOC_TM05 .VECTOR 0x0044 _SOC_TM06 .VECTOR 0x0046 _SOC_TM07 .VECTOR 0x0048 _SOC_P6 .VECTOR 0x004A _SOC_P7 .VECTOR 0x004C _SOC_P8 .VECTOR 0x004E _SOC_P9 .VECTOR 0x0050 _SOC_P10 .VECTOR 0x0052 _SOC_P11 .VECTOR 0x0054 _SOC_TM10 .VECTOR 0x0056 _SOC_TM11 .VECTOR 0x0058 _SOC_TM12 .VECTOR 0x005A _SOC_SRE3_TM13H .VECTOR 0x005C _SOC_MD .VECTOR 0x005E _SOC_IICA1 .VECTOR 0x0060 _SOC_FL .VECTOR 0x0062 _SOC_DMA2 .VECTOR 0x0064 _SOC_DMA3 .VECTOR 0x0066 _SOC_TM14 .VECTOR 0x0068 _SOC_TM15 .VECTOR 0x006A _SOC_TM16 .VECTOR 0x006C _SOC_TM17 .VECTOR 0x006E .SECTION .text, TEXT _SOC_WDTI: sys_isr_enter MOVW AX, #0 CALL !!_int_dummy sys_isr_exit _SOC_LVI: sys_isr_enter MOVW AX, #1 CALL !!_int_dummy sys_isr_exit _SOC_P0: sys_isr_enter MOVW AX, #2 CALL !!_int_dummy sys_isr_exit _SOC_P1: sys_isr_enter MOVW AX, #3 CALL !!_int_dummy sys_isr_exit _SOC_P2: sys_isr_enter MOVW AX, #4 CALL !!_int_dummy sys_isr_exit _SOC_P3: sys_isr_enter MOVW AX, #5 CALL !!_int_dummy sys_isr_exit _SOC_P4: sys_isr_enter MOVW AX, #6 CALL !!_int_dummy sys_isr_exit _SOC_P5: sys_isr_enter MOVW AX, #7 CALL !!_int_dummy sys_isr_exit _SOC_ST2_CSI20_IIC20: sys_isr_enter MOVW AX, #8 CALL !!_int_dummy sys_isr_exit _SOC_SR2_CSI20_IIC21: sys_isr_enter MOVW AX, #9 CALL !!_int_dummy sys_isr_exit _SOC_SRE2_TM11H: sys_isr_enter MOVW AX, #10 CALL !!_int_dummy sys_isr_exit _SOC_DMA0: sys_isr_enter MOVW AX, #11 CALL !!_int_dummy sys_isr_exit _SOC_DMA1: sys_isr_enter MOVW AX, #12 CALL !!_int_dummy sys_isr_exit _SOC_ST0_CSI00_IIC00: sys_isr_enter MOVW AX, #13 CALL !!_int_dummy sys_isr_exit _SOC_SR0_CSI01_IIC01: sys_isr_enter MOVW AX, #14 CALL !!_int_dummy sys_isr_exit _SOC_SRE0_TM01H: sys_isr_enter MOVW AX, #15 CALL !!_int_dummy sys_isr_exit _SOC_ST1_CSI10_IIC10: sys_isr_enter MOVW AX, #16 CALL !!_int_dummy sys_isr_exit _SOC_SR1_CSI11_IIC11: sys_isr_enter MOVW AX, #17 CALL !!_int_dummy sys_isr_exit _SOC_SRE1_TM03H: sys_isr_enter MOVW AX, #18 CALL !!_int_dummy sys_isr_exit _SOC_IICA0: sys_isr_enter MOVW AX, #19 CALL !!_int_dummy sys_isr_exit _SOC_TM00: sys_isr_enter MOVW AX, #20 CALL !_krhino_tick_proc sys_isr_exit _SOC_TM01: sys_isr_enter MOVW AX, #21 CALL !!_int_dummy sys_isr_exit _SOC_TM02: sys_isr_enter MOVW AX, #22 CALL !!_int_dummy sys_isr_exit _SOC_TM03: sys_isr_enter MOVW AX, #23 CALL !!_int_dummy sys_isr_exit _SOC_AD: sys_isr_enter MOVW AX, #24 CALL !!_int_dummy sys_isr_exit _SOC_RTC: sys_isr_enter MOVW AX, #25 CALL !!_int_dummy sys_isr_exit _SOC_IT: sys_isr_enter MOVW AX, #26 CALL !!_int_dummy sys_isr_exit _SOC_KR: sys_isr_enter MOVW AX, #27 CALL !!_int_dummy sys_isr_exit _SOC_ST3_CSI30_IIC30: sys_isr_enter MOVW AX, #28 CALL !!_int_dummy sys_isr_exit _SOC_SR3_CSI31_IIC31: sys_isr_enter MOVW AX, #29 CALL !!_int_dummy sys_isr_exit _SOC_TM13: sys_isr_enter MOVW AX, #30 CALL !!_int_dummy sys_isr_exit _SOC_TM04: sys_isr_enter MOVW AX, #31 CALL !!_int_dummy sys_isr_exit _SOC_TM05: sys_isr_enter MOVW AX, #32 CALL !!_int_dummy sys_isr_exit _SOC_TM06: sys_isr_enter MOVW AX, #33 CALL !!_int_dummy sys_isr_exit _SOC_TM07: sys_isr_enter MOVW AX, #34 CALL !!_int_dummy sys_isr_exit _SOC_P6: sys_isr_enter MOVW AX, #35 CALL !!_int_dummy sys_isr_exit _SOC_P7: sys_isr_enter MOVW AX, #36 CALL !!_int_dummy sys_isr_exit _SOC_P8: sys_isr_enter MOVW AX, #37 CALL !!_int_dummy sys_isr_exit _SOC_P9: sys_isr_enter MOVW AX, #38 CALL !!_int_dummy sys_isr_exit _SOC_P10: sys_isr_enter MOVW AX, #39 CALL !!_int_dummy sys_isr_exit _SOC_P11: sys_isr_enter MOVW AX, #40 CALL !!_int_dummy sys_isr_exit _SOC_TM10: sys_isr_enter MOVW AX, #41 CALL !!_int_dummy sys_isr_exit _SOC_TM11: sys_isr_enter MOVW AX, #42 CALL !!_int_dummy sys_isr_exit _SOC_TM12: sys_isr_enter MOVW AX, #43 CALL !!_int_dummy sys_isr_exit _SOC_SRE3_TM13H: sys_isr_enter MOVW AX, #44 CALL !!_int_dummy sys_isr_exit _SOC_MD: sys_isr_enter MOVW AX, #45 CALL !!_int_dummy sys_isr_exit _SOC_IICA1: sys_isr_enter MOVW AX, #46 CALL !!_int_dummy sys_isr_exit _SOC_FL: sys_isr_enter MOVW AX, #47 CALL !!_int_dummy sys_isr_exit _SOC_DMA2: sys_isr_enter MOVW AX, #48 CALL !!_int_dummy sys_isr_exit _SOC_DMA3: sys_isr_enter MOVW AX, #49 CALL !!_int_dummy sys_isr_exit _SOC_TM14: sys_isr_enter MOVW AX, #50 CALL !!_int_dummy sys_isr_exit _SOC_TM15: sys_isr_enter MOVW AX, #51 CALL !!_int_dummy sys_isr_exit _SOC_TM16: sys_isr_enter MOVW AX, #52 CALL !!_int_dummy sys_isr_exit _SOC_TM17: sys_isr_enter MOVW AX, #53 CALL !!_int_dummy sys_isr_exit
import 'dart:convert'; import 'package:collection/collection.dart'; import 'package:http_parser/http_parser.dart'; import '../../extensions/helpers_extension.dart'; import 'stream_info_provider.dart'; /// class PlayerResponse { // Json parsed map Map<String, dynamic> root; /// late final String playabilityStatus = root.get('playabilityStatus')!.getT<String>('status')!; /// bool get isVideoAvailable => playabilityStatus.toLowerCase() != 'error'; /// bool get isVideoPlayable => playabilityStatus.toLowerCase() == 'ok'; /// String get videoTitle => root.get('videoDetails')!.getT<String>('title')!; /// String get videoAuthor => root.get('videoDetails')!.getT<String>('author')!; /// DateTime? get videoUploadDate => root .get('microformat') ?.get('playerMicroformatRenderer') ?.getT<String>('uploadDate') ?.parseDateTime(); /// DateTime? get videoPublishDate => root .get('microformat') ?.get('playerMicroformatRenderer') ?.getT<String>('publishedAt') ?.parseDateTime(); /// String get videoChannelId => root.get('videoDetails')!.getT<String>('channelId')!; /// Duration get videoDuration => Duration( seconds: int.parse(root.get('videoDetails')!.getT<String>('lengthSeconds')!)); /// List<String> get videoKeywords => root .get('videoDetails') ?.getT<List<dynamic>>('keywords') ?.cast<String>() ?? const []; /// String get videoDescription => root.get('videoDetails')!.getT<String>('shortDescription')!; /// int get videoViewCount => int.parse(root.get('videoDetails')!.getT<String>('viewCount')!); /// String? get previewVideoId => root .get('playabilityStatus') ?.get('errorScreen') ?.get('playerLegacyDesktopYpcTrailerRenderer') ?.getValue('trailerVideoId') ?? Uri.splitQueryString(root .get('playabilityStatus') ?.get('errorScreen') ?.get('') ?.get('ypcTrailerRenderer') ?.getValue('playerVars') ?? '')['video_id']; /// bool get isLive => root.get('videoDetails')?.getT<bool>('isLive') ?? false; /// String? get hlsManifestUrl => root.get('streamingData')?.getT<String>('hlsManifestUrl'); /// String? get dashManifestUrl => root.get('streamingData')?.getT<String>('dashManifestUrl'); /// late final List<StreamInfoProvider> muxedStreams = root .get('streamingData') ?.getList('formats') ?.map((e) => _StreamInfo(e)) .cast<StreamInfoProvider>() .toList() ?? const <StreamInfoProvider>[]; /// late final List<StreamInfoProvider> adaptiveStreams = root .get('streamingData') ?.getList('adaptiveFormats') ?.map((e) => _StreamInfo(e)) .cast<StreamInfoProvider>() .toList() ?? const []; /// late final List<StreamInfoProvider> streams = [ ...muxedStreams, ...adaptiveStreams ]; /// late final List<ClosedCaptionTrack> closedCaptionTrack = root .get('captions') ?.get('playerCaptionsTracklistRenderer') ?.getList('captionTracks') ?.map((e) => ClosedCaptionTrack(e)) .cast<ClosedCaptionTrack>() .toList() ?? const []; /// late final String? videoPlayabilityError = root.get('playabilityStatus')?.getT<String>('reason'); PlayerResponse(this.root); /// PlayerResponse.parse(String raw) : root = json.decode(raw); } /// class ClosedCaptionTrack { // Json parsed class final Map<String, dynamic> root; /// String get url => root.getT<String>('baseUrl')!; /// String get languageCode => root.getT<String>('languageCode')!; /// String get languageName => root.get('name')!.getT<String>('simpleText')!; /// bool get autoGenerated => root.getT<String>('vssId')!.toLowerCase().startsWith('a.'); /// ClosedCaptionTrack(this.root); } class _StreamInfo extends StreamInfoProvider { static final _contentLenExp = RegExp(r'[\?&]clen=(\d+)'); /// Json parsed map final Map<String, dynamic> root; @override late final int? bitrate = root.getT<int>('bitrate'); @override late final String? container = mimeType?.subtype; @override late final int? contentLength = int.tryParse( root.getT<String>('contentLength') ?? _contentLenExp.firstMatch(url)?.group(1) ?? ''); @override late final int? framerate = root.getT<int>('fps'); @override late final String? signature = Uri.splitQueryString(root.getT<String>('signatureCipher') ?? '')['s']; @override late final String? signatureParameter = Uri.splitQueryString( root.getT<String>('cipher') ?? '')['sp'] ?? Uri.splitQueryString(root.getT<String>('signatureCipher') ?? '')['sp']; @override late final int tag = root.getT<int>('itag')!; @override late final String url = root.getT<String>('url') ?? Uri.splitQueryString(root.getT<String>('cipher') ?? '')['url'] ?? Uri.splitQueryString(root.getT<String>('signatureCipher') ?? '')['url']!; @override late final String? videoCodec = isAudioOnly ? null : codecs?.split(',').firstOrNull?.trim().nullIfWhitespace; @override late final int? videoHeight = root.getT<int>('height'); @override late final String? videoQualityLabel = root.getT<String>('qualityLabel'); @override late final int? videoWidth = root.getT<int>('width'); late final bool isAudioOnly = mimeType?.type == 'audio'; late final MediaType? mimeType = _getMimeType(); MediaType? _getMimeType() { var mime = root.getT<String>('mimeType'); if (mime == null) { return null; } return MediaType.parse(mime); } late final String? codecs = mimeType?.parameters['codecs']?.toLowerCase(); @override late final String? audioCodec = isAudioOnly ? codecs : _getAudioCodec(codecs?.split(','))?.trim(); String? _getAudioCodec(List<String>? codecs) { if (codecs == null) { return null; } if (codecs.length == 1) { return null; } return codecs.last; } _StreamInfo(this.root); }
package org.covidwatch.android.ui.reporting import android.view.View import com.xwray.groupie.viewbinding.BindableItem import org.covidwatch.android.R import org.covidwatch.android.data.model.PositiveDiagnosisReport import org.covidwatch.android.databinding.ItemPositiveDiagnosisChildBinding import org.covidwatch.android.extension.fromHtml import org.covidwatch.android.ui.util.DateFormatter class DiagnosisDetailsItem( val viewModel: PositiveDiagnosesViewModel, val diagnosis: PositiveDiagnosisReport ) : BindableItem<ItemPositiveDiagnosisChildBinding>() { override fun getLayout(): Int = R.layout.item_positive_diagnosis_child override fun bind(viewBinding: ItemPositiveDiagnosisChildBinding, position: Int) { val symptomsStartDate = diagnosis.verificationData?.symptomsStartDate val context = viewBinding.root.context val symptomsDateText = symptomsStartDate?.let { DateFormatter.format(it) } ?: context.getString(R.string.no_symptoms_report) viewBinding.symptomsDate.text = context.getString( R.string.symptoms_diagnosis_date, symptomsDateText ).fromHtml() val possibleInfectionDate = diagnosis.verificationData?.possibleInfectionDate val infectionDateText = possibleInfectionDate?.let { DateFormatter.format(it) } ?: context.getString(R.string.no_infection_date_report) viewBinding.infectionDate.text = context.getString(R.string.infection_diagnosis_date, infectionDateText).fromHtml() val testDiagnosisDate = diagnosis.verificationData?.testDate val testDateText = testDiagnosisDate?.let { DateFormatter.format(it) } ?: context.getString(R.string.no_test_date_report) viewBinding.testDate.text = context.getString(R.string.test_diagnosis_date, testDateText).fromHtml() viewBinding.btnDeleteDiagnosis.setOnClickListener { viewModel.deleteDiagnosis(diagnosis) } } override fun initializeViewBinding(view: View) = ItemPositiveDiagnosisChildBinding.bind(view) }
package dog.snow.androidrecruittest.repository.repos import dog.snow.androidrecruittest.repository.daos.PhotoDao import dog.snow.androidrecruittest.repository.database.AppDatabase import dog.snow.androidrecruittest.repository.model.RawPhoto import dog.snow.androidrecruittest.repository.model.RawPhotoEntity import dog.snow.androidrecruittest.repository.service.PhotoService import retrofit2.Response import retrofit2.Retrofit import java.net.SocketTimeoutException import java.net.UnknownHostException class PhotoRepo( /*private val db: AppDatabase, private val retrofit: Retrofit, private val photoService: PhotoService, private val photoDao: PhotoDao*/){ suspend fun getPhotos(photoService: PhotoService, limit: Int) : Response<List<RawPhoto>>{ return photoService.getPhotos(limit) } suspend fun getPhotosId(photoDao: PhotoDao) : List<Int>{ return photoDao.getPhotosId() } suspend fun getPhoto(photoDao: PhotoDao, id: Int) : RawPhotoEntity{ return photoDao.getPhoto(id) } suspend fun pushPhotos(photosList: List<RawPhoto>){ //photoDao.pushPhotos(mapPhotos(photosList)) } suspend fun deletePhoto(photoDao: PhotoDao, photo: RawPhotoEntity){ try { val delete = photoDao.deletePhotos(photo) if (delete != 1){ throw Exception() } }catch (e: Exception){ println("Error delete DAO-> photo") } } suspend fun getAlbumsId(photoDao: PhotoDao) : List<Int>{ val albums = photoDao.getAlbumsId() return albums.distinct() //wywala powtórzenai } /*fun mapPhoto (data: RawPhoto) : RawPhotoEntity{ return RawPhotoEntity(data.id, data.albumId, data.title, data.url, data.thumbnailUrl) }*/ fun mapPhotos (data: List<RawPhoto>) : List<RawPhotoEntity>{ val photos: MutableList<RawPhotoEntity> = mutableListOf() data.forEach { data-> photos.add(RawPhotoEntity(data.id, data.albumId, data.title, data.url, data.thumbnailUrl)) } return photos } suspend fun cachePhotos(photoService: PhotoService, photoDao: PhotoDao, limit: Int): String { try { val retrofitResponse = photoService.getPhotos(limit) if (retrofitResponse.isSuccessful) { retrofitResponse.body()?.let { data -> try { val insert = photoDao.pushPhotos(mapPhotos(data)) if (insert.isEmpty()){ throw Exception() } }catch (e: Exception){ println("Error DAO-> photo") return "Error DAO-> photo" } } return "" }else{ when(retrofitResponse.code()){ in 400..499 -> { println("Error SERVICE: Client-> photo") return "Error SERVICE: Client-> photo" } in 500..599 -> { println("Error SERVICE: Server-> photo") return "Error SERVICE: Server-> photo" } else -> { println("Error SERVICE-> photo") return "Error SERVICE-> photo" } } } }catch (e: Exception){ when (e){ is SocketTimeoutException ->{ println("Error SERVICE: SocketTimeoutException-> photo") return "Error SERVICE: SocketTimeoutException-> photo" } is UnknownHostException -> { println("Error SERVICE: UnknownHostException-> photo") return "Error SERVICE: UnknownHostException-> photo" } else -> { println("Error SERVICE: Exception-> photo") return "Error SERVICE: Exception-> photo" } } } } }
using System; using System.Threading.Tasks; namespace Qmmands { internal interface ITypeParser { Task<TypeParserResult<object>> ParseAsync(string value, ICommandContext context, IServiceProvider provider); } }
package jp.co.yuji.mydebugapplication.presentation.view.fragment.hard import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import jp.co.yuji.mydebugapplication.R import jp.co.yuji.mydebugapplication.presentation.view.fragment.BaseFragment import java.io.BufferedReader import java.io.InputStreamReader import kotlinx.android.synthetic.main.fragment_common_log.view.* /** * Memory Info Fragment */ class MemoryInfoFragment : BaseFragment() { companion object { const val command = "cat proc/meminfo" fun newInstance() : Fragment { return MemoryInfoFragment() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_common_log, container, false) view.logText.text = execute(MemoryInfoFragment.command) return view } override fun getTitle(): Int { return R.string.screen_name_memory_info } private fun execute(command: String) : String { var inputStreamReader : InputStreamReader? = null var bufferReader : BufferedReader? = null try { val process = Runtime.getRuntime().exec(command) inputStreamReader = InputStreamReader(process.inputStream) bufferReader = BufferedReader(inputStreamReader, 1024) return bufferReader.readText() } catch (e: Exception) { return e.message.toString() } finally { try { inputStreamReader?.close() bufferReader?.close() } catch (e: Exception) { return e.message.toString() } } } }
<style> p.combinado:first-letter { color: #00587A; font-size:xx-large; } </style> ![Legenda](imagens/capitulo.svg) # **Apresentação** ??? "➡️ Ferramentas de acessibilidade" :material-cursor-default-click-outline: Clique no botão abaixo para alternar visualização: <div class="tx-switch"> <button data-md-color-scheme="default"><code>Modo normal</code></button> <button data-md-color-scheme="slate"><code>Modo escuro</code></button> </div> <script> var buttons = document.querySelectorAll("button[data-md-color-scheme]") buttons.forEach(function(button) { button.addEventListener("click", function() { var attr = this.getAttribute("data-md-color-scheme") document.body.setAttribute("data-md-color-scheme", attr) var name = document.querySelector("#__code_0 code span:nth-child(7)") name.textContent = attr }) }) </script> <p style="text-align: right;"> Tiago Oliveira Motta<br> Daniela Melaré Vieira Barros<br> Eniel do Espírito Santo<br> Adilson Gomes dos Santos </p> <p style="text-align: justify;"> <p class="combinado">No ano de 2017, a Câmara de Pesquisa e Pós-Graduação da Universidade Federal do Recôncavo da Bahia aprovou o projeto do curso de Especialização em Tecnologias e Educação Aberta e Digital na modalidade a Distância, buscando o desenvolvimento de competências fundamentais para a concepção, desenvolvimento, avaliação e análise de ferramentas digitais e conteúdo de áudio, vídeo e multimídia; a identificação e descrição de diferentes quadros de referência e cenários de utilização de ambientes educativos emergentes online, promovendo o uso das tecnologias digitais; e a concepção, desenho e o desenvolvimento de um projeto com recurso para diferentes tecnologias e plataformas digitais. </p> </p> <p style="text-align: justify;"> Duas seleções foram realizadas com o ingresso de 200 estudantes em ambas as seleções e, dos estudantes ingressantes da segunda seleção desta especialização são, em sua maioria, professores do ensino fundamental e médio da rede pública do estado da Bahia são profissionais que tiveram seus polos presenciais em diferentes territórios de identidade do estado da Bahia: Macaúbas (Território Velho Chico), Remanso (Território Sertão do São Francisco), Sapeaçu (Território Recôncavo), Valença (Território Baixo Sul) e Vitória da Conquista (Território Sudoeste Baiano).</p> <p style="text-align: justify;"> Dentre os Trabalhos de Conclusão de Especialização defendidos em seção pública, conforme previsto no Projeto Pedagógico deste curso, aqueles que obtiveram seus artigos com as melhores avaliações foram convidados a contribuírem com seus trabalhos na composição dos capítulos deste livro. Assim, 24 autores contribuíram para a materialização deste livro. Esses trabalhos tiveram como principal fonte de dados estudos publicados em livros e periódicos, em sua maioria da área de Educação e Computação. Eles trataram de diversas dimensões do ensino a distância sempre com o olhar das tecnologias digitais.</p> <p style="text-align: justify;"> Organizado em 3 seções: Gamificação e Cibercultura (i); Tutoria, Ensino em Redes e Objetos Digitais de Aprendizagem (ii), e; Tecnologias Educacionais e Autonomia (iii). Tratam-se de temas caros para a Educação a Distância, modalidade de ensino que durante o período de pandemia ganhou ainda mais destaque na sociedade mundial, uma vez que a educação presencial no formato conhecido até então teve seu funcionamento inviabilizado.</p> <p style="text-align: justify;"> A seção I é formada por 8 capítulos relacionados à Gamificação e Cibercultura. Inicialmente o assunto tratado por Gama e Bezerra é o uso do jogo de xadrez como ferramenta para o desenvolvimento cognitivo de educandos. Em seguida Magalhães e Motta elencam as questões de pesquisa relacionadas ao ensino de Matemática na educação básica (Ensino Fundamental e Médio) utilizando a Gamificação. No capítulo seguinte, Marinho e Gomes discutem o ensino de História utilizando Jogos Digitais. Esse capítulo é sucedido pelo trabalho de Silva Júnior e Motta que, por sua vez, trataram da influência dos Jogos Digitais no ensino de Matemática nos anos finais do Ensino Fundamental. Em seguida, Silva e Gomes apresentaram as dificuldades enfrentadas para a efetiva aplicação da Gamificação nos ambientes educacionais. Nesse mesmo sentido, Souza e Lago apresentaram os desafios e potencialidades na aplicação da Gamificação no processo educativo. Em seguida, Alves e Silva apresentam uma análise de expressões artísticas onde a arte e a tecnologia se entrelaçaram na sociedade e cultura digital. Por fim, Gonzalez e Silva discutiram desafios e potencialidades dos processos de ensino e aprendizagem na cibercultura no escopo do ensino fundamental.</p> <p style="text-align: justify;"> A seção II é composta por 9 capítulos relacionados à Tutoria, Ensino de Redes e Objetos Digitais de Aprendizagem. Essa seção é inaugurada com o texto de Anunciação e Santo num trabalho onde são discutidas as habilidades e competências necessárias ao docente que atua no ensino à distância. No capítulo seguinte, Assis e Silva apresentaram o papel do tutor na Educação a Distância, listando as funções por eles assumidas, assim como os desafios enfrentados e as suas perspectivas. Santos e Bezerra dão continuidade no estudo dos papeis e desafios dos tutores, e demonstram em seu texto a importância dos tutores para o sucesso de educandos em turmas que ocorrem no formato de Educação a Distância. Em seguida, Silva e Santo trazem à tona aspectos essenciais ao bom funcionamento de comunidades virtuais de aprendizagem. Fernandes e Passos, por sua vez, destacam a importância da Tecnologia da Informação para o sucesso da aprendizagem em rede. No capítulo seguinte, Ferreira e Zunino analisam os efeitos e mudanças introduzidas pelas Tecnologias Digitais da Informação e Comunicação e o uso de ferramentas da Web enquanto espaços de aprendizagem colaborativa e em rede em sala de aula. Em seguida, Pereira e Henriques trouxeram reflexões acerca da análise realizada sobre o potencial educativo das redes sociais na internet. No capítulo seguinte, Leite e Correia discutem o uso e a aplicação de Objetos Digitais de Aprendizagem no âmbito da Educação Técnica e Profissional. No fechamento dessa seção, Siqueira e Santana analisaram produções presentes na internet a respeito do topônimo Gongogi a partir da criação de repositórios digitais escolares e ações interdisciplinares.</p> <p style="text-align: justify;"> A seção III deste livro reúne capítulos contendo estudos relacionados à Tecnologias Educacionais e à Autonomia dos educandos. Inicialmente Carvalho e Sousa avaliam os benefícios do uso do Storytelling na produção de conteúdo educacional voltado ao Ensino a Distância, buscando o engajamento dos estudantes. No capítulo seguinte, Melo e Rosado apresentam um estudo onde foram utilizadas placas de Arduíno para estudar o comportamento das marés. Em seguida, Menezes Filho e Silva analisam as possibilidades da abordagem do Ensino Híbrido através da implementação da Sala de Aula Invertida no processo educacional e a participação das Tecnologias Digitais nesse processo. Em seguida Nascimento e Lago discutem o uso do aplicativo QR Code como recurso pedagógico no ensino da Língua Portuguesa. No capítulo seguinte, Santos e Passos apresentam o cenário recente acerca do uso de tecnologias em escolas públicas de zona rural no Brasil. Em seguida Silva e Nejmeddine apresentam uma investigação sobre o efeito da produção de vídeos como estimuladora da criatividade em processos de ensino e aprendizagem na Educação Superior brasileira. Por fim, Viana e Rocha apresentam as contribuições trazidas por estudos culturais para a educação de surdos numa perspectiva 2.0.</p> <p style="text-align: justify;"> Esperamos que essa coletânea de estudos possa colaborar com educadores, coordenadores pedagógicos, implementadores de políticas públicas, pesquisadores e pessoas interessadas em estudos sobre educação, seja no seu exercício profissional, seja na atualização profissional de cada agente ou na construção de um projeto educacional avançado e que utilize Tecnologias Digitais.</p>
<?php namespace Drupal\Tests\migrate_source_csv\Kernel\Plugin\migrate\source; use Drupal\node\Entity\Node; use Drupal\Tests\migrate\Kernel\MigrateTestBase; /** * @coversDefaultClass \Drupal\migrate_source_csv\Plugin\migrate\source\CSV * * @group migrate_source_csv */ class CSVTest extends MigrateTestBase { /** * {@inheritdoc} */ public static $modules = [ 'system', 'field', 'user', 'node', 'datetime', 'migrate', 'migrate_source_csv', 'migrate_source_csv_test', ]; /** * Tests execution of a migration sourced from CSV. */ public function testMigrate() { $this->installEntitySchema('user'); $this->installEntitySchema('node'); $this->installConfig(['migrate_source_csv_test']); /** @var \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migrationManager */ $migrationManager = $this->container->get('plugin.manager.migration'); $migration = $migrationManager->createInstance('migrate_csv_test'); $this->executeMigration($migration); $node = Node::load(1); $this->assertEquals($node->label(), 'Justin Dean'); $this->assertEquals($node->get('field_first_name')->value, 'Justin'); $this->assertEquals($node->get('field_last_name')->value, 'Dean'); $this->assertEquals($node->get('field_email')->value, 'jdean0@example.com'); $this->assertEquals($node->get('field_ip_address')->value, '60.242.130.40'); $this->assertEquals($node->get('field_dob')->value, '1955-01-05'); } }
from haystack import indexes from haystack import site from jazzpos.models import Customer, Patient class CustomerIndex(indexes.RealTimeSearchIndex): text = indexes.CharField(document=True, use_template=True) class PatientIndex(indexes.RealTimeSearchIndex): text = indexes.CharField(document=True, use_template=True) site.register(Customer, CustomerIndex) site.register(Patient, PatientIndex)
// // SwordInstallSource.h // Eloquent // // Created by Manfred Bergmann on 13.08.07. // Copyright 2007 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> #import "SwordModule.h" #ifdef __cplusplus #include <swmgr.h> #include <installmgr.h> #endif @class SwordManager; @class SwordInstallSourceManager; #define INSTALLSOURCE_TYPE_FTP @"FTP" @interface SwordInstallSource : NSObject - (id)init; #ifdef __cplusplus - (id)initWithSource:(sword::InstallSource *)is; #endif - (id)initWithType:(NSString *)aType; @property (retain, readwrite) NSString *caption; @property (retain, readwrite) NSString *type; @property (retain, readwrite) NSString *source; @property (retain, readwrite) NSString *directory; @property (readwrite) BOOL deleteOnDealloc; - (BOOL)isLocalSource; // get config entry - (NSString *)configEntry; // install module - (void)installModuleWithName:(NSString *)mName usingManager:(SwordManager *)swManager withInstallController:(SwordInstallSourceManager *)sim; /** List of available InstallSources */ - (NSDictionary *)allModules; /** List of modules for given type */ - (NSArray *)listModulesForType:(ModuleType)aType; /** list module types */ - (NSArray *)listModuleTypes; /** Returns the SwordManager attached to this SwordInstallSource */ - (SwordManager *)swordManager; #ifdef __cplusplus - (sword::InstallSource *)installSource; #endif @end
class LocationFacade class << self def coordinates(location) data = MapquestService.coordinates(location) data[:results].map do |location| Coordinate.new(location) end end end end
use App::KADR::Path -all; use common::sense; use FindBin; use Test::More; my $file = dir($FindBin::Bin)->file('file.t'); subtest 'abs_cmp' => sub { ok $file == dir($FindBin::Bin)->file('file.t'); ok $file != dir($FindBin::Bin)->file('dir.t'); ok $file != dir($FindBin::Bin, 'file.t'); }; done_testing;
import { browser } from "webextension-polyfill-ts"; import { utils } from "../browser"; import { handleSelection } from "./selection"; const CONTEXT_MENU_CONTENTS = { forSelection: ["Add endpoint"], }; export const setupContextMenus = () => { CONTEXT_MENU_CONTENTS.forSelection.forEach(commandId => { browser.contextMenus.create({ type: "separator", id: "sep1", contexts: ["selection"], }); browser.contextMenus.create({ title: commandId + ' "%s"', id: commandId, contexts: ["selection"], }); }); addContextMenuClickedHandler(); }; const addContextMenuClickedHandler = () => { browser.contextMenus.onClicked.addListener(async item => { console.log( `Selection menu '${item.menuItemId}' got selection: '${ item.selectionText }'` ); if (!item.selectionText) { return; } const tab = await utils.getActiveTab(); const url = tab.url; await handleSelection({ url, selection: item.selectionText }); }); };
/* * Copyright 2019 PingCAP, Inc. * * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.pingcap.tispark import com.pingcap.tikv.meta.TiTimestamp import org.apache.spark.sql.sources._ import org.apache.spark.sql.types.StructType import org.apache.spark.sql.{DataFrame, SQLContext, SaveMode, TiContext} /** * TiDB Source implementation for Spark SQL */ class TiDBDataSource extends DataSourceRegister with RelationProvider with SchemaRelationProvider with CreatableRelationProvider { override def shortName(): String = "tidb" override def toString: String = "TIDB" /** * Create a new `TiDBRelation` instance using parameters from Spark SQL DDL. */ override def createRelation(sqlContext: SQLContext, parameters: Map[String, String]): BaseRelation = { val options = new TiDBOptions(parameters) val tiContext = new TiContext(sqlContext.sparkSession, Some(options)) TiSparkConnectorUtils.checkVersionAndEnablePushdown(sqlContext.sparkSession, tiContext) val ts = tiContext.tiSession.createTxnClient().getTimestamp TiDBRelation(tiContext.tiSession, options.tiTableRef, tiContext.meta, ts, Some(options))( sqlContext ) } /** * Load a `TiDBRelation` using user-provided schema, so no inference over TiDB will be used. */ override def createRelation(sqlContext: SQLContext, parameters: Map[String, String], schema: StructType): BaseRelation = // TODO: use schema info // pending: https://internal.pingcap.net/jira/browse/TISPARK-98 createRelation(sqlContext, parameters) /** * Creates a Relation instance by first writing the contents of the given DataFrame to TiDB */ override def createRelation(sqlContext: SQLContext, saveMode: SaveMode, parameters: Map[String, String], df: DataFrame): BaseRelation = { val options = new TiDBOptions(parameters) TiDBWriter.write(df, sqlContext, saveMode, options) createRelation(sqlContext, parameters) } }
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import 'package:amplify_authenticator/amplify_authenticator.dart'; import 'package:amplify_authenticator/src/keys.dart'; import 'package:amplify_authenticator/src/state/inherited_authenticator_state.dart'; import 'package:amplify_flutter/amplify_flutter.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; /// Loads the given [authenticator] widget and waits for it to render. Future<void> loadAuthenticator({ required WidgetTester tester, required Widget authenticator, }) async { // resolves issue on iOS. See: https://github.com/flutter/flutter/issues/89651 final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized() as IntegrationTestWidgetsFlutterBinding; if (!binding.sendFramesToEngine) binding.allowFirstFrame(); await tester.pumpWidget(authenticator); await tester.pumpAndSettle(); } /// Waits for the next bloc event. Future<void> nextBlocEvent( WidgetTester tester, { BlocEventPredicate? where, Duration timeout = const Duration(seconds: 5), }) async { final inheritedViewModel = tester.widget<InheritedAuthenticatorState>( find.byKey(keyInheritedAuthenticatorState), ); await inheritedViewModel.state.nextBlocEvent(where: where).timeout(timeout); await tester.pumpAndSettle(); } /// Do nothing. void noOp() {} /// Signs out the current user, if any. Safe to call anywhere. Future<void> signOut() async { try { await Amplify.Auth.signOut(); // ignore: avoid_catches_without_on_clauses } catch (_) {} }
/* Copyright 2017 Gravitational, Inc. 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 monitoring import ( "context" "fmt" "runtime" "github.com/gravitational/satellite/agent/health" pb "github.com/gravitational/satellite/agent/proto/agentpb" "github.com/gravitational/trace" "github.com/cloudfoundry/gosigar" "github.com/dustin/go-humanize" ) // NewHostChecker returns a new checker to validate host environment func NewHostChecker(config HostConfig) health.Checker { return &hostChecker{ HostConfig: config, getMemory: realGetMemory, getCPU: realGetCPU, } } // HostConfig describes host environment requirements type HostConfig struct { // MinCPU specifies the minimum amount of logical CPUs to expect MinCPU int // MinRAMBytes specifies the minimum amount of RAM to expect MinRAMBytes uint64 } // hostChecker validates CPU and RAM requirements type hostChecker struct { HostConfig getMemory memoryGetterFunc getCPU cpuGetterFunc } // Name returns checker id // Implements health.Checker func (c *hostChecker) Name() string { return hostCheckerID } // Check validates that the host has enough RAM/CPU. // Implements health.Checker func (c *hostChecker) Check(ctx context.Context, reporter health.Reporter) { var probes health.Probes err := c.check(ctx, &probes) if err != nil && !trace.IsNotFound(err) { reporter.Add(NewProbeFromErr(c.Name(), "failed to validate host environment", err)) return } health.AddFrom(reporter, &probes) if probes.NumProbes() != 0 { return } reporter.Add(NewSuccessProbe(c.Name())) } func (c *hostChecker) check(ctx context.Context, reporter health.Reporter) error { mem, err := c.getMemory() if err != nil { return trace.Wrap(err, "failed to query memory info") } if mem.Total < c.MinRAMBytes { reporter.Add(&pb.Probe{ Checker: c.Name(), Detail: fmt.Sprintf("at least %s of RAM required, only %s available", humanize.Bytes(c.MinRAMBytes), humanize.Bytes(mem.Total)), Status: pb.Probe_Failed, }) } if c.getCPU() < c.MinCPU { reporter.Add(&pb.Probe{ Checker: c.Name(), Detail: fmt.Sprintf("at least %d CPUs required, only %d available", c.MinCPU, c.getCPU()), Status: pb.Probe_Failed, }) } return nil } type memoryGetterFunc func() (*sigar.Mem, error) func realGetMemory() (*sigar.Mem, error) { var mem sigar.Mem if err := mem.Get(); err != nil { return nil, trace.ConvertSystemError(err) } return &mem, nil } type cpuGetterFunc func() (numCPU int) func realGetCPU() (numCPU int) { return runtime.NumCPU() } const ( hostCheckerID = "cpu-ram" )
import { GetStaticProps } from "next"; import Head from "next/head"; import Link from "next/link"; import { api } from "../../services/api"; import { Table, Space, Popconfirm } from "antd"; import "antd/dist/antd.css"; import styles from "./users.module.scss"; type User = { id: number; email: string; name: string; unitId: number; companyId: number; }; type UserProps = { allUsers: User[]; }; async function deleteUser(id) { // Comentei para não quebrar a aplicação, pois a rota da api não funciona // const { data } = await api.delete("users", { // params: { // id: id, // }, // }); } const columns = [ { title: "Nome", dataIndex: "name", key: "name", }, { title: "E-mail", dataIndex: "email", key: "email", }, { title: "Unidade", dataIndex: "unitName", key: "unit", }, { title: "Empresa", dataIndex: "companyName", key: "company", }, { title: "Ações", key: "action", render: (text, user) => ( <Space> <Link href={`/users/${user.id}`}>Editar</Link> <Popconfirm title={`Tem certeza que deseja excluir ${user.name}?`} okText="Sim" cancelText="Não" onConfirm={() => deleteUser(user.id)} > <a href={`/users/${user.id}`}>Excluir</a> </Popconfirm> </Space> ), }, ]; export default function User({ allUsers }: UserProps) { return ( <div className={styles.userContainer}> <Head> <title>Usuários | Tractian</title> </Head> <section className={styles.users}> <h2>Usuários</h2> <Table className={styles.table} columns={columns} dataSource={allUsers} /> </section> </div> ); } export const getStaticProps: GetStaticProps = async () => { const { data } = await api.get("users", { params: {}, }); async function getUnits() { const { data } = await api.get("units", { params: {}, }); return data; } async function getCompanies() { const { data } = await api.get("companies", { params: {}, }); return data; } const units = await getUnits(); const companies = await getCompanies(); function getNameUnit(id) { const unit = units.find(unit => unit.id === id); return unit.name; } function getNameCompany(id) { const company = companies.find(company => company.id === id); return company.name; } const allUsers = data.map(user => { const companyName = getNameCompany(user.companyId); const unitName = getNameUnit(user.unitId); return { id: user.id, name: user.name, email: user.email, unitId: user.unitId, companyId: user.companyId, unitName: unitName, companyName: companyName, }; }); return { props: { allUsers, }, revalidate: 60 * 60 * 8, }; };
package io.idml.functions import io.idml.datanodes.IDouble import io.idml.{IdmlArray, IdmlNothing, IdmlValue, InvalidCaller} /** Calculate an average value */ case object AverageFunction extends IdmlFunction0 { def name: String = "average" protected def apply(cursor: IdmlValue): IdmlValue = { cursor match { case nothing: IdmlNothing => nothing case array: IdmlArray if array.items.size > 0 => // FIXME: turn Idml into a numeric and replace this with sum() val sum = array.items.reduce((l, r) => l.+(r)) sum / IDouble(array.items.size) case other: Any => InvalidCaller } } }
package com.mytest.composetest.coroutinetest import androidx.lifecycle.asLiveData import com.mytest.composetest.util.LogDebug import com.mytest.composetest.util.LogError import kotlinx.coroutines.* import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.* import kotlin.coroutines.CoroutineContext class CallbackFlowTest : CoroutineScope { private val TAG = "CallbackFlowTest" override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.Main data class TestText(var msg: String) private fun getCallbackFlowTest(): Flow<String> { return callbackFlow { repeat(10000) { delay(100) trySend("body thread:${Thread.currentThread().name} - $it") } awaitClose { // } } .map { delay(1000) "map thread:${Thread.currentThread().name} | $it" } .conflate() .flowOn(Dispatchers.IO) } suspend fun test() { getCallbackFlowTest().collect { delay(2000) LogError(TAG) { it } } } fun test2() = getCallbackFlowTest().asLiveData() private fun initForPreload() = callbackFlow { //... trySend { 1 // 임시로 넣은값 } awaitClose { //... } } .conflate() .map { it //기존 map 내용 추가 } .flowOn(Dispatchers.IO) //Dispatchers.IO 대신 keyDefaultCoroutineDispatcher 사용 .asLiveData() private fun initForDownloadable() { //... callbackFlow { //... trySend { 1 // 임시로 넣은값 } awaitClose { //... } } .conflate() .onEach { //map의 내용 + collect에 있던 내용 } .launchIn(this + Dispatchers.IO) //Dispatchers.IO 대신 keyDefaultCoroutineDispatcher 사용 // Transformation.map 을 return } fun callbackFlowTest2() { LogDebug(TAG) { "callbackFlowTest2() - START" } callbackFlow { repeat(10000) { delay(100) trySend("body thread:${Thread.currentThread().name} - $it") } awaitClose { // } } .conflate() .onEach { delay(1000) LogError(TAG) { "map thread:${Thread.currentThread().name} | $it" } } .launchIn(this + Dispatchers.IO) LogDebug(TAG) { "callbackFlowTest2()- END" } } suspend fun getCallbackFlowTest4() { callbackFlow<TestText> { val testText = TestText("start") repeat(10000) { delay(100) val msg = "body thread:${Thread.currentThread().name} - $it" // testText.msg = msg // trySend(testText) trySend(TestText("aa")) } awaitClose { // } } .distinctUntilChanged() .collect { LogError(TAG) {it.msg} } } }
; uninterpreted functions ; expect: SAT (decl-ty u) (decl a u) (decl b u) (decl f (-> u prop)) (assert (not (= (f a) (f b)))) ; u = {a,b} (assert (forall (x u) (or (= x a) (= x b)))) (goal ((x u)) (not (= (f x) (f b))))
module Listen module Adapters DEFAULT_POLLING_LATENCY = 1.0 # Polling Adapter that works cross-platform and # has no dependencies. This is the adapter that # uses the most CPU processing power and has higher # file IO than the other implementations. # class Polling < Adapter private # The default delay between checking for changes. # # @see Listen::Adapter#default_latency # def default_latency 1.0 end # The thread on which the main thread should wait # when the adapter has been started in blocking mode. # # @see Listen::Adapter#blocking_thread # def blocking_thread poller_thread end # @see Listen::Adapter#start_worker # # @see Listen::Adapter#start_worker # def start_worker # The polling adapter has no worker! Sad panda! :'( end # Poll listener directory for file system changes. # # @see Listen::Adapter#poll_changed_directories # def poll_changed_directories until stopped next if paused start = Time.now.to_f callback.call(directories.dup, :recursive => true) turnstile.signal nap_time = latency - (Time.now.to_f - start) sleep(nap_time) if nap_time > 0 end rescue Interrupt end end end end
import React from 'react'; import currencyFormatter from 'currency-formatter'; const CurrencyFormatter = (props) => { return ( <span> {currencyFormatter.format(props.amount, {locale: 'en-GB'})} </span> ); } export default CurrencyFormatter;
require 'unit_helper' class EndOfDayTest < Test::Unit::TestCase context "Initializing" do setup do @request = end_of_day_request end [ :options ].each do |attr| should "set @#{attr} instance variable" do assert_not_nil @request.send(attr) end end end context "A base request" do setup do @request = end_of_day_request end should "delegate to options" do assert_delegates_to_ostruct(@request, @request.options, *[ :login, :password, :merchant_id, :bin, :terminal_id, :currency_code, :currency_exponent, :customer_ref_num, :order_id ]) end end end
const constExistsIn = ({ name, constants, prefix, value }) => { const constant = constants[name] const expectation = `${name} is defined` const actual = `(actual value '${constant}')` expect(constant).to.not.equal(undefined, expectation + ' ' + actual) if (value !== undefined) { expect(constant === value).to.equal(true, `${expectation} and equals ${value} ${actual}`) } else if (prefix !== undefined) { expect(constant.startsWith(prefix)).to.equal(true, `${expectation} and starts with ${prefix} ${actual}`) } } const allConstExistIn = ({ list, ...other }) => { for (let name of list) { constExistsIn({ name, ...other }) } } export default { constExistsIn, allConstExistIn }
import React from 'react'; import '../styles/components/no-post-found.css'; const NoPostFound = () => { return ( <> <div className='no-post-found__img-container'> <img src='https://static.platzi.com/static/images/error/img404.png' alt='No post found' /> </div> <p className='no-post-found__text'> Parece que el artículo que buscas no existe. {' '} <br /> ¿Y si lo escribes? 🤓 </p> </> ); }; export default NoPostFound;
# Imitation Learning In this repository we implement, test, and examine some of the well-known IL algorithms. - [x] DAGGER - [x] Confidence-Based Autonomy (CBA) - [ ] BCO - [ ] GAIL
package Catmandu::Store::File::Multi::Bag; use Catmandu::Sane; our $VERSION = '1.16'; use Moo; use Catmandu::Util qw(:is); use Catmandu::Logger; use namespace::clean; extends 'Catmandu::Store::Multi::Bag'; with 'Catmandu::FileBag'; sub add { my ($self, $data) = @_; # Overwrite the Multi::Bag add an store each stream in the backend store my $rewind = 0; my $id = $data->{_id}; my $stream = $data->{_stream}; my $new_data = {}; # By default try to add the data to all the stores for my $store (@{$self->store->stores}) { my $bag = $store->bag($self->name); next unless $bag; if ($rewind) { # Rewind the stream after first use... Catmandu::BadVal->throw("IO stream needs to seekable") unless $stream->isa('IO::Seekable'); $stream->seek(0, 0); } my $file = {_id => $id, _stream => $stream}; $bag->add($file); for (keys %$file) { $new_data->{$_} = $file->{$_} unless exists $new_data->{$_}; } $rewind = 1; } # Check if the returned record contains the minimum required fields # (otherwise we have a File::Store implementation that doesn't inline # update the passed $data in add($data)) if ( exists $new_data->{size} && exists $new_data->{created} && exists $new_data->{modified}) { # all is ok } else { $self->log->warn( "$self doesn't inline update \$data in add(\$data) method"); $new_data = $self->get($id); } if ($new_data) { $data->{$_} = $new_data->{$_} for keys %$new_data; } else { $self->log->error("can't find $id in $self!"); } 1; } sub upload { my ($self, $io, $id) = @_; # Upload in a FileStore should send data, in a normal Store it adds an # empty record my $rewind; my $bytes = 0; for my $store (@{$self->store->stores}) { if ($store->does('Catmandu::FileStore')) { my $bag = $store->bag($self->name); next unless $bag; if ($rewind) { # Rewind the stream after first use... Catmandu::BadVal->throw("IO stream needs to seekable") unless $io->isa('IO::Seekable'); $io->seek(0, 0); } $bytes = $store->bag($self->name)->upload($io, $id) || $self->log->error( "failed to upload $id to " . $self->name); $rewind = 1; } else { my $bag = $store->bag($self->name); next unless $bag; $bag->add({_id => $id}); } } return $bytes; } 1; __END__ =pod =head1 NAME Catmandu::Store::File::Multi::Bag - Index of all "files" in a Catmandu::Store::File::Multi "folder" =head1 SYNOPSIS use Catmandu; my $store = Catmandu->store('File::Multi' , stores [ Catmandu->store('File::Simple', root => '/data1/files') , Catmandu->store('File::Simple', root => '/data1/files_copy') , ]); my $index = $store->index; # List all containers $index->each(sub { my $container = shift; print "%s\n" , $container->{_id}; }); # Add a new folder $index->add({_id => '1234'}); # Delete a folder $index->delete(1234); # Get a folder my $folder = $index->get(1234); # Get the files in an folder my $files = $index->files(1234); $files->each(sub { my $file = shift; my $name = $file->{_id}; my $size = $file->{size}; my $content_type = $file->{content_type}; my $created = $file->{created}; my $modified = $file->{modified}; $file->stream(IO::File->new(">/tmp/$name"), file); }); # Add a file $files->upload(IO::File->new("<data.dat"),"data.dat"); # Retrieve a file my $file = $files->get("data.dat"); # Stream a file to an IO::Handle $files->stream(IO::File->new(">data.dat"),$file); # Delete a file $files->delete("data.dat"); # Delete a folders $index->delete("1234"); =head1 INHERITED METHODS This Catmandu::Bag implements: =over 3 =item L<Catmandu::Bag> =item L<Catmandu::FileBag> =item L<Catmandu::Droppable> =back =cut
<div class="header"> <div class="left"> <href href="#" data-href="/"><h1><span>DUO</span>SCAN</h1></href> </div> </div> <div id="install"> <h1>Instalando DUOSCAN</h1> <form action=""> <span>É para criar uma conta admin</span> <input type="text" placeholder="E-mail" id="email"> <input type="text" placeholder="Senha" id="senha"> <span>Configurando um banco de dados</span> <input type="text" placeholder="Hostname" id="hostname"> <input type="text" placeholder="Database" id="database"> <input type="text" placeholder="Senha banco de dados" id="senha_banco"> <button>Instalar</button> </form> </div> <style> #install{ position: relative; width: calc(100% - 100px - 30vw); height: auto; background: #3F51B5; top: 70px; text-align: center; padding: 30px; padding-bottom: 120px; margin: 0px auto; } #install span{ position: relative; padding: 0px; font-size: 22px; top: 5px; float: left; padding: 20px 10px 20px; } #install input{ width: 100%; border: none; margin-top: 20px; font-size: 22px; padding: 10px; border-radius: 30px; position: relative; left: -10px; } #install button{ width: 50%; border: none; top: 40px; position: relative; padding: 10px; background: #8BC34A; font-size: 22px; color: #151515; cursor: pointer; } </style> <script></script> </div>
class ClassName < ActiveRecord::Base belongs_to :teacher has_many :student_teacher_classes has_many :students, through: :student_teacher_classes has_many :curriculums, dependent: :destroy has_many :assignments, through: :curriculums, dependent: :destroy include Sluggable::InstanceMethods extend Sluggable::ClassMethods def self.create_new_class(session, params) @teacher = Teacher.find(session[:user_id]) @class = ClassName.create(name: params[:name], teacher_id: @teacher.id) params[:student].each do |student| if student[:name] != "" student = Student.create(student) StudentTeacherClass.create(student_id: student.id, class_name_id: @class.id) end end @teacher end end
Det er mange ulike måter en kan vurdere et programmeringsprosjekt, og her må en selv vurdere hva som er den beste måten ut ifra hvilket fag man jobber i, hvilken aldergruppe og hvilket nivå elevene er på, hva man ønsker å teste og hvor mye tid man har til rådighet til å jobbe med prosjektet. I vårt [lærerdokument](../../pages/hvordan_bruke_lærerveiledning.html) har vi blant annet beskrevet ulike måter dette kan gjøres på, tillegg til en del andre nyttige tips til hvordan man underviser i programmering.
# Логические функции Логические функции принимают любые числовые типы, а возвращают число типа UInt8, равное 0 или 1. Ноль в качестве аргумента считается "ложью", а любое ненулевое значение - "истиной". ## and, оператор AND ## or, оператор OR ## not, оператор NOT ## xor
#!/usr/bin/env bash # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ###################################### # install_container_management # # installs moby-engine docker container management if needed. # ARGUMENTS: # # OUTPUTS: # Write output to stdout # RETURN: # updates the global variable OK_TO_CONTINUE in case of failure to false. ###################################### install_container_management() { if [ -x "$(command -v docker)" ]; then log_info "docker command is already available." else log_info "Installing moby-engine container management" apt-get install moby-engine -y 2>>$STDERR_REDIRECT 1>>$STDOUT_REDIRECT & long_running_command $! exit_code=$? if [[ $exit_code != 0 ]]; then log_info "moby-engine installation failed with code: %d" $exit_code exit ${EXIT_CODES[8]} fi log_info "Installed moby-engine container management" fi }
<?php namespace App\Http\Controllers; use App\Category, App\Post; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class PostsByCategoryController extends Controller { public function __invoke($key) { $posts = Category::where('key', '=', $key)->first()->post(); return view('posts_by_category', ['posts' => $posts->paginate(10), 'category' => Category::where('key', '=', $key)->first() ] ); } }
public class Produto { String descricao; String fornecedor; double valorCusto; int quantidade; public double calcularValorEmEstoque() { return this.valorCusto * this.quantidade; } public double adicionarAoValorCusto() { return this.valorCusto * 1.65; } public double adicionarQualquerPorcentagemAoValorCusto(int porcentagem) { return this.valorCusto + this.valorCusto * (porcentagem/100); } public String toString() { return ("Descrição do produto:" + this.descricao +"\n Fornecedor: " + this.fornecedor +"\n Valor de custo:" + this.valorCusto +"\n Quantidade em estoque: " + this.quantidade +"\n Valor em estoque: " + this.calcularValorEmEstoque() +"\n Valor custo com acréscimo de 65%: \n" + this.adicionarAoValorCusto() ); } }
require 'test_helper' class FindingReviewAssignmentTest < ActiveSupport::TestCase setup do @finding_review_assignment = finding_review_assignments :review_without_conclusion_being_implemented_weakness end test 'create' do assert_difference 'FindingReviewAssignment.count' do @finding_review_assignment = FindingReviewAssignment.create!( review: reviews(:review_without_conclusion), finding: findings(:unanswered_weakness) ) end end test 'update' do old_updated_at = @finding_review_assignment.updated_at assert @finding_review_assignment.touch, @finding_review_assignment.errors.full_messages.join('; ') @finding_review_assignment.reload assert_not_equal old_updated_at, @finding_review_assignment.updated_at end test 'destroy' do finding_review_assignment = finding_review_assignments :review_without_conclusion_being_implemented_weakness assert_difference 'FindingReviewAssignment.count', -1 do finding_review_assignment.destroy end end test 'destroy gets cancelled if repeated' do finding_review_assignment = finding_review_assignments :review_without_conclusion_being_implemented_weakness finding_review_assignment.finding.update! state: Finding::STATUS[:repeated] assert_no_difference 'FindingReviewAssignment.count' do finding_review_assignment.destroy end end test 'validates blank atrtributes' do @finding_review_assignment.finding_id = nil assert @finding_review_assignment.invalid? assert_error @finding_review_assignment, :finding_id, :blank end test 'validates duplicated review' do review = @finding_review_assignment.review # Para que ARel cargue la relación review.finding_review_assignments.map(&:finding_id) finding_review_assignment = review.finding_review_assignments.build( finding_id: @finding_review_assignment.finding_id ) finding_review_assignment.review = review assert finding_review_assignment.invalid? assert_error finding_review_assignment, :finding_id, :taken end end
class Chef < ActiveRecord::Base belongs_to :employable, polymorphic: true end class ChefList < Chef belongs_to :employable_list, polymorphic: true end
'use strict'; const express = require('express'); const categories = require('../lib/models/categories/categories.collection') const router = express.Router(); router.post('/categories', postCategory); router.get('/categories', getCategory); router.get('/categories/:id', getCategory); router.put('/categories/:id', updateCategory); router.delete('/categories/:id', deleteCategory); // categories routes function getCategory (req, res, next) { let id = req.params.id; categories.read(id).then(data=>{ res.status(200).json(data); }) .catch(next); } function postCategory (req, res, next){ categories.create(req.body).then(data=>{ res.status(201).json(data); }) .catch(next); } function updateCategory (req, res, next){ let id = req.params.id; categories.update(id, req.body).then(()=>{ categories.read(id).then(data=>{ res.status(200).json(data); }) }) .catch(next); } function deleteCategory (req, res, next){ let id = req.params.id; categories.delete(id).then(data=>{ res.status(200).json(data); }) .catch(next); } module.exports = router;
# scikit-vm # Usage ## Start VM <code> vagrant up </code> ## Login as Root <code> vagrant ssh ... sudo su </code> Let's play scikit!
import 'package:pkgraph/src/models/package_version.dart'; import 'package:test/test.dart'; void main() { group('PackageVersion', () { Map<String, dynamic> json; setUp(() { json = { 'author': 'krieger', 'authors': ['archer', 'lana'], 'dependencies': { 'package_a': '^1.0.0', 'package_b': '2.0.0', }, 'description': 'the description', 'dev_dependencies': { 'package_c': '0.1.2', 'package_d': '^3.0.0', }, 'environment': { 'sdk': '>=2.0.0 <3.0.0', }, 'homepage': 'https://homepage.com', 'name': 'package', 'version': '0.1.2', }; }); group('.fromJson', () { test('should correctly read a minimal map', () { final version = PackageVersion.fromJson( json, source: 'source', ordinal: 0, ); expect(version.author, 'krieger'); expect(version.authors, const ['archer', 'lana']); expect(version.dependencies, hasLength(2)); final first = version.dependencies.first; expect(first.packageName, 'package_a'); expect(first.constraint.toString(), '^1.0.0'); final second = version.dependencies.last; expect(second.packageName, 'package_b'); expect(second.constraint.toString(), '2.0.0'); expect(version.description, 'the description'); final firstDev = version.devDependencies.first; expect(firstDev.packageName, 'package_c'); expect(firstDev.constraint.toString(), '0.1.2'); final secondDev = version.devDependencies.last; expect(secondDev.packageName, 'package_d'); expect(secondDev.constraint.toString(), '^3.0.0'); expect(version.sdk.toString(), '>=2.0.0 <3.0.0'); expect(version.homepage.toString(), 'https://homepage.com'); expect(version.name, 'package'); expect(version.version.toString(), '0.1.2'); expect(version.major, 0); expect(version.minor, 1); expect(version.patch, 2); expect(version.source, 'source'); expect(version.ordinal, 0); }); }); }); }
package trwmutex import "sync" // TRWMutex is extended RWMutex which have TryLock() and TryRLock(). type TRWMutex struct { mu sync.Mutex rwmu sync.RWMutex w int r int } // Lock locks m and wait until all other Lock or RLock is unlocked. func (m *TRWMutex) Lock() { m.mu.Lock() m.w++ if m.r > 0 || m.w > 1 { // other one already acquired lock. wait outside of m.mu lock m.mu.Unlock() m.rwmu.Lock() } else { // m.rwmu.Lock() never blocks m.rwmu.Lock() m.mu.Unlock() } } // TryLock try to lock m. returns false if fails. func (m *TRWMutex) TryLock() bool { m.mu.Lock() if m.r > 0 || m.w > 0 { // other one already acquired lock. m.mu.Unlock() return false } m.w++ // m.rwmu.Lock() never blocks m.rwmu.Lock() m.mu.Unlock() return true } // Unlock unlocks m. func (m *TRWMutex) Unlock() { m.mu.Lock() m.w-- m.rwmu.Unlock() m.mu.Unlock() } // RLock locks m shared and until other Lock is unlocked. func (m *TRWMutex) RLock() { m.mu.Lock() m.r++ if m.w > 0 { // other one already acquired lock. wait outside of m.mu lock m.mu.Unlock() m.rwmu.RLock() } else { // m.rwmu.RLock() never blocks m.rwmu.RLock() m.mu.Unlock() } } // TryRLock try to lock m shared. returns false if fails. func (m *TRWMutex) TryRLock() bool { m.mu.Lock() if m.w > 0 { // other one already acquired lock. m.mu.Unlock() return false } m.r++ // m.rwmu.RLock() never blocks m.rwmu.RLock() m.mu.Unlock() return true } // RUnlock unlocks m. func (m *TRWMutex) RUnlock() { m.mu.Lock() m.r-- m.rwmu.RUnlock() m.mu.Unlock() }
package com.andyanika.translator.repository.remote.di.koin import core.interfaces.RemoteRepository import com.andyanika.translator.repository.remote.ApiVariants import com.andyanika.translator.repository.remote.BuildConfig import com.andyanika.translator.repository.remote.stub.StubRemoteRepository import com.andyanika.translator.repository.remote.yandex.YandexApi import com.andyanika.translator.repository.remote.yandex.YandexModelsAdapter import com.andyanika.translator.repository.remote.yandex.YandexRemoteRepository import com.andyanika.translator.repository.remote.yandex.YandexTranslationParamsBuilder import com.google.gson.FieldNamingPolicy import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.core.qualifier.named import org.koin.dsl.bind import org.koin.dsl.module import org.koin.dsl.single import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit private const val NETWORK_READ_TIMEOUT = 5 private const val NETWORK_WRITE_TIMEOUT = 5 private const val NETWORK_CONNECT_TIMEOUT = 15 private const val URL = "https://translate.yandex.net/api/v1.5/tr.json/" val networkModule = module { single<OkHttpClient> { val builder = OkHttpClient.Builder() .readTimeout(NETWORK_READ_TIMEOUT.toLong(), TimeUnit.SECONDS) .writeTimeout(NETWORK_WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS) .connectTimeout(NETWORK_CONNECT_TIMEOUT.toLong(), TimeUnit.SECONDS) if (BuildConfig.DEBUG) { builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) } builder.build() } single { GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create() } single<YandexTranslationParamsBuilder>() single<YandexModelsAdapter>() single<YandexApi> { Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(get())) .baseUrl(URL) .client(get()) .build() .create(YandexApi::class.java) } // region api variants single<YandexRemoteRepository>(named<ApiVariants.Yandex>()) bind RemoteRepository::class single(named<ApiVariants.Stub>()) { StubRemoteRepository } bind RemoteRepository::class // provided by default: single<RemoteRepository> { get(named<ApiVariants.Stub>()) } // endregion }
@extends('layouts.master') @section('answer') <div class=""> <span>réponse : </span><h2>{{$question->answer}}</h2> <p class="wiki">{{$question->wiki}}</p> <p>catégorie : {{$question->category->title}}</p> </div> @stop
namespace DesignMode.AdapterPattern { public class Mp4Player:IAdvancedMediaPlayer { public string playVlc(string fileName) { return ""; } public string playMp4(string fileName) { return "Playing mp4 file. Name: " + fileName; } } }
import { flow } from "lodash"; import { onGet, string, fields, withFields, withProps } from "@webiny/commodo"; import { validation } from "@webiny/validation"; import { Context as CommodoContext } from "@webiny/api-plugin-commodo-db-proxy/types"; import { Context as I18NContext } from "@webiny/api-i18n/types"; import onGetI18NValues from "./onGetI18NValues"; export type I18NString = { context: CommodoContext & I18NContext; [key: string]: any; }; export default ({ context: { i18n, commodo }, ...rest }: I18NString) => { const { id } = commodo.fields; return fields({ ...rest, value: {}, instanceOf: flow( withFields({ values: onGet(value => onGetI18NValues(value, i18n))( fields({ list: true, value: [], instanceOf: withFields({ locale: id({ validation: validation.create("required") }), value: string() })() }) ) }), withProps({ get value() { const locale = i18n.getLocale(); const value = this.values.find(value => value.locale === locale.id); return value ? value.value : ""; } }) )() }); };
import { ICanComponentProps } from '../CanComponent/ICanComponentProps'; export interface IIconProps extends ICanComponentProps { height: number; image: any; name: string; refreshRate: number; width: number; };
package example; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; import scala.Tuple2; import java.util.Arrays; public final class Top10WordAnalyzer { public static void main(String[] args) { JavaSparkContext sc = new JavaSparkContext(new SparkConf().setAppName("Top10")); sc.textFile(args[0]).map(line -> line.replaceAll("[^A-Za-z]+", " ")) .map(String::toLowerCase) .flatMap(line -> Arrays.asList(line.split("\\s+")).iterator()) .mapToPair(word -> new Tuple2<>(word, 1L)) .reduceByKey((x, y) -> x + y) .collect() .stream() .sorted((t1, t2) -> t2._2.compareTo(t1._2)) .map(tuple -> tuple._1() + ": " + tuple._2()) .limit(10) .forEach(System.out::println); sc.stop(); } }
INSERT INTO Quiz.USER (id, email, score) VALUES (7, 'dsa', 0); INSERT INTO Quiz.USER (id, email, score) VALUES (8, 'Manuel', 10); INSERT INTO Quiz.USER (id, email, score) VALUES (9, 'Denis', 15); INSERT INTO Quiz.USER (id, email, score) VALUES (10, 'Grig', 20); INSERT INTO Quiz.USER (id, email, score) VALUES (11, 'dsa', 0); INSERT INTO Quiz.USER (id, email, score) VALUES (12, 'Iulian', 0); INSERT INTO Quiz.USER (id, email, score) VALUES (13, 'Grenadier', 15); INSERT INTO Quiz.USER (id, email, score) VALUES (14, 'dev', 10); INSERT INTO Quiz.USER (id, email, score) VALUES (15, 'sergiu.abrudean@evozon.com', 20); INSERT INTO Quiz.USER (id, email, score) VALUES (16, 'sergiu.abrudean@evozon.com', 20); INSERT INTO Quiz.USER (id, email, score) VALUES (17, 'sergiu.abrudean@evozon.com', 20);
package com.mentatlabs.nsa package javac trait JavacVersions { val `1.4` = JavacVersion(1, 4) val `1.5` = JavacVersion(1, 5) val `1.6` = JavacVersion(1, 6) val `1.7` = JavacVersion(1, 7) val `1.8` = JavacVersion(1, 8) val `1.9` = JavacVersion(1, 9) }
CREATE Procedure [dbo].[usp_deleteEmptyRole] -- Add the parameters for the stored procedure here @RoleName nvarchar(50) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; SELECT LoginID FROM Users INNER JOIN Permissions ON Users.UserID = Permissions.UserID INNER JOIN Roles ON Permissions.RoleID = Roles.RoleID WHERE (Roles.Role = @RoleName) IF @@ROWCOUNT = 0 BEGIN UPDATE Roles SET Inactive = 1 WHERE (Role = @RoleName) AND (Inactive = 0) END END
# encoding: utf-8 class Train::Transports::SSH class CiscoIOSConnection < BaseConnection class BadEnablePassword < Train::TransportError; end def initialize(options) super(options) logger.level = Logger::INFO # Extract options to avoid passing them in to `Net::SSH.start` later @host = options.delete(:host) @user = options.delete(:user) @port = options.delete(:port) @enable_password = options.delete(:enable_password) # Use all options left that are not `nil` for `Net::SSH.start` later @ssh_options = options.reject { |_key, value| value.nil? } @prompt = /^\S+[>#]\r\n.*$/ end def uri "ssh://#{@user}@#{@host}:#{@port}" end def unique_identifier result = run_command_via_connection('show version | include Processor') result.stdout.split(' ')[-1] end private def establish_connection logger.debug("[SSH] opening connection to #{self}") Net::SSH.start(@host, @user, @ssh_options) end def session return @session unless @session.nil? @session = open_channel(establish_connection) # Escalate privilege to enable mode if password is given if @enable_password # This verifies we are not in privileged exec mode before running the # enable command. Otherwise, the password will be in history. if run_command_via_connection('show privilege').stdout.split[-1] != '15' run_command_via_connection("enable\r\n#{@enable_password}") end end # Prevent `--MORE--` by removing terminal length limit run_command_via_connection('terminal length 0') @session end def run_command_via_connection(cmd) # Ensure buffer is empty before sending data @buf = '' logger.debug("[SSH] Running `#{cmd}` on #{self}") session.send_data(cmd + "\r\n") logger.debug('[SSH] waiting for prompt') until @buf =~ @prompt raise BadEnablePassword if @buf =~ /Bad secrets/ session.connection.process(0) end # Save the buffer and clear it for the next command output = @buf.dup @buf = '' format_result(format_output(output, cmd)) end ERROR_MATCHERS = [ 'Bad IP address', 'Incomplete command', 'Invalid input detected', 'Unrecognized host', ].freeze # IOS commands do not have an exit code so we must compare the command # output with partial segments of known errors. Then, we return a # `CommandResult` with arguments in the correct position based on the # result. def format_result(result) if ERROR_MATCHERS.none? { |e| result.include?(e) } CommandResult.new(result, '', 0) else CommandResult.new('', result, 1) end end # The buffer (@buf) contains all data sent/received on the SSH channel so # we need to format the data to match what we would expect from Train def format_output(output, cmd) leading_prompt = /(\r\n|^)\S+[>#]/ command_string = /#{Regexp.quote(cmd)}\r\n/ trailing_prompt = /\S+[>#](\r\n|$)/ trailing_line_endings = /(\r\n)+$/ output .sub(leading_prompt, '') .sub(command_string, '') .gsub(trailing_prompt, '') .gsub(trailing_line_endings, '') end # Create an SSH channel that writes to @buf when data is received def open_channel(ssh) logger.debug("[SSH] opening SSH channel to #{self}") ssh.open_channel do |ch| ch.on_data do |_, data| @buf += data end ch.send_channel_request('shell') do |_, success| raise 'Failed to open SSH shell' unless success logger.debug('[SSH] shell opened') end end end end end
/** * */ package hudson.plugins.starteam; import hudson.model.AbstractBuild; import hudson.scm.ChangeLogParser; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.xml.sax.SAXException; /** * ChangeLogParser implementation for the StarTeam SCM. * * @author Eric D. Broyles * @version 1.0 */ public class StarTeamChangeLogParser extends ChangeLogParser { /** * {@inheritDoc} */ @Override public ChangeLogSet<? extends Entry> parse(AbstractBuild build, File changelogFile) throws IOException, SAXException { return parse0(build, new FileInputStream(changelogFile), changelogFile.getAbsolutePath()); } /** * Parses the change log stream and returns a Perforce change log set. * * @param aBuild * the build for the change log * @param aChangeLogStream * input stream containing the change log * @return the change log set */ public static StarTeamChangeLogSet parse(AbstractBuild aBuild, InputStream aChangeLogStream) throws IOException, SAXException { return parse0(aBuild, aChangeLogStream, null); } private static final ThreadLocal<SimpleDateFormat> TIME_FORMATTER = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); }; }; @SuppressWarnings("unchecked") private static StarTeamChangeLogSet parse0(AbstractBuild aBuild, InputStream aChangeLogStream, String filePath) throws IOException, SAXException { ArrayList<StarTeamChangeLogEntry> changeLogEntries = new ArrayList<StarTeamChangeLogEntry>(); SAXReader reader = new SAXReader(); Document changeDoc = null; StarTeamChangeLogSet changeLogSet = new StarTeamChangeLogSet(aBuild, changeLogEntries); try { changeDoc = reader.read(aChangeLogStream); Node historyNode = changeDoc.selectSingleNode("/changelog"); if (historyNode == null) { return changeLogSet; } List<Node> entries = historyNode.selectNodes("entry"); if (entries == null) { return changeLogSet; } for (Node node : entries) { StarTeamChangeLogEntry change = new StarTeamChangeLogEntry(); if (node.selectSingleNode("fileName") != null) { change .setFileName(node.selectSingleNode("fileName").getStringValue()); } if (node.selectSingleNode("revisionNumber") != null) { change.setRevisionNumber(Integer.parseInt((node .selectSingleNode("revisionNumber").getStringValue()))); } if (node.selectSingleNode("date") != null) { change.setDate(TIME_FORMATTER.get().parse( node.selectSingleNode("date").getStringValue())); } if (node.selectSingleNode("message") != null) { change.setMsg(node.selectSingleNode("message").getStringValue()); } if (node.selectSingleNode("user") != null) { change.setUsername(node.selectSingleNode("user").getStringValue()); } if (node.selectSingleNode("changeType") != null) { change.setChangeType(node.selectSingleNode("changeType") .getStringValue()); } change.setParent(changeLogSet); // Assign Parent changeLogEntries.add(change); } } catch (Exception e) { throw new IOException("Failed to parse changelog file" + (filePath != null ? filePath : "") + ": " + e.getMessage(), e); } return changeLogSet; } }
package main import "fmt" func main() { fmt.Println(monkeyTrouble(true, false)); } /** *if both monkeys are smiling then we are in trouble *if both are not smiling then we are also in trouble **/ func monkeyTrouble(aSmile, bSmile bool) bool { if ((aSmile && bSmile) || (!aSmile && !bSmile)) { return true; } return false; }
// // Created by zhougang on 2019/6/6. // #ifndef ANDROID_DRAW_H #define ANDROID_DRAW_H #include <stdint.h> typedef struct SpiceRect { int32_t left; int32_t top; int32_t right; int32_t bottom; } SpiceRect; #endif //ANDROID_DRAW_H
// notice.dart // see_app // // Created by JohnnyB0Y on 2020/5/16. // Copyright © 2020 JohnnyB0Y. All rights reserved. // import 'model.dart'; abstract class NoticeObservable { observedNotice(Notice notice, NoticeCenter noticeCenter); } /// 通告 class Notice { final String name; final dynamic context; final ReactModel? rm; Notice({required this.name, this.context, this.rm}); } class Observation { /// 订阅通知的名称 final String name; /// 发送与接收通知之间约定的暗号 final dynamic cipher; Observation({required this.name, required this.cipher}); } /// 观察者模型 class Observer { final String? name; final dynamic cipher; final NoticeObservable observer; Observer({required this.observer, this.name, this.cipher}); } /// 通告中心 class NoticeCenter { NoticeCenter(); // 单例 factory NoticeCenter.defaultCenter() { if (_instance == null) { _instance = NoticeCenter(); } return _instance!; } static NoticeCenter? _instance; final Map<String, List<Observer>> observers = Map(); /// 添加观察者 /// observer实现NoticeObservable协议的观察者 /// forName 通知名称 /// cipher 通知发送方和接收方约定的暗号,对上了才可收到通知 bool addObserver(NoticeObservable observer, String forName, [cipher]) { // 取出观察者列表 List<Observer>? list = observers[forName]; if (list == null) { list = []; observers[forName] = list; } else { // 排除重复 for (var om in list) { if (observer == om.observer) { return false; } } } // 添加观察者 Observer om = Observer(observer: observer ,name: forName, cipher: cipher); list.add(om); return true; } /// 发出自定义通知 /// notice 当你想自定义发送数据时使用 /// cipher 通知发送方和接收方的暗号,对上了才可收到通知 postNotice(Notice notice, String forName, [cipher]) { List<Observer>? list = observers[forName]; if (list == null || list.isEmpty) { return; } for (int i = 0; i<list.length; i++) { Observer om = list[i]; if (om.cipher == cipher) { // 通知 om.observer.observedNotice(notice, this); } } } postNoticeForName(String name, dynamic context, ReactModel rm, [cipher]) { var notice = Notice(name: name, context: context, rm: rm); postNotice(notice, name, cipher); } /// 移除通知 /// observer 观察者 /// forName 通知名称 removeObserver(NoticeObservable observer, String forName) { List<Observer> list = observers[forName] ?? []; int index = -1; for (int i = 0; i<list.length; i++) { if (list[i].observer == observer) { index = i; break; } } if (index != -1) { list.removeAt(index); } } removeAllObservers() { observers.clear(); } } class ObservedDefaultNoticeCenter { final List<Observation> observations; final Function(Notice notice) observedNotice; ObservedDefaultNoticeCenter({required this.observations, required this.observedNotice}); }
require "test_helper" require "set" class QueryTest < UnitTestCase def assert_query(expect, *args) test_ids = expect.first.is_a?(Integer) expect = expect.to_a unless expect.respond_to?(:map!) query = Query.lookup(*args) actual = test_ids ? query.result_ids : query.results msg = "Query results are wrong. SQL is:\n" + query.last_query if test_ids assert_equal(expect.sort, actual.sort, msg) else assert_obj_list_equal(expect.sort_by(&:id), actual.sort_by(&:id), msg) end type = args[0].t.sub(/um$/, "(um|a)") assert_match(/#{type}|Advanced Search|(Lower|Higher) Taxa/, query.title) assert(!query.title.include?("[:"), "Title contains undefined localizations: <#{query.title}>") end def clean(str) str.gsub(/\s+/, " ").strip end ############################################################################## def test_basic assert_raises(NameError) { Query.lookup(:BogusModel) } assert_raises(NameError) { Query.lookup(:Name, :bogus) } query = Query.lookup(:Observation) assert(query.record.new_record?) assert_equal("Observation", query.model.to_s) assert_equal(:all, query.flavor) query2 = Query.lookup_and_save(:Observation) assert(!query2.record.new_record?) assert_equal(query, query2) assert_equal(query2, Query.safe_find(query2.id)) assert_nil(Query.safe_find(0)) updated_at = query2.record.updated_at assert_equal(0, query2.record.access_count) query3 = Query.lookup(:Observation) assert_equal(query2.serialize, query3.serialize) assert_equal(updated_at.to_s, query3.record.updated_at.to_s) assert_equal(0, query3.record.access_count) end def test_validate_params @fungi = names(:fungi) assert_raises(RuntimeError) { Query.lookup(:Name, :all, xxx: true) } assert_raises(RuntimeError) { Query.lookup(:Name, :all, by: [1, 2, 3]) } assert_raises(RuntimeError) { Query.lookup(:Name, :all, by: true) } assert_equal("id", Query.lookup(:Name, :all, by: :id).params[:by]) assert_equal( :either, Query.lookup(:Name, :all, misspellings: :either).params[:misspellings] ) assert_equal( :either, Query.lookup(:Name, :all, misspellings: "either").params[:misspellings] ) assert_raises(RuntimeError) do Query.lookup(:Name, :all, misspellings: "bogus") end assert_raises(RuntimeError) do Query.lookup(:Name, :all, misspellings: true) end assert_raises(RuntimeError) { Query.lookup(:Name, :all, misspellings: 123) } assert_raises(RuntimeError) { Query.lookup(:Image, :by_user) } assert_raises(RuntimeError) { Query.lookup(:Image, :by_user, user: :bogus) } assert_raises(RuntimeError) { Query.lookup(:Image, :by_user, user: "rolf") } assert_raises(RuntimeError) { Query.lookup(:Image, :by_user, user: @fungi) } assert_equal(rolf.id, Query.lookup(:Image, :by_user, user: rolf).params[:user]) assert_equal(rolf.id, Query.lookup(:Image, :by_user, user: rolf.id).params[:user]) assert_equal(rolf.id, Query.lookup(:Image, :by_user, user: rolf.id.to_s). params[:user]) assert_raises(RuntimeError) { Query.lookup(:User, :in_set) } # Oops, :in_set query is generic, # doesn't know to require Name instances here. # assert_raises(RuntimeError) { Query.lookup(:Name, :in_set, ids: rolf) } assert_raises(RuntimeError) { Query.lookup(:Name, :in_set, ids: "one") } assert_raises(RuntimeError) { Query.lookup(:Name, :in_set, ids: "1,2,3") } assert_equal([], Query.lookup(:User, :in_set, ids: []).params[:ids]) assert_equal([rolf.id], Query.lookup(:User, :in_set, ids: rolf.id).params[:ids]) assert_equal([names(:fungi).id], Query.lookup(:Name, :in_set, ids: names(:fungi).id.to_s).params[:ids]) assert_equal([rolf.id, mary.id], Query.lookup(:User, :in_set, ids: [rolf.id, mary.id]).params[:ids]) assert_equal([1, 2], Query.lookup(:User, :in_set, ids: %w[1 2]).params[:ids]) assert_equal([rolf.id, mary.id], Query.lookup(:User, :in_set, ids: [rolf.id.to_s, mary.id.to_s]).params[:ids]) assert_equal([rolf.id], Query.lookup(:User, :in_set, ids: rolf).params[:ids]) assert_equal([rolf.id, mary.id], Query.lookup(:User, :in_set, ids: [rolf, mary]).params[:ids]) assert_equal([rolf.id, mary.id, junk.id], Query.lookup(:User, :in_set, ids: [rolf, mary.id, junk.id.to_s]).params[:ids]) assert_raises(RuntimeError) { Query.lookup(:Name, :pattern_search) } assert_raises(RuntimeError) do Query.lookup(:Name, :pattern_search, pattern: true) end assert_raises(RuntimeError) do Query.lookup(:Name, :pattern_search, pattern: [1, 2, 3]) end assert_raises(RuntimeError) do Query.lookup(:Name, :pattern_search, pattern: rolf) end assert_equal("123", Query.lookup(:Name, :pattern_search, pattern: 123). params[:pattern]) assert_equal("rolf", Query.lookup(:Name, :pattern_search, pattern: "rolf"). params[:pattern]) assert_equal("rolf", Query.lookup(:Name, :pattern_search, pattern: :rolf). params[:pattern]) assert_raises(RuntimeError) { Query.lookup(:Name, :of_children) } assert_nil(Query.lookup(:Name, :of_children, name: @fungi).params[:all]) assert_equal(false, Query.lookup(:Name, :of_children, name: @fungi, all: false). params[:all]) assert_equal(false, Query.lookup(:Name, :of_children, name: @fungi, all: "false"). params[:all]) assert_equal(false, Query.lookup(:Name, :of_children, name: @fungi, all: 0). params[:all]) assert_equal(false, Query.lookup(:Name, :of_children, name: @fungi, all: :no). params[:all]) assert_equal(true, Query.lookup(:Name, :of_children, name: @fungi, all: true). params[:all]) assert_equal(true, Query.lookup(:Name, :of_children, name: @fungi, all: "true"). params[:all]) assert_equal(true, Query.lookup(:Name, :of_children, name: @fungi, all: 1). params[:all]) assert_equal(true, Query.lookup(:Name, :of_children, name: @fungi, all: :yes). params[:all]) assert_raises(RuntimeError) do Query.lookup(:Name, :of_children, name: @fungi, all: [123]) end assert_raises(RuntimeError) do Query.lookup(:Name, :of_children, name: @fungi, all: "bogus") end assert_raises(RuntimeError) do Query.lookup(:Name, :of_children, name: @fungi, all: rolf) end assert_equal(["table"], Query.lookup(:Name, :all, join: :table).params[:join]) assert_equal(%w[table1 table2], Query.lookup(:Name, :all, join: %i[table1 table2]). params[:join]) assert_equal(["table"], Query.lookup(:Name, :all, tables: :table).params[:tables]) assert_equal(%w[table1 table2], Query.lookup(:Name, :all, tables: %i[table1 table2]). params[:tables]) assert_equal(["foo = bar"], Query.lookup(:Name, :all, where: "foo = bar").params[:where]) assert_equal(["foo = bar", "id in (1,2,3)"], Query.lookup(:Name, :all, where: ["foo = bar", "id in (1,2,3)"]). params[:where]) assert_equal("names.id", Query.lookup(:Name, :all, group: "names.id").params[:group]) assert_equal("id DESC", Query.lookup(:Name, :all, order: "id DESC").params[:order]) assert_raises(RuntimeError) { Query.lookup(:Name, :all, group: %w[1 2]) } assert_raises(RuntimeError) { Query.lookup(:Name, :all, order: %w[1 2]) } end def test_initialize_helpers query = Query.lookup(:Name) assert_equal("4,1,2", query.clean_id_set(["4", 1, 4, 2, 4, 1, 2])) assert_equal("-1", query.clean_id_set([])) assert_equal("blah", query.clean_pattern("blah")) assert_equal("foo bar", query.clean_pattern("foo bar")) assert_equal('\\"foo\\%bar\\"', query.clean_pattern('"foo%bar"')) assert_equal('one\\\\two', query.clean_pattern('one\\two')) assert_equal("foo%bar", query.clean_pattern("foo*bar")) assert_nil(query.and_clause) assert_equal("one", query.and_clause("one")) assert_equal("(one AND two)", query.and_clause("one", "two")) assert_equal("(one AND two AND three)", query.and_clause("one", "two", "three")) assert_nil(query.or_clause) assert_equal("one", query.or_clause("one")) assert_equal("(one OR two)", query.or_clause("one", "two")) assert_equal("(one OR two OR three)", query.or_clause("one", "two", "three")) end def test_google_parse query = Query.lookup(:Name) assert_equal([["blah"]], query.google_parse("blah").goods) assert_equal([%w[foo bar]], query.google_parse("foo OR bar").goods) assert_equal([["one"], %w[foo bar], ["two"]], query.google_parse("one foo OR bar two").goods) assert_equal([["one"], ["foo", "bar", "quoted phrase", "-gar"], ["two"]], query.google_parse( 'one foo OR bar OR "quoted phrase" OR -gar two' ).goods) assert_equal([], query.google_parse("-bad").goods) assert_equal(["bad"], query.google_parse("-bad").bads) assert_equal(["bad"], query.google_parse("foo -bad bar").bads) assert_equal(["bad wolf"], query.google_parse('foo -"bad wolf" bar').bads) assert_equal(["bad wolf", "foo", "bar"], query.google_parse('-"bad wolf" -foo -bar').bads) end def test_google_conditions query = Query.lookup(:Name) assert_equal( ["x LIKE '%blah%'"], query.google_conditions(query.google_parse("blah"), "x") ) assert_equal( ["x NOT LIKE '%bad%'"], query.google_conditions(query.google_parse("-bad"), "x") ) assert_equal( ["x LIKE '%foo%' AND x NOT LIKE '%bad%'"], query.google_conditions(query.google_parse("foo -bad"), "x") ) assert_equal( ["x LIKE '%foo%' AND x LIKE '%bar%' AND x NOT LIKE '%bad%'"], query.google_conditions(query.google_parse("foo bar -bad"), "x") ) assert_equal( ["(x LIKE '%foo%' OR x LIKE '%bar%') AND x NOT LIKE '%bad%'"], query.google_conditions(query.google_parse("foo OR bar -bad"), "x") ) assert_equal( ["(x LIKE '%foo%' OR x LIKE '%bar%' OR x LIKE '%any%thing%') " \ "AND x LIKE '%surprise!%' AND x NOT LIKE '%bad%' " \ "AND x NOT LIKE '%lost boys%'"], query.google_conditions( query.google_parse( 'foo OR bar OR "any*thing" -bad surprise! -"lost boys"' ), "x" ) ) end def test_lookup assert_equal(0, QueryRecord.count) q1 = Query.lookup_and_save(:Observation) assert_equal(1, QueryRecord.count) Query.lookup_and_save(:Observation, :pattern_search, pattern: "blah") assert_equal(2, QueryRecord.count) # New because params are different from q1. q3 = Query.lookup_and_save(:Observation, :all, by: :id) assert_equal(3, QueryRecord.count) # Not new because flavor is explicitly defaulted before validate. q4 = Query.lookup_and_save(:Observation, :all) assert_equal(3, QueryRecord.count) assert_equal(q1, q4, QueryRecord.count) # Ditto default flavor. q5 = Query.lookup_and_save(:Observation, :all, by: :id) assert_equal(3, QueryRecord.count) assert_equal(q3, q5, QueryRecord.count) # New pattern is new query. Query.lookup_and_save(:Observation, :pattern_search, pattern: "new blah") assert_equal(4, QueryRecord.count) # Old pattern but new order. Query.lookup_and_save(:Observation, :pattern_search, pattern: "blah", by: :date) assert_equal(5, QueryRecord.count) # Identical, even though :by is explicitly set in one. Query.lookup_and_save(:Observation, :pattern_search, pattern: "blah") assert_equal(5, QueryRecord.count) # Identical query, but new query because order given explicitly. Order is # not given default until query is initialized, thus default not stored in # params, so lookup doesn't know about it. Query.lookup_and_save(:Observation, :all, by: :date) assert_equal(6, QueryRecord.count) # Just a sanity check. Query.lookup_and_save(:Name) assert_equal(7, QueryRecord.count) end # rubocop:disable Metrics/LineLength # def test_cleanup # # Due to the modified => updated_at change explicitly setting updated_at # # this way doesn't work. However, I don't really understand what this test # # does or if it's important, since the time zone comment is definitely # # inaccurate. - NJW # # # It is supposed to verify that QueryRecord.cleanup culls old unused # # queries. This is called automatically periodicallt when clients create # # or lookup new queries. - JPH # # # This avoids any possible difference in time zone between mysql and you. # # (This should be obsolete, but timezone handling is tested elsewhere.) # now = DateTime.parse(QueryRecord.connection.select_value("SELECT NOW()") # .to_s) # # s11 = QueryRecord.new(access_count: 0, updated_at: now - 1.minute) # s12 = QueryRecord.new(access_count: 0, updated_at: now - 6.hour + 1.minute) # s13 = QueryRecord.new(access_count: 0, updated_at: now - 6.hour - 1.minute) # s14 = QueryRecord.new(access_count: 0, updated_at: now - 1.day + 1.minute) # s15 = QueryRecord.new(access_count: 0, updated_at: now - 1.day - 1.minute) # s21 = QueryRecord.new(access_count: 1, updated_at: now - 1.minute) # s22 = QueryRecord.new(access_count: 1, updated_at: now - 6.hour + 1.minute) # s23 = QueryRecord.new(access_count: 1, updated_at: now - 6.hour - 1.minute) # s24 = QueryRecord.new(access_count: 1, updated_at: now - 1.day + 1.minute) # s25 = QueryRecord.new(access_count: 1, updated_at: now - 1.day - 1.minute) # # assert_save(s11) # assert_save(s12) # assert_save(s13) # assert_save(s14) # assert_save(s15) # assert_save(s21) # assert_save(s22) # assert_save(s23) # assert_save(s24) # assert_save(s25) # # s11 = s11.id # s12 = s12.id # s13 = s13.id # s14 = s14.id # s15 = s15.id # s21 = s21.id # s22 = s22.id # s23 = s23.id # s24 = s24.id # s25 = s25.id # # assert_state_exists(s11) # assert_state_exists(s12) # assert_state_exists(s13) # assert_state_exists(s14) # assert_state_exists(s15) # assert_state_exists(s21) # assert_state_exists(s22) # assert_state_exists(s23) # assert_state_exists(s24) # assert_state_exists(s25) # # QueryRecord.cleanup # # assert_state_exists(s11) # assert_state_exists(s12) # assert_state_not_exists(s13) # assert_state_not_exists(s14) # assert_state_not_exists(s15) # assert_state_exists(s21) # assert_state_exists(s22) # assert_state_exists(s23) # assert_state_exists(s24) # assert_state_not_exists(s25) # end # # def assert_state_exists(id) # assert(!id.nil? && QueryRecord.find(id)) # end # # def assert_state_not_exists(id) # assert_raises(ActiveRecord::RecordNotFound) { QueryRecord.find(id) } # end # rubocop:enable Metrics/LineLength ############################################################################## # # :section: Query Mechanics # ############################################################################## def test_query query = Query.lookup(:Name) query.initialize_query assert_equal([], query.join) assert_equal([], query.tables) assert_equal(1, query.where.length) # misspellings assert_equal("", query.group) assert_not_equal("", query.order) # whatever the default order is # Clean it out completely. query.where = [] query.order = "" assert_equal( "SELECT DISTINCT names.id FROM `names`", clean(query.query) ) assert_equal( "SELECT foo bar FROM `names`", clean(query.query(select: "foo bar")) ) assert_equal( "SELECT DISTINCT names.id FROM `names` " \ "JOIN `rss_logs` ON names.rss_log_id = rss_logs.id", clean(query.query(join: :rss_logs)) ) assert_equal( "SELECT DISTINCT names.id FROM `names` " \ "JOIN `observations` ON observations.name_id = names.id "\ "JOIN `rss_logs` ON observations.rss_log_id = rss_logs.id", clean(query.query(join: { observations: :rss_logs })) ) assert_equal( "SELECT DISTINCT names.id FROM `names`, `rss_logs`", clean(query.query(tables: :rss_logs)) ) assert_equal( "SELECT DISTINCT names.id FROM `names`, `images`, `comments`", clean(query.query(tables: %i[images comments])) ) assert_equal( "SELECT DISTINCT names.id FROM `names` WHERE shazam!", clean(query.query(where: "shazam!")) ) assert_equal( "SELECT DISTINCT names.id FROM `names` WHERE foo AND bar", clean(query.query(where: %w[foo bar])) ) assert_equal( "SELECT DISTINCT names.id FROM `names` WHERE foo AND bar", clean(query.query(where: %w[foo bar])) ) assert_equal( "SELECT DISTINCT names.id FROM `names` GROUP BY blah blah blah", clean(query.query(group: "blah blah blah")) ) assert_equal( "SELECT DISTINCT names.id FROM `names` ORDER BY foo, bar, names.id DESC", # (tacks on 'id DESC' for disambiguation) clean(query.query(order: "foo, bar")) ) assert_equal( "SELECT DISTINCT names.id FROM `names` ORDER BY comments.id ASC", clean(query.query(order: "comments.id ASC")) # (sees id in there already) ) assert_equal( "SELECT DISTINCT names.id FROM `names` LIMIT 10", clean(query.query(limit: 10)) ) # Now, all together... assert_equal( "SELECT names.* FROM `names`, `images` " \ "JOIN `observations` ON observations.name_id = names.id " \ "JOIN `users` ON names.reviewer_id = users.id " \ "WHERE one = two AND foo LIKE bar " \ "GROUP BY blah.id ORDER BY names.id ASC LIMIT 10, 10", clean(query.query(select: "names.*", join: %i[observations users.reviewer], tables: :images, where: ["one = two", "foo LIKE bar"], group: "blah.id", order: "names.id ASC", limit: "10, 10")) ) end def test_join_conditions query = Query.lookup(:Name) query.initialize_query query.where = [] query.order = "" # Joins should include these: # names => observations => locations # names => observations => comments # names => observations => images_observations => images # names => users (as reviewer) sql = query.query( join: [ { observations: [ :locations, :comments, { images_observations: :images } ] }, :'users.reviewer' ] ) assert_match(/names.reviewer_id = users.id/, sql) assert_match(/observations.name_id = names.id/, sql) assert_match(/observations.location_id = locations.id/, sql) assert_match(/comments.target_id = observations.id/, sql) assert_match(/comments.target_type = (['"])Observation\1/, sql) assert_match(/images_observations.observation_id = observations.id/, sql) assert_match(/images_observations.image_id = images.id/, sql) end def test_reverse_order query = Query.lookup(:Name) assert_equal("", query.reverse_order("")) assert_equal("id ASC", query.reverse_order("id DESC")) assert_equal("one ASC, two DESC, three ASC", query.reverse_order("one DESC, two ASC, three DESC")) assert_equal( 'IF(users.name = "", users.login, users.name) DESC, users.id ASC', query.reverse_order( 'IF(users.name = "", users.login, users.name) ASC, users.id DESC' ) ) end def test_join_direction # RssLog can join to Observation two ways. When joining from observations # to rss_logs, use observations.rss_log_id = rss_logs.id. query = Query.lookup(:Observation) query.initialize_query query.join << :rss_logs assert_match(/observations.rss_log_id = rss_logs.id/, query.query) # And use rss_logs.observation_id = observations.id the other way. query = Query.lookup(:RssLog) query.initialize_query query.join << :observations assert_match(/rss_logs.observation_id = observations.id/, query.query) end def test_low_levels query = Query.lookup(:Name, :all, misspellings: :either, by: :id) @fungi = names(:fungi) @agaricus = names(:agaricus) num = Name.count num_agaricus = Name.where('text_name LIKE "Agaricus%"').count assert_equal(num, query.select_count) assert_equal(num, query.select_count(limit: 10)) # limits no. of counts!! assert_equal(num_agaricus, query.select_count(where: 'text_name LIKE "Agaricus%"')) assert_equal(Name.first.id, query.select_value) assert_equal(Name.offset(10).first.id, query.select_value(limit: "10, 10")) # 11th id assert_equal(Name.last.id, query.select_value(order: :reverse)) # last id assert_equal(Name.first.text_name, query.select_value(select: "text_name").to_s) assert_equal(Name.all.map { |name| name.id.to_s }, query.select_values.map(&:to_s)) assert_equal([names(:agaricus_campestris).id.to_s, names(:agaricus).id.to_s, names(:agaricus_campestrus).id.to_s, names(:agaricus_campestras).id.to_s, names(:agaricus_campestros).id.to_s].sort, query.select_values(where: 'text_name LIKE "Agaricus%"'). map(&:to_s).sort) agaricus = query.select_values(select: "text_name", where: 'text_name LIKE "Agaricus%"'). map(&:to_s) assert_equal(num_agaricus, agaricus.uniq.length) assert_equal(num_agaricus, agaricus.select { |x| x[0, 8] == "Agaricus" }.count) assert_equal(Name.all.map { |x| [x.id] }, query.select_rows) assert_equal(Name.all.map { |x| { "id" => x.id } }, query.select_all) assert_equal({ "id" => Name.first.id }, query.select_one) assert_equal([Name.first], query.find_by_sql(limit: 1)) assert_equal(@agaricus.children.sort_by(&:id), query.find_by_sql(where: 'text_name LIKE "Agaricus %"')) end def test_tables_used query = Query.lookup(:Observation, :all, by: :id) assert_equal([:observations], query.tables_used) query = Query.lookup(:Observation, :all, by: :name) assert_equal(%i[names observations], query.tables_used) query = Query.lookup(:Image, :all, by: :name) assert_equal(%i[images images_observations names observations], query.tables_used) assert_equal(true, query.uses_table?(:images)) assert_equal(true, query.uses_table?(:images_observations)) assert_equal(true, query.uses_table?(:names)) assert_equal(true, query.uses_table?(:observations)) assert_equal(false, query.uses_table?(:comments)) end def test_results query = Query.lookup(:User, :all, by: :id) assert_equal( Set.new, Set.new([rolf.id, mary.id, junk.id, dick.id, katrina.id, roy.id]) - query.result_ids ) assert_equal(roy.location_format, :scientific) assert_equal( Set.new, Set.new([rolf, mary, junk, dick, katrina, roy]) - query.results ) assert_equal(User.all.find_index(junk), query.index(junk)) assert_equal(User.all.find_index(dick), query.index(dick)) assert_equal(User.all.find_index(mary), query.index(mary)) # Verify that it's getting all this crap from cache. query.result_ids = [rolf.id, junk.id, katrina.id, 100] assert_equal([rolf, junk, katrina], query.results) # Should be able to set it this way, too. query.results = [dick, mary, rolf] assert_equal(3, query.num_results) assert_equal([dick.id, mary.id, rolf.id], query.result_ids) assert_equal([dick, mary, rolf], query.results) assert_equal(1, query.index(mary)) assert_equal(2, query.index(rolf)) end def paginate_test_setup(number, num_per_page) @names = Name.all.order(:id) @pages = MOPaginator.new(number: number, num_per_page: num_per_page) @query = Query.lookup(:Name, :all, misspellings: :either, by: :id) end def paginate_test(number, num_per_page, expected_nths) paginate_test_setup(number, num_per_page) paginate_assertions(number, num_per_page, expected_nths) end # parameters are the ordinals of objects which have been ordered by id # E.g., 1 corresponds to Name.all.order(:id).first def paginate_assertions(number, num_per_page, expected_nths) from_nth = (number - 1) * num_per_page to_nth = from_nth + num_per_page - 1 name_ids = @names.map { |n| n[:id] } assert_equal( expected_nths, @query.paginate_ids(@pages).map { |id| name_ids.index(id) + 1 } ) assert_equal(@names.size, @pages.num_total) assert_equal(@names[from_nth..to_nth], @query.paginate(@pages)) end def test_paginate_start paginate_test(1, 4, [1, 2, 3, 4]) end def test_paginate_middle MO.debugger_flag = true paginate_test(2, 4, [5, 6, 7, 8]) end def paginate_test_letter_setup(number, num_per_page) paginate_test_setup(number, num_per_page) @query.need_letters = "names.text_name" @letters = @names.map { |n| n.text_name[0, 1] }.uniq.sort end def test_paginate_need_letters paginate_test_letter_setup(1, 4) paginate_assertions(1, 4, [1, 2, 3, 4]) assert_equal(@letters, @pages.used_letters.sort) end def test_paginate_ells paginate_test_letter_setup(2, 3) @pages = MOPaginator.new(number: 2, num_per_page: 3, letter: "L") # Make sure we have a bunch of Lactarii, Leptiotas, etc. @ells = @names.select { |n| n.text_name[0, 1] == "L" } assert(@ells.length >= 9) assert_equal(@ells[3..5].map(&:id), @query.paginate_ids(@pages)) assert_equal(@letters, @pages.used_letters.sort) assert_equal(@ells[3..5], @query.paginate(@pages)) end def test_eager_instantiator query = Query.lookup(:Observation) ids = query.result_ids first = query.instantiate([ids[0]]).first assert(!first.images.loaded?) first = query.instantiate([ids[0]], include: :images).first assert(!first.images.loaded?) # Have to test it on a different one, because first is now cached. second = query.instantiate([ids[1]], include: :images).first assert(second.images.loaded?) # Or we can clear out the cache and it will work... query.clear_cache first = query.instantiate([ids[0]], include: :images).first assert(first.images.loaded?) end ############################################################################## # # :section: Sequence Operators # ############################################################################## def test_current query = Query.lookup(:Name) @fungi = names(:fungi) @agaricus = names(:agaricus) @peltigera = names(:peltigera) assert_nil(query.current_id) assert_nil(query.current) query.current_id = @fungi.id assert_equal(@fungi.id, query.current_id) assert_equal(@fungi, query.current) query.current = @agaricus assert_equal(@agaricus.id, query.current_id) assert_equal(@agaricus, query.current) query.current = @peltigera.id assert_equal(@peltigera.id, query.current_id) assert_equal(@peltigera, query.current) end def test_next_and_prev query = Query.lookup(:Name, :all, misspellings: :either, by: :id) @names = Name.all query.current = @names[2] assert_equal(query, query.prev) assert_equal(@names[1].id, query.current_id) assert_equal(query, query.prev) assert_equal(@names[0].id, query.current_id) assert_nil(query.prev) assert_equal(@names[0].id, query.current_id) assert_equal(query, query.next) assert_equal(@names[1].id, query.current_id) assert_equal(query, query.next) assert_equal(@names[2].id, query.current_id) assert_equal(query, query.last) assert_equal(@names[-1].id, query.current_id) assert_equal(query, query.last) assert_equal(@names[-1].id, query.current_id) assert_nil(query.next) assert_equal(@names[-1].id, query.current_id) assert_equal(query, query.first) assert_equal(@names[0].id, query.current_id) assert_equal(query, query.first) assert_equal(@names[0].id, query.current_id) query.reset assert_equal(@names[2].id, query.current_id) end def test_inner_outer outer = Query.lookup_and_save(:Observation, :all, by: :id) q = Query.lookup( :Image, :inside_observation, outer: outer, observation: observations(:minimal_unknown_obs).id, by: :id ) assert_equal([], q.result_ids) # Because autogenerated fixture ids order is unpredictable, track which # observations and images go with each inner query. inners_details = [ { obs: observations(:detailed_unknown_obs).id, imgs: [images(:in_situ_image).id, images(:turned_over_image).id] }, { obs: observations(:coprinus_comatus_obs).id, imgs: [images(:connected_coprinus_comatus_image).id] }, { obs: observations(:agaricus_campestris_obs).id, imgs: [images(:agaricus_campestris_image).id] }, { obs: observations(:peltigera_obs).id, imgs: [images(:peltigera_image).id] } ] inner1 = Query.lookup_and_save( :Image, :inside_observation, outer: outer, observation: inners_details.first[:obs], by: :id ) assert_equal(inners_details.first[:imgs], inner1.result_ids) inner2 = Query.lookup_and_save( :Image, :inside_observation, outer: outer, observation: inners_details.second[:obs], by: :id ) assert_equal(inners_details.second[:imgs], inner2.result_ids) inner3 = Query.lookup_and_save( :Image, :inside_observation, outer: outer, observation: inners_details.third[:obs], by: :id ) assert_equal(inners_details.third[:imgs], inner3.result_ids) inner4 = Query.lookup_and_save( :Image, :inside_observation, outer: outer, observation: inners_details.fourth[:obs], by: :id ) assert_equal(inners_details.fourth[:imgs], inner4.result_ids) # Now that inner queries are defined, add them to inners_details inners_details.first[:inner] = inner1 inners_details.second[:inner] = inner2 inners_details.third[:inner] = inner3 inners_details.fourth[:inner] = inner4 # calculate some other details inners_query_ids = inners_details.map { |n| n[:inner].record.id }.sort inners_obs_ids = inners_details.map { |n| n[:obs] }.sort assert(inner1.has_outer?) # it's been tweaked but still same id assert_equal(outer.record.id, inner1.outer.record.id) assert_equal(inners_details.first[:obs], inner1.get_outer_current_id) assert_equal(inners_details.second[:obs], inner2.get_outer_current_id) assert_equal(inners_details.third[:obs], inner3.get_outer_current_id) assert_equal(inners_details.fourth[:obs], inner4.get_outer_current_id) # inner1: Images in Observations # inner1's outer: all Observations by id # inner1.outer should be all Observations with images, sorted by id q = inner1.outer results = q.result_ids assert_equal( obs_with_imgs_ids, results, "inner1.outer missing images #{obs_with_imgs_ids - results}\n" \ "query was #{q.last_query}\n" ) # Following tests if results contain all inners_outer_obs_ids -- in order. # (Works because each is: (a) sorted, and (b) has no duplicate entries. missing_obs_ids = inners_obs_ids - results assert_empty(missing_obs_ids, "inner1.outer results missing observations #{missing_obs_ids}") q.current_id = results[1] assert_equal(q, q.first) assert_equal(results[0], q.current_id) assert_equal(q, q.last) assert_equal(results[-1], q.current_id) ##### Test next and previous on the query results. ##### # (Results are images of all obs with images, not just inner1 - inner4.) non_uniq_imgs_with_obs_count = Image.joins(:observations).size # Get 1st result, which is 1st image of 1st imaged observation obs = obs_with_imgs_ids.first imgs = Observation.find(obs).images.order("id ASC").map(&:id) img = imgs.first qr = QueryRecord.where( ["description REGEXP ?", "observation=##{obs}"] ).first q = Query.deserialize(qr.description) q_first_query = q.first q_last_query = q.last q.current_id = img assert_nil(q.prev, "Result for obs #{obs}, image #{q.current_id} is not the first") ### Use next to step forward through the other results, ### # checking for the right query, observation, and image (non_uniq_imgs_with_obs_count - 1).times do obs, imgs, img = next_result(obs, imgs, img) q = q.next # Are we looking at the right obs and query? if inners_obs_ids.include?(obs) assert( inners_query_ids.include?(q.id), "A Query for Observation #{obs} should be in inner1 - inner4" ) assert_equal( inners_details.find { |n| n[:obs] == obs }[:inner].id, q.id, "Query #{q.id} is not the inner for Observation #{obs}" ) else refute(inners_query_ids.include?(q.id), "Observation #{obs} should not be in inner1 - inner4") end # And at the right image? assert_equal(img, q.current_id) end # Are we at the last result? assert_equal(q_last_query, q, "Current query is not the last") assert_nil(q.last.next, "Failed to get to last result") assert_equal(obs_with_imgs_ids.last, obs, "Last result not for the last Observation with an Image") assert_equal(Observation.find(obs).images.last.id, img, "Last result not for last Image in last Observation result") ### Use prev to step back through the results, ### # again checking for the right query, observation, and image (non_uniq_imgs_with_obs_count - 1).times do obs, imgs, img = prev_result(obs, imgs, img) q = q.prev # Are we looking at the right obs and query? if inners_obs_ids.include?(obs) assert(inners_query_ids.include?(q.id), "A Query for Observation #{obs} should be in inner1 - inner4") assert_equal( inners_details.find { |n| n[:obs] == obs }[:inner].id, q.id, "Query #{q.id} is not the inner for Observation #{obs}" ) else refute(inners_query_ids.include?(q.id), "Observation #{obs} should not be in inner1 - inner4") end # And at the right image? assert_equal(img, q.current_id) end # Are we back at the first result? assert_equal(q_first_query, q, "Current query is not the first") assert_nil(q.prev, "Failed to step back to first result") assert_equal(obs_with_imgs_ids.first, obs, "First result not for the first Observation with an Image") assert_equal(Observation.find(obs).images.first.id, img, "First result not for first Image in an Observation") # Can we get to first query directly from an intermediate query? q = q.next assert_equal(q_first_query, q.first) end def obs_with_imgs_ids Observation.distinct.joins(:images).order(:id).map(&:id) end # Return next result's: observation.id, image.id list, image.id # If no more results, then returned obs will be nil # For previoua result, call with inc = -1 # usage: obs, imgs, img = next_result(obs, imgs, img) # obs, imgs, img = next_result(obs, imgs, img, -1) def next_result(obs, imgs, img, inc = 1) next_idx = imgs.index(img) + inc # if there's another img for this obs, just get it if next_idx.between?(0, imgs.count - 1) img = imgs[next_idx] # else get the next obs, if there is one elsif (obs = obs_with_imgs_ids[obs_with_imgs_ids.index(obs) + inc]) # get its list of image ids imgs = Observation.find(obs).images.order("id ASC").map(&:id) # get first or last image in the list # depending on whether were going forward or back through results img = inc > 0 ? imgs.first : imgs.last end [obs, imgs, img] end def prev_result(obs, imgs, img) next_result(obs, imgs, img, -1) end ############################################################################## # # :section: Test Coerce # ############################################################################## def test_basic_coerce assert_equal(0, QueryRecord.count) q1 = Query.lookup_and_save(:Observation, :pattern_search, pattern: "search") assert_equal(1, QueryRecord.count) # Trvial coercion: any flavor from a model to the same model. q2 = q1.coerce(:Observation) assert_equal(q1, q2) assert_equal(1, QueryRecord.count) # No search is coercable to RssLog (yet). q3 = q1.coerce(:RssLog) assert_nil(q3) assert_equal(1, QueryRecord.count) end # rubocop:disable Naming/VariableName # RuboCop gives false positives here def test_observation_image_coercion # Several observation queries can be turned into image queries. q1a = Query.lookup_and_save(:Observation, :all, by: :id) q2a = Query.lookup_and_save(:Observation, :by_user, user: mary.id) q3a = Query.lookup_and_save( :Observation, :in_species_list, species_list: species_lists(:first_species_list).id ) q4a = Query.lookup_and_save(:Observation, :of_name, name: names(:conocybe_filaris).id) q5a = Query.lookup_and_save(:Observation, :in_set, ids: [ observations(:detailed_unknown_obs).id, observations(:agaricus_campestris_obs).id, observations(:agaricus_campestras_obs).id ]) q6a = Query.lookup_and_save(:Observation, :pattern_search, pattern: '"somewhere else"') q7a = Query.lookup_and_save(:Observation, :advanced_search, location: "glendale") q8a = Query.lookup_and_save(:Observation, :at_location, location: locations(:burbank)) q9a = Query.lookup_and_save(:Observation, :at_where, location: "california") qAa = Query.lookup_and_save(:Observation, :of_children, name: names(:conocybe_filaris).id) assert_equal(10, QueryRecord.count) # Try coercing them all. assert(q1b = q1a.coerce(:Image)) assert(q2b = q2a.coerce(:Image)) assert(q3b = q3a.coerce(:Image)) assert(q4b = q4a.coerce(:Image)) assert(q5b = q5a.coerce(:Image)) assert(q6b = q6a.coerce(:Image)) assert(q7b = q7a.coerce(:Image)) assert(q8b = q8a.coerce(:Image)) assert(q9b = q9a.coerce(:Image)) assert(qAb = qAa.coerce(:Image)) # They should all be new records assert(q1b.record.new_record?) assert_save(q1b) assert(q2b.record.new_record?) assert_save(q2b) assert(q3b.record.new_record?) assert_save(q3b) assert(q4b.record.new_record?) assert_save(q4b) assert(q5b.record.new_record?) assert_save(q5b) assert(q6b.record.new_record?) assert_save(q6b) assert(q7b.record.new_record?) assert_save(q7b) assert(q8b.record.new_record?) assert_save(q8b) assert(q9b.record.new_record?) assert_save(q9b) assert(qAb.record.new_record?) assert_save(qAb) # Check their descriptions. assert_equal("Image", q1b.model.to_s) assert_equal("Image", q2b.model.to_s) assert_equal("Image", q3b.model.to_s) assert_equal("Image", q4b.model.to_s) assert_equal("Image", q5b.model.to_s) assert_equal("Image", q6b.model.to_s) assert_equal("Image", q7b.model.to_s) assert_equal("Image", q8b.model.to_s) assert_equal("Image", q9b.model.to_s) assert_equal("Image", qAb.model.to_s) assert_equal(:with_observations, q1b.flavor) assert_equal(:with_observations_by_user, q2b.flavor) assert_equal(:with_observations_in_species_list, q3b.flavor) assert_equal(:with_observations_of_name, q4b.flavor) assert_equal(:with_observations_in_set, q5b.flavor) assert_equal(:with_observations_in_set, q6b.flavor) assert_equal(:with_observations_in_set, q7b.flavor) assert_equal(:with_observations_at_location, q8b.flavor) assert_equal(:with_observations_at_where, q9b.flavor) assert_equal(:with_observations_of_children, qAb.flavor) # Now try to coerce them back to Observation. assert(q1c = q1b.coerce(:Observation)) assert(q2c = q2b.coerce(:Observation)) assert(q3c = q3b.coerce(:Observation)) assert(q4c = q4b.coerce(:Observation)) assert(q5c = q5b.coerce(:Observation)) assert(q6c = q6b.coerce(:Observation)) assert(q7c = q7b.coerce(:Observation)) assert(q8c = q8b.coerce(:Observation)) assert(q9c = q9b.coerce(:Observation)) assert(qAc = qAb.coerce(:Observation)) # Only some should be new. assert(!q1c.record.new_record?) assert_equal(q1a, q1c) assert(!q2c.record.new_record?) assert_equal(q2a, q2c) assert(!q3c.record.new_record?) assert_equal(q3a, q3c) assert(!q4c.record.new_record?) assert_equal(q4a, q4c) assert(!q5c.record.new_record?) assert_equal(q5a, q5c) assert(q6c.record.new_record?) # (converted to in_set) assert(q7c.record.new_record?) # (converted to in_set) assert(!q8c.record.new_record?) assert_equal(q8a, q8c) assert(!q9c.record.new_record?) assert_equal(q9a, q9c) assert(!qAc.record.new_record?) assert_equal(qAa, qAc) end def test_observation_location_coercion # Almost any query on observations should be mappable, i.e. coercable into # a query on those observations' locations. q1a = Query.lookup_and_save(:Observation, :all, by: :id) q2a = Query.lookup_and_save(:Observation, :by_user, user: mary.id) q3a = Query.lookup_and_save( :Observation, :in_species_list, species_list: species_lists(:first_species_list).id ) q4a = Query.lookup_and_save(:Observation, :of_name, name: names(:conocybe_filaris).id) q5a = Query.lookup_and_save(:Observation, :in_set, ids: [observations(:detailed_unknown_obs).id, observations(:agaricus_campestris_obs).id, observations(:agaricus_campestras_obs).id]) q6a = Query.lookup_and_save(:Observation, :pattern_search, pattern: '"somewhere else"') q7a = Query.lookup_and_save(:Observation, :advanced_search, location: "glendale") q8a = Query.lookup_and_save(:Observation, :at_location, location: locations(:burbank)) q9a = Query.lookup_and_save(:Observation, :at_where, location: "california") qAa = Query.lookup_and_save(:Observation, :of_children, name: names(:conocybe_filaris).id) assert_equal(10, QueryRecord.count) # Try coercing them all. assert(q1b = q1a.coerce(:Location)) assert(q2b = q2a.coerce(:Location)) assert(q3b = q3a.coerce(:Location)) assert(q4b = q4a.coerce(:Location)) assert(q5b = q5a.coerce(:Location)) assert(q6b = q6a.coerce(:Location)) assert(q7b = q7a.coerce(:Location)) assert(q8b = q8a.coerce(:Location)) assert_nil(q9a.coerce(:Location)) assert(qAb = qAa.coerce(:Location)) # They should all be new records assert(q1b.record.new_record?) assert_save(q1b) assert(q2b.record.new_record?) assert_save(q2b) assert(q3b.record.new_record?) assert_save(q3b) assert(q4b.record.new_record?) assert_save(q4b) assert(q5b.record.new_record?) assert_save(q5b) assert(q6b.record.new_record?) assert_save(q6b) assert(q7b.record.new_record?) assert_save(q7b) assert(q8b.record.new_record?) assert_save(q8b) assert(qAb.record.new_record?) assert_save(qAb) # Check their descriptions. assert_equal("Location", q1b.model.to_s) assert_equal("Location", q2b.model.to_s) assert_equal("Location", q3b.model.to_s) assert_equal("Location", q4b.model.to_s) assert_equal("Location", q5b.model.to_s) assert_equal("Location", q6b.model.to_s) assert_equal("Location", q7b.model.to_s) assert_equal("Location", q8b.model.to_s) assert_equal("Location", qAb.model.to_s) assert_equal(:with_observations, q1b.flavor) assert_equal(:with_observations_by_user, q2b.flavor) assert_equal(:with_observations_in_species_list, q3b.flavor) assert_equal(:with_observations_of_name, q4b.flavor) assert_equal(:with_observations_in_set, q5b.flavor) assert_equal(:with_observations_in_set, q6b.flavor) assert_equal(:with_observations_in_set, q7b.flavor) assert_equal(:in_set, q8b.flavor) assert_equal(:with_observations_of_children, qAb.flavor) assert_equal({ old_by: "id" }, q1b.params) assert_equal({ user: mary.id }, q2b.params) assert_equal({ species_list: species_lists(:first_species_list).id }, q3b.params) assert_equal({ name: names(:conocybe_filaris).id }, q4b.params) assert_equal({ ids: [locations(:burbank).id] }, q8b.params) assert_equal({ name: names(:conocybe_filaris).id }, qAb.params) assert_equal([observations(:detailed_unknown_obs).id, observations(:agaricus_campestris_obs).id, observations(:agaricus_campestras_obs).id], q5b.params[:ids]) assert_equal([observations(:strobilurus_diminutivus_obs).id, observations(:agaricus_campestros_obs).id, observations(:agaricus_campestras_obs).id, observations(:agaricus_campestrus_obs).id], q6b.params[:ids]) assert_equal([observations(:coprinus_comatus_obs).id], q7b.params[:ids]) assert_match(/Observations.*Matching.*somewhere.*else/, q6b.params[:old_title]) assert_match(/Advanced.*Search/, q7b.params[:old_title]) assert_equal(1, q5b.params.keys.length) assert_equal(2, q6b.params.keys.length) assert_equal(2, q7b.params.keys.length) # Now try to coerce them back to Observation. assert(q1c = q1b.coerce(:Observation)) assert(q2c = q2b.coerce(:Observation)) assert(q3c = q3b.coerce(:Observation)) assert(q4c = q4b.coerce(:Observation)) assert(q5c = q5b.coerce(:Observation)) assert(q6c = q6b.coerce(:Observation)) assert(q7c = q7b.coerce(:Observation)) assert_nil(q8b.coerce(:Observation)) assert(qAc = qAb.coerce(:Observation)) # Only some should be new. assert(!q1c.record.new_record?) assert_equal(q1a, q1c) assert(!q2c.record.new_record?) assert_equal(q2a, q2c) assert(!q3c.record.new_record?) assert_equal(q3a, q3c) assert(!q4c.record.new_record?) assert_equal(q4a, q4c) assert(!q5c.record.new_record?) assert_equal(q5a, q5c) assert(q6c.record.new_record?) # (converted to in_set) assert(q7c.record.new_record?) # (converted to in_set) assert(!qAc.record.new_record?) assert_equal(qAa, qAc) end def test_observation_name_coercion # Several observation queries can be turned into name queries. q1a = Query.lookup_and_save(:Observation, :all, by: :id) q2a = Query.lookup_and_save(:Observation, :by_user, user: mary.id) q3a = Query.lookup_and_save( :Observation, :in_species_list, species_list: species_lists(:first_species_list).id ) q4a = Query.lookup_and_save(:Observation, :of_name, name: names(:conocybe_filaris).id) q5a = Query.lookup_and_save(:Observation, :in_set, ids: [ observations(:detailed_unknown_obs).id, observations(:agaricus_campestris_obs).id, observations(:agaricus_campestras_obs).id ]) q6a = Query.lookup_and_save(:Observation, :pattern_search, pattern: '"somewhere else"') q7a = Query.lookup_and_save(:Observation, :advanced_search, location: "glendale") q8a = Query.lookup_and_save(:Observation, :at_location, location: locations(:burbank)) q9a = Query.lookup_and_save(:Observation, :at_where, location: "california") assert_equal(9, QueryRecord.count) # Try coercing them all. assert(q1b = q1a.coerce(:Name)) assert(q2b = q2a.coerce(:Name)) assert(q3b = q3a.coerce(:Name)) assert_nil(q4a.coerce(:Name)) assert(q5b = q5a.coerce(:Name)) assert(q6b = q6a.coerce(:Name)) assert(q7b = q7a.coerce(:Name)) assert(q8b = q8a.coerce(:Name)) assert(q9b = q9a.coerce(:Name)) # They should all be new records assert(q1b.record.new_record?) assert_save(q1b) assert(q2b.record.new_record?) assert_save(q2b) assert(q3b.record.new_record?) assert_save(q3b) assert(q5b.record.new_record?) assert_save(q5b) assert(q6b.record.new_record?) assert_save(q6b) assert(q7b.record.new_record?) assert_save(q7b) assert(q8b.record.new_record?) assert_save(q8b) assert(q9b.record.new_record?) assert_save(q9b) # Check their descriptions. assert_equal("Name", q1b.model.to_s) assert_equal("Name", q2b.model.to_s) assert_equal("Name", q3b.model.to_s) assert_equal("Name", q5b.model.to_s) assert_equal("Name", q6b.model.to_s) assert_equal("Name", q7b.model.to_s) assert_equal("Name", q8b.model.to_s) assert_equal("Name", q9b.model.to_s) assert_equal(:with_observations, q1b.flavor) assert_equal(:with_observations_by_user, q2b.flavor) assert_equal(:with_observations_in_species_list, q3b.flavor) assert_equal(:with_observations_in_set, q5b.flavor) assert_equal(:with_observations_in_set, q6b.flavor) assert_equal(:with_observations_in_set, q7b.flavor) assert_equal(:with_observations_at_location, q8b.flavor) assert_equal(:with_observations_at_where, q9b.flavor) # Now try to coerce them back to Observation. assert(q1c = q1b.coerce(:Observation)) assert(q2c = q2b.coerce(:Observation)) assert(q3c = q3b.coerce(:Observation)) assert(q5c = q5b.coerce(:Observation)) assert(q6c = q6b.coerce(:Observation)) assert(q7c = q7b.coerce(:Observation)) assert(q8c = q8b.coerce(:Observation)) assert(q9c = q9b.coerce(:Observation)) # Only some should be new. assert(!q1c.record.new_record?) assert_equal(q1a, q1c) assert(!q2c.record.new_record?) assert_equal(q2a, q2c) assert(!q3c.record.new_record?) assert_equal(q3a, q3c) assert(!q5c.record.new_record?) assert_equal(q5a, q5c) assert(q6c.record.new_record?) # (converted to in_set) assert(q7c.record.new_record?) # (converted to in_set) assert(!q8c.record.new_record?) assert_equal(q8a, q8c) assert(!q9c.record.new_record?) assert_equal(q9a, q9c) end def test_description_coercion # Several description queries can be turned into name queries and back. q1a = Query.lookup_and_save(:NameDescription, :all) q2a = Query.lookup_and_save(:NameDescription, :by_author, user: rolf.id) q3a = Query.lookup_and_save(:NameDescription, :by_editor, user: rolf.id) q4a = Query.lookup_and_save(:NameDescription, :by_user, user: rolf.id) assert_equal(4, QueryRecord.count) # Try coercing them into name queries. assert(q1b = q1a.coerce(:Name)) assert(q2b = q2a.coerce(:Name)) assert(q3b = q3a.coerce(:Name)) assert(q4b = q4a.coerce(:Name)) # They should all be new records assert(q1b.record.new_record?) assert_save(q1b) assert(q2b.record.new_record?) assert_save(q2b) assert(q3b.record.new_record?) assert_save(q3b) assert(q4b.record.new_record?) assert_save(q4b) # Make sure they're right. assert_equal("Name", q1b.model.to_s) assert_equal("Name", q2b.model.to_s) assert_equal("Name", q3b.model.to_s) assert_equal("Name", q4b.model.to_s) assert_equal(:with_descriptions, q1b.flavor) assert_equal(:with_descriptions_by_author, q2b.flavor) assert_equal(:with_descriptions_by_editor, q3b.flavor) assert_equal(:with_descriptions_by_user, q4b.flavor) assert_equal(rolf.id, q2b.params[:user]) assert_equal(rolf.id, q3b.params[:user]) assert_equal(rolf.id, q4b.params[:user]) # Try coercing them back. assert(q1c = q1b.coerce(:NameDescription)) assert(q2c = q2b.coerce(:NameDescription)) assert(q3c = q3b.coerce(:NameDescription)) assert(q4c = q4b.coerce(:NameDescription)) # None should be new records assert_equal(q1a, q1c) assert_equal(q2a, q2c) assert_equal(q3a, q3c) assert_equal(q4a, q4c) end # rubocop:enable Naming/VariableName def test_rss_log_coercion # The site index's default RssLog query should be coercable into queries on # the member classes, so that when a user clicks on an RssLog entry in the # main index and goes to a show_object page, they can continue to browse # results via prev/next. (Actually, it handles this better now, # recognizing in next/prev_object that the query is on RssLog and can skip # between controllers while browsing the results, but still worth testing # this old mechanism, just in case.) # This is the default query for list_rss_logs. q1 = Query.lookup_and_save(:RssLog) # Click through to an item (User is expected to fail). q2 = q1.coerce(:Location) q3 = q1.coerce(:Name) q4 = q1.coerce(:Observation) q5 = q1.coerce(:SpeciesList) q6 = q1.coerce(:User) # Make sure they succeeded and created new queries. assert(q2) assert(q2.record.new_record?) assert_save(q2) assert(q3) assert(q3.record.new_record?) assert_save(q3) assert(q4) assert(q4.record.new_record?) assert_save(q4) assert(q5) assert(q5.record.new_record?) assert_save(q5) assert_nil(q6) # Make sure they are correct. assert_equal("Location", q2.model.to_s) assert_equal("Name", q3.model.to_s) assert_equal("Observation", q4.model.to_s) assert_equal("SpeciesList", q5.model.to_s) assert_equal(:by_rss_log, q2.flavor) assert_equal(:by_rss_log, q3.flavor) assert_equal(:by_rss_log, q4.flavor) assert_equal(:by_rss_log, q5.flavor) assert_equal({}, q2.params) assert_equal({}, q3.params) assert_equal({}, q4.params) assert_equal({}, q5.params) end def test_coercable assert(Query.lookup(:Observation, :all, by: :id).coercable?(:Image)) refute(Query.lookup(:Herbarium, :all, by: :id).coercable?(:Project)) end ############################################################################## # # :section: Test Query Results # ############################################################################## def test_article_all assert_query(Article.all, :Article, :all) end def test_article_by_rss_log assert_query(Article.joins(:rss_log).distinct, :Article, :by_rss_log) end def test_article_in_set assert_query([articles(:premier_article).id], :Article, :in_set, ids: [articles(:premier_article).id]) assert_query([], :Article, :in_set, ids: []) end def test_article_pattern_search assert_query([], :Article, :pattern_search, pattern: "no article has this") # title assert_query(Article.where("title LIKE '%premier_article%' OR body LIKE '%premier_article%'"), :Article, :pattern_search, pattern: "premier_article") # body assert_query(Article.where("title LIKE '%Body of Article%' OR body LIKE '%Body of Article%'"), :Article, :pattern_search, pattern: "Body of Article") assert_query(Article.all, :Article, :pattern_search, pattern: "") end def test_collection_number_all expect = CollectionNumber.all.sort_by(&:format_name) assert_query(expect, :CollectionNumber, :all) end def test_collection_number_for_observation obs = observations(:detailed_unknown_obs) expect = obs.collection_numbers.sort_by(&:format_name) assert_query(expect, :CollectionNumber, :for_observation, observation: obs.id) end def test_collection_number_pattern_search expect = CollectionNumber. where("name like '%Singer%' or number like '%Singer%'"). sort_by(&:format_name) assert_query(expect, :CollectionNumber, :pattern_search, pattern: "Singer") expect = CollectionNumber. where("name like '%123a%' or number like '%123a%'"). sort_by(&:format_name) assert_query(expect, :CollectionNumber, :pattern_search, pattern: "123a") end def test_comment_all expect = Comment.all.reverse assert_query(expect, :Comment, :all) end def test_comment_by_user expect = Comment.where(user_id: mary.id).reverse assert_query(expect, :Comment, :by_user, user: mary) end def test_comment_for_target obs = observations(:minimal_unknown_obs) expect = Comment.where(target_id: obs.id) assert_query(expect, :Comment, :for_target, target: obs, type: "Observation") end def test_comment_for_user expect = Comment.all.select { |c| c.target.user == mary } assert_query(expect, :Comment, :for_user, user: mary) assert_query([], :Comment, :for_user, user: rolf) end def test_comment_in_set assert_query([comments(:detailed_unknown_obs_comment).id, comments(:minimal_unknown_obs_comment_1).id], :Comment, :in_set, ids: [comments(:detailed_unknown_obs_comment).id, comments(:minimal_unknown_obs_comment_1).id]) end def test_comment_pattern_search expect = [ comments(:minimal_unknown_obs_comment_1), comments(:detailed_unknown_obs_comment) ] assert_query(expect, :Comment, :pattern_search, pattern: "unknown") end def test_external_link_all assert_query(ExternalLink.all.sort_by(&:url), :ExternalLink, :all) assert_query(ExternalLink.where(user: users(:mary)).sort_by(&:url), :ExternalLink, :all, users: users(:mary)) assert_query([], :ExternalLink, :all, users: users(:dick)) obs = observations(:coprinus_comatus_obs) assert_query(obs.external_links.sort_by(&:url), :ExternalLink, :all, observations: obs) obs = observations(:detailed_unknown_obs) assert_query([], :ExternalLink, :all, observations: obs) site = external_sites(:mycoportal) assert_query(site.external_links.sort_by(&:url), :ExternalLink, :all, external_sites: site) site = external_sites(:inaturalist) assert_query(site.external_links.sort_by(&:url), :ExternalLink, :all, external_sites: site) assert_query(site.external_links.sort_by(&:url), :ExternalLink, :all, url: "iNaturalist") end def test_herbarium_all expect = Herbarium.all.sort_by(&:name) assert_query(expect, :Herbarium, :all) end def test_herbarium_in_set expect = [ herbaria(:dick_herbarium), herbaria(:nybg_herbarium) ] assert_query(expect, :Herbarium, :in_set, ids: expect) end def test_herbarium_pattern_search expect = [herbaria(:nybg_herbarium)] assert_query(expect, :Herbarium, :pattern_search, pattern: "awesome") end def test_image_advanced_search assert_query([images(:agaricus_campestris_image).id], :Image, :advanced_search, name: "Agaricus") assert_query(Image.joins(observations: :location). where(observations: { location: locations(:burbank) }). where(observations: { is_collection_location: true }), :Image, :advanced_search, location: "burbank") assert_query([images(:connected_coprinus_comatus_image).id], :Image, :advanced_search, location: "glendale") assert_query(Image.includes(:observations). where(observations: { user: mary }), :Image, :advanced_search, user: "mary") assert_query([images(:turned_over_image).id, images(:in_situ_image).id], :Image, :advanced_search, content: "little") assert_query([images(:connected_coprinus_comatus_image).id], :Image, :advanced_search, content: "fruiting") assert_query([], :Image, :advanced_search, name: "agaricus", location: "glendale") assert_query([images(:agaricus_campestris_image).id], :Image, :advanced_search, name: "agaricus", location: "burbank") assert_query([images(:turned_over_image).id, images(:in_situ_image).id], :Image, :advanced_search, content: "little", location: "burbank") end def test_herbarium_record_all expect = HerbariumRecord.all.sort_by(&:herbarium_label) assert_query(expect, :HerbariumRecord, :all) end def test_herbarium_record_for_observation obs = observations(:coprinus_comatus_obs) expect = obs.herbarium_records.sort_by(&:herbarium_label) assert_query(expect, :HerbariumRecord, :for_observation, observation: obs.id) end def test_herbarium_record_in_herbarium nybg = herbaria(:nybg_herbarium) expect = nybg.herbarium_records.sort_by(&:herbarium_label) assert_query(expect, :HerbariumRecord, :in_herbarium, herbarium: nybg.id) end def test_image_all expect = Image.all.reverse assert_query(expect, :Image, :all) end def test_image_by_user expect = Image.where(user_id: rolf.id).reverse assert_query(expect, :Image, :by_user, user: rolf) expect = Image.where(user_id: mary.id).reverse assert_query(expect, :Image, :by_user, user: mary) expect = Image.where(user_id: dick.id).reverse assert_query(expect, :Image, :by_user, user: dick) end def test_image_in_set assert_query([images(:turned_over_image).id, images(:agaricus_campestris_image).id, images(:disconnected_coprinus_comatus_image).id], :Image, :in_set, ids: [images(:turned_over_image).id, images(:agaricus_campestris_image).id, images(:disconnected_coprinus_comatus_image).id]) end def test_image_inside_observation obs = observations(:detailed_unknown_obs) assert_equal(2, obs.images.length) expect = obs.images.sort_by(&:id) assert_query(expect, :Image, :inside_observation, observation: obs, outer: 1) # (outer is only used by prev/next) obs = observations(:minimal_unknown_obs) assert_equal(0, obs.images.length) assert_query(obs.images, :Image, :inside_observation, observation: obs, outer: 1) # (outer is only used by prev/next) end def test_image_for_project assert_query( projects(:bolete_project).images.sort, :Image, :for_project, project: projects(:bolete_project), by: :id ) assert_query([], :Image, :for_project, project: projects(:empty_project)) end def test_image_pattern_search assert_query([images(:agaricus_campestris_image).id], :Image, :pattern_search, pattern: "agaricus") # name assert_query([images(:agaricus_campestris_image).id, images(:connected_coprinus_comatus_image).id, images(:turned_over_image).id, images(:in_situ_image).id], :Image, :pattern_search, pattern: "bob dob") # copyright holder assert_query( [images(:in_situ_image).id], :Image, :pattern_search, pattern: "looked gorilla OR original" # notes ) assert_query([images(:agaricus_campestris_image).id, images(:connected_coprinus_comatus_image).id], :Image, :pattern_search, pattern: "notes some") # notes assert_query( [images(:turned_over_image).id, images(:in_situ_image).id], :Image, :pattern_search, pattern: "dobbs -notes" # (c), not notes ) assert_query([images(:in_situ_image).id], :Image, :pattern_search, pattern: "DSCN8835") # original filename end def test_image_with_observations assert_query(Image.includes(:observations). where.not(observations: { thumb_image: nil }), :Image, :with_observations) end def test_image_with_observations_at_location assert_query(Image.joins(observations: :location). where(observations: { location: locations(:burbank) }). where(observations: { is_collection_location: true }), :Image, :with_observations_at_location, location: locations(:burbank).id) assert_query([], :Image, :with_observations_at_location, location: locations(:mitrula_marsh).id) end def test_image_with_observations_at_where assert_query([images(:connected_coprinus_comatus_image).id], :Image, :with_observations_at_where, user_where: "glendale", location: "glendale") assert_query([], :Image, :with_observations_at_where, user_where: "snazzle", location: "snazzle") end def test_image_with_observations_by_user assert_query(Image.joins(:observations). where(observations: { user: rolf }), :Image, :with_observations_by_user, user: rolf) assert_query(Image.joins(:observations). where(observations: { user: mary }), :Image, :with_observations_by_user, user: mary) assert_query([], :Image, :with_observations_by_user, user: users(:zero_user)) end def test_image_with_observations_for_project assert_query([], :Image, :with_observations_for_project, project: projects(:empty_project)) assert_query(observations(:two_img_obs).images, :Image, :with_observations_for_project, project: projects(:two_img_obs_project)) end def test_image_with_observations_in_set assert_query([images(:agaricus_campestris_image).id, images(:turned_over_image).id, images(:in_situ_image).id], :Image, :with_observations_in_set, ids: [observations(:detailed_unknown_obs).id, observations(:agaricus_campestris_obs).id]) assert_query([], :Image, :with_observations_in_set, ids: [observations(:minimal_unknown_obs).id]) end def test_image_with_observations_in_species_list assert_query([images(:turned_over_image).id, images(:in_situ_image).id], :Image, :with_observations_in_species_list, species_list: species_lists(:unknown_species_list).id) assert_query([], :Image, :with_observations_in_species_list, species_list: species_lists(:first_species_list).id) end def test_image_with_observations_of_children assert_query([images(:agaricus_campestris_image).id], :Image, :with_observations_of_children, name: names(:agaricus)) end def test_image_sorted_by_original_name assert_query([images(:turned_over_image).id, images(:connected_coprinus_comatus_image).id, images(:disconnected_coprinus_comatus_image).id, images(:in_situ_image).id, images(:commercial_inquiry_image).id, images(:agaricus_campestris_image).id], :Image, :in_set, ids: [images(:in_situ_image).id, images(:turned_over_image).id, images(:commercial_inquiry_image).id, images(:disconnected_coprinus_comatus_image).id, images(:connected_coprinus_comatus_image).id, images(:agaricus_campestris_image).id], by: :original_name) end def test_image_with_observations_of_name assert_query(Image.joins(:images_observations, :observations). where(observations: { name: names(:fungi) }), :Image, :with_observations_of_name, name: names(:fungi).id) assert_query([images(:connected_coprinus_comatus_image).id], :Image, :with_observations_of_name, name: names(:coprinus_comatus).id) assert_query([images(:agaricus_campestris_image).id], :Image, :with_observations_of_name, name: names(:agaricus_campestris).id) assert_query([], :Image, :with_observations_of_name, name: names(:conocybe_filaris).id) end def test_location_advanced_search assert_query([locations(:burbank).id], :Location, :advanced_search, name: "agaricus") assert_query([], :Location, :advanced_search, name: "coprinus") assert_query([locations(:burbank).id], :Location, :advanced_search, location: "burbank") assert_query([locations(:howarth_park).id, locations(:salt_point).id], :Location, :advanced_search, location: "park") assert_query(Location.joins(observations: :user). where(observations: { user: rolf }).uniq, :Location, :advanced_search, user: "rolf") assert_query(Location.joins(:observations). where(observations: { user: dick }).uniq, :Location, :advanced_search, user: "dick") # content in obs.notes assert_query([locations(:burbank).id], :Location, :advanced_search, content: '"strange place"') # content in Comment assert_query( [locations(:burbank).id], :Location, :advanced_search, content: '"a little of everything"' ) # no search loc.notes assert_query([], :Location, :advanced_search, content: '"play with"') assert_query([locations(:burbank).id], :Location, :advanced_search, name: "agaricus", content: '"lawn"') assert_query([], :Location, :advanced_search, name: "agaricus", content: '"play with"') # from observation and comment for same observation assert_query([locations(:burbank).id], :Location, :advanced_search, content: '"a little of everything" "strange place"') # from different comments, should fail assert_query([], :Location, :advanced_search, content: '"minimal unknown" "complicated"') end def test_location_all expect = Location.all.to_a assert_query(expect, :Location, :all, by: :id) end def test_location_by_user assert_query(Location.where(user: rolf), :Location, :by_user, user: rolf, by: :id) assert_query([], :Location, :by_user, user: users(:zero_user)) end def test_location_by_editor assert_query([], :Location, :by_editor, user: rolf) User.current = mary loc = Location.where.not(user: mary).first loc.display_name = "new name" loc.save assert_query([loc], :Location, :by_editor, user: mary) assert_query([], :Location, :by_editor, user: dick) end def test_location_by_rss_log assert_query(Location.joins(:rss_log).distinct, :Location, :by_rss_log) end def test_location_in_set assert_query([locations(:gualala).id, locations(:albion).id, locations(:burbank).id, locations(:elgin_co).id], :Location, :in_set, ids: [locations(:gualala).id, locations(:albion).id, locations(:burbank).id, locations(:elgin_co).id]) end def test_location_pattern_search expect = Location.all.select { |l| l.display_name =~ /california/i } assert_query(expect, :Location, :pattern_search, pattern: "California", by: :id) assert_query([locations(:elgin_co).id], :Location, :pattern_search, pattern: "Canada") assert_query([], :Location, :pattern_search, pattern: "Canada -Elgin") end def test_location_regexp_search assert_query(Location.where("name REGEXP 'California'"), :Location, :regexp_search, regexp: ".alifornia") end def test_location_with_descriptions assert_query(LocationDescription.all.map(&:location_id).uniq, :Location, :with_descriptions) end def test_location_with_descriptions_by_user assert_query([locations(:albion).id], :Location, :with_descriptions_by_user, user: rolf) assert_query([], :Location, :with_descriptions_by_user, user: mary) end def test_location_with_descriptions_by_author assert_query([locations(:albion).id], :Location, :with_descriptions_by_author, user: rolf) assert_query([], :Location, :with_descriptions_by_author, user: mary) end def test_location_with_descriptions_by_editor User.current = mary desc = location_descriptions(:albion_desc) desc.notes = "blah blah blah" desc.save assert_query([], :Location, :with_descriptions_by_editor, user: rolf) assert_query([locations(:albion).id], :Location, :with_descriptions_by_editor, user: mary) end def test_location_with_descriptions_in_set assert_query([locations(:albion), locations(:no_mushrooms_location)], :Location, :with_descriptions_in_set, ids: [location_descriptions(:albion_desc).id, location_descriptions(:no_mushrooms_location_desc).id]) assert_query([locations(:albion)], :Location, :with_descriptions_in_set, ids: [location_descriptions(:albion_desc).id, rolf.id]) assert_query([], :Location, :with_descriptions_in_set, ids: [rolf.id]) end def test_location_with_observations assert_query(Location.joins(:observations).uniq, :Location, :with_observations) end def test_location_with_observations_by_user assert_query(Location.joins(:observations). where(observations: { user: rolf }).to_a.uniq, :Location, :with_observations_by_user, user: rolf.id) assert_query([], :Location, :with_observations_by_user, user: users(:zero_user)) end def test_location_with_observations_for_project assert_query([], :Location, :with_observations_for_project, project: projects(:empty_project)) assert_query([observations(:collected_at_obs).location], :Location, :with_observations_for_project, project: projects(:obs_collected_and_displayed_project)) end def test_location_with_observations_in_set assert_query([locations(:burbank).id], :Location, :with_observations_in_set, ids: [observations(:minimal_unknown_obs).id]) assert_query([], :Location, :with_observations_in_set, ids: [observations(:coprinus_comatus_obs).id]) end def test_location_with_observations_in_species_list assert_query([locations(:burbank).id], :Location, :with_observations_in_species_list, species_list: species_lists(:unknown_species_list).id) assert_query([], :Location, :with_observations_in_species_list, species_list: species_lists(:first_species_list).id) end def test_location_with_observations_of_children assert_query([locations(:burbank).id], :Location, :with_observations_of_children, name: names(:agaricus)) end def test_location_with_observations_of_name assert_query([locations(:burbank).id], :Location, :with_observations_of_name, name: names(:agaricus_campestris).id) assert_query([], :Location, :with_observations_of_name, name: names(:peltigera).id) end def test_location_description_all all = LocationDescription.all.to_a assert_query(all, :LocationDescription, :all, by: :id) end def test_location_description_by_user assert_query([location_descriptions(:albion_desc).id], :LocationDescription, :by_user, user: rolf) assert_query([], :LocationDescription, :by_user, user: mary) end def test_location_description_by_author loc1, loc2, loc3 = Location.all desc1 = loc1.description ||= LocationDescription.create!(location_id: loc1.id) desc2 = loc2.description ||= LocationDescription.create!(location_id: loc2.id) desc3 = loc3.description ||= LocationDescription.create!(location_id: loc3.id) desc1.add_author(rolf) desc2.add_author(mary) desc3.add_author(rolf) # Using Rails instead of db; don't know how to do it with .joins & .where descs = LocationDescription.all assert_query(descs.find_all { |d| d.authors.include?(rolf) }, :LocationDescription, :by_author, user: rolf, by: :id) assert_query(descs.find_all { |d| d.authors.include?(mary) }, :LocationDescription, :by_author, user: mary) assert_query([], :LocationDescription, :by_author, user: users(:zero_user)) end def test_location_description_by_editor loc1, loc2, loc3 = Location.all desc1 = loc1.description ||= LocationDescription.create!(location_id: loc1.id) desc2 = loc2.description ||= LocationDescription.create!(location_id: loc2.id) desc3 = loc3.description ||= LocationDescription.create!(location_id: loc3.id) desc1.add_editor(rolf) # Fails since he's already an author! desc2.add_editor(mary) desc3.add_editor(rolf) # Using Rails instead of db; don't know how to do it with .joins & .where descs = LocationDescription.all assert_query(descs.find_all { |d| d.editors.include?(rolf) }, :LocationDescription, :by_editor, user: rolf, by: :id) assert_query(descs.find_all { |d| d.editors.include?(mary) }, :LocationDescription, :by_editor, user: mary) assert_query([], :LocationDescription, :by_editor, user: users(:zero_user)) end def test_location_description_in_set assert_query([], :LocationDescription, :in_set, ids: rolf.id) assert_query(LocationDescription.all, :LocationDescription, :in_set, ids: LocationDescription.select(:id).to_a) assert_query([location_descriptions(:albion_desc).id], :LocationDescription, :in_set, ids: [rolf.id, location_descriptions(:albion_desc).id]) end def test_name_advanced_search assert_query([names(:macrocybe_titans).id], :Name, :advanced_search, name: "macrocybe*titans") assert_query([names(:coprinus_comatus).id], :Name, :advanced_search, location: "glendale") # where expect = Name.where("observations.location_id" => locations(:burbank).id). includes(:observations).order(:text_name, :author).to_a assert_query(expect, :Name, :advanced_search, location: "burbank") # location expect = Name.where("observations.user_id" => rolf.id). includes(:observations).order(:text_name, :author).to_a assert_query(expect, :Name, :advanced_search, user: "rolf") assert_query([names(:coprinus_comatus).id], :Name, :advanced_search, content: "second fruiting") # notes assert_query([names(:fungi).id], :Name, :advanced_search, content: '"a little of everything"') # comment end def test_name_all expect = Name.all.order(:sort_name).to_a # SQL does not sort 'Kuhner' and 'Kühner' do_test_name_all(expect) if sql_collates_accents? pair = expect.select { |x| x.text_name == "Lentinellus ursinus" } a = expect.index(pair.first) b = expect.index(pair.last) expect[a], expect[b] = expect[b], expect[a] do_test_name_all(expect) end def do_test_name_all(expect) expect_good = expect.reject(&:is_misspelling?) expect_bad = expect.select(&:is_misspelling?) assert_query(expect_good, :Name, :all) assert_query(expect, :Name, :all, misspellings: :either) assert_query(expect_good, :Name, :all, misspellings: :no) assert_query(expect_bad, :Name, :all, misspellings: :only) end def test_name_by_user assert_query(Name.where(user: mary).where(correct_spelling: nil), :Name, :by_user, user: mary, by: :id) assert_query(Name.where(user: dick).where(correct_spelling: nil), :Name, :by_user, user: dick, by: :id) assert_query(Name.where(user: rolf).where(correct_spelling: nil), :Name, :by_user, user: rolf, by: :id) assert_query([], :Name, :by_user, user: users(:zero_user)) end def test_name_by_editor assert_query([], :Name, :by_editor, user: rolf, by: :id) assert_query([], :Name, :by_editor, user: mary, by: :id) assert_query([names(:peltigera).id], :Name, :by_editor, user: dick, by: :id) end def test_name_by_rss_log assert_query([names(:fungi).id], :Name, :by_rss_log) end def test_name_in_set assert_query([names(:fungi).id, names(:coprinus_comatus).id, names(:conocybe_filaris).id, names(:lepiota_rhacodes).id, names(:lactarius_subalpinus).id], :Name, :in_set, ids: [names(:fungi).id, names(:coprinus_comatus).id, names(:conocybe_filaris).id, names(:lepiota_rhacodes).id, names(:lactarius_subalpinus).id]) end def test_name_of_children expect = Name.where("text_name LIKE 'agaricus %'").order("text_name").to_a expect.reject!(&:is_misspelling?) assert_query(expect, :Name, :of_children, name: names(:agaricus)) end def test_name_of_parents peltigeraceae = names(:peltigeraceae) peltigera = names(:peltigera) assert_query([peltigeraceae], :Name, :of_parents, name: peltigera) fungi = names(:fungi) basidiomycota = names(:basidiomycota) basidiomycetes = names(:basidiomycetes) agaricales = names(:agaricales) agaricaceae = names(:agaricaceae) agaricus = names(:agaricus) agaricus_campestris = names(:agaricus_campestris) assert_query([agaricaceae], :Name, :of_parents, name: agaricus) assert_query([agaricus], :Name, :of_parents, name: agaricus_campestris) assert_query([ fungi, basidiomycota, basidiomycetes, agaricales, agaricaceae, agaricus ], :Name, :of_parents, name: agaricus_campestris, all: "yes") end def test_name_pattern_search assert_query( [], :Name, :pattern_search, pattern: "petigera" # search_name ) assert_query( [names(:petigera).id], :Name, :pattern_search, pattern: "petigera", misspellings: :either ) assert_query( [names(:peltigera).id], :Name, :pattern_search, pattern: "ye auld manual of lichenes" # citation ) assert_query( [names(:agaricus_campestras).id], :Name, :pattern_search, pattern: "prevent me" # description notes ) assert_query( [names(:suillus)], :Name, :pattern_search, pattern: "smell as sweet" # gen_desc ) # Prove pattern search gets hits for description look_alikes assert_query( [names(:peltigera).id], :Name, :pattern_search, pattern: "superficially similar" ) end def test_name_with_descriptions expect = NameDescription.distinct(:name_id).order(:name_id).pluck(:name_id) assert_query(expect, :Name, :with_descriptions, by: :id) end def test_name_with_descriptions_by_user assert_query([names(:agaricus_campestris).id, names(:peltigera).id], :Name, :with_descriptions_by_user, user: mary, by: :id) assert_query([names(:boletus_edulis).id, names(:peltigera).id, names(:suillus).id], :Name, :with_descriptions_by_user, user: dick, by: :id) end def test_name_with_descriptions_by_author assert_query([names(:coprinus_comatus).id, names(:peltigera).id], :Name, :with_descriptions_by_author, user: rolf, by: :id) assert_query([names(:agaricus_campestris).id, names(:peltigera).id], :Name, :with_descriptions_by_author, user: mary, by: :id) assert_query([names(:boletus_edulis).id], :Name, :with_descriptions_by_author, user: dick, by: :id) end def test_name_with_descriptions_by_editor assert_query([names(:coprinus_comatus).id], :Name, :with_descriptions_by_editor, user: rolf) assert_query([names(:coprinus_comatus).id], :Name, :with_descriptions_by_editor, user: mary) assert_query([], :Name, :with_descriptions_by_editor, user: dick) end def test_name_with_descriptions_in_set desc1 = name_descriptions(:peltigera_desc) desc2 = name_descriptions(:peltigera_alt_desc) desc3 = name_descriptions(:draft_boletus_edulis) name1 = names(:peltigera) name2 = names(:boletus_edulis) assert_query([name2, name1], :Name, :with_descriptions_in_set, ids: [desc1, desc2, desc3]) end def test_name_with_observations expect = Observation.select(:name).distinct.pluck(:name_id).sort assert_query(expect, :Name, :with_observations, by: :id) end def test_name_with_observations_at_location assert_query(Name.joins(:observations). where(observations: { location: locations(:burbank) }). distinct, :Name, :with_observations_at_location, location: locations(:burbank)) end def test_name_with_observations_at_where assert_query([names(:coprinus_comatus).id], :Name, :with_observations_at_where, user_where: "glendale", location: "glendale") end def test_name_with_observations_by_user assert_query(Name.joins(:observations). where(observations: { user: rolf }).distinct, :Name, :with_observations_by_user, user: rolf) assert_query(Name.joins(:observations). where(observations: { user: mary }).distinct, :Name, :with_observations_by_user, user: mary) assert_query([], :Name, :with_observations_by_user, user: users(:zero_user)) end def test_name_with_observations_for_project assert_query([], :Name, :with_observations_for_project, project: projects(:empty_project)) assert_query([observations(:two_img_obs).name], :Name, :with_observations_for_project, project: projects(:two_img_obs_project)) end def test_name_with_observations_in_set assert_query([names(:agaricus_campestras).id, names(:agaricus_campestris).id, names(:fungi).id], :Name, :with_observations_in_set, ids: [observations(:detailed_unknown_obs).id, observations(:agaricus_campestris_obs).id, observations(:agaricus_campestras_obs).id]) end def test_name_with_observations_in_species_list assert_query([names(:fungi).id], :Name, :with_observations_in_species_list, species_list: species_lists(:unknown_species_list).id) assert_query([], :Name, :with_observations_in_species_list, species_list: species_lists(:first_species_list).id) end def test_name_description_all all = NameDescription.all.to_a assert_query(all, :NameDescription, :all, by: :id) end def test_name_description_by_user assert_query([name_descriptions(:draft_agaricus_campestris).id, name_descriptions(:peltigera_user_desc).id], :NameDescription, :by_user, user: mary, by: :id) assert_query([name_descriptions(:draft_coprinus_comatus).id, name_descriptions(:draft_lactarius_alpinus).id, name_descriptions(:peltigera_source_desc).id], :NameDescription, :by_user, user: katrina, by: :id) assert_query([], :NameDescription, :by_user, user: junk, by: :id) end def test_name_description_by_author assert_query([name_descriptions(:peltigera_alt_desc).id, name_descriptions(:coprinus_comatus_desc).id], :NameDescription, :by_author, user: rolf, by: :id) assert_query([name_descriptions(:draft_agaricus_campestris).id, name_descriptions(:peltigera_user_desc).id], :NameDescription, :by_author, user: mary, by: :id) assert_query([], :NameDescription, :by_author, user: junk) end def test_name_description_by_editor assert_query([name_descriptions(:coprinus_comatus_desc).id], :NameDescription, :by_editor, user: rolf) assert_query([name_descriptions(:coprinus_comatus_desc).id], :NameDescription, :by_editor, user: mary) assert_query([], :NameDescription, :by_editor, user: dick) end def test_name_description_in_set assert_query([], :NameDescription, :in_set, ids: rolf.id) assert_query(NameDescription.all, :NameDescription, :in_set, ids: NameDescription.select(:id).to_a) assert_query([NameDescription.first.id], :NameDescription, :in_set, ids: [rolf.id, NameDescription.first.id]) end def test_observation_advanced_search assert_query([observations(:strobilurus_diminutivus_obs).id], :Observation, :advanced_search, name: "diminutivus") assert_query([observations(:coprinus_comatus_obs).id], :Observation, :advanced_search, location: "glendale") # where expect = Observation.where(location_id: locations(:burbank)).to_a assert_query(expect, :Observation, :advanced_search, location: "burbank", by: :id) # location expect = Observation.where(user_id: rolf.id).to_a assert_query(expect, :Observation, :advanced_search, user: "rolf", by: :id) assert_query([observations(:coprinus_comatus_obs).id], :Observation, :advanced_search, content: "second fruiting") # notes assert_query([observations(:minimal_unknown_obs).id], :Observation, :advanced_search, content: "agaricus") # comment end def test_observation_all expect = Observation.all.order("`when` DESC, id DESC").to_a assert_query(expect, :Observation, :all) end def test_observation_at_location expect = Observation.where(location_id: locations(:burbank).id). includes(:name). order("names.text_name, names.author, observations.id DESC").to_a assert_query(expect, :Observation, :at_location, location: locations(:burbank)) end def test_observation_at_where assert_query([observations(:coprinus_comatus_obs).id], :Observation, :at_where, user_where: "glendale", location: "glendale") end def test_observation_by_rss_log expect = Observation.where.not(rss_log: nil) assert_query(expect, :Observation, :by_rss_log) end def test_observation_by_user expect = Observation.where(user_id: rolf.id).to_a assert_query(expect, :Observation, :by_user, user: rolf, by: :id) expect = Observation.where(user_id: mary.id).to_a assert_query(expect, :Observation, :by_user, user: mary, by: :id) expect = Observation.where(user_id: dick.id).to_a assert_query(expect, :Observation, :by_user, user: dick, by: :id) assert_query([], :Observation, :by_user, user: junk, by: :id) end def test_observation_for_project assert_query([], :Observation, :for_project, project: projects(:empty_project)) assert_query(projects(:bolete_project).observations, :Observation, :for_project, project: projects(:bolete_project)) end def test_observation_in_set obs_set_ids = [observations(:unknown_with_no_naming).id, observations(:minimal_unknown_obs).id, observations(:strobilurus_diminutivus_obs).id, observations(:detailed_unknown_obs).id, observations(:agaricus_campestros_obs).id, observations(:coprinus_comatus_obs).id, observations(:agaricus_campestras_obs).id, observations(:agaricus_campestris_obs).id, observations(:agaricus_campestrus_obs).id] assert_query(obs_set_ids, :Observation, :in_set, ids: obs_set_ids) end def test_observation_in_species_list # These two are identical, so should be disambiguated by reverse_id. assert_query([observations(:detailed_unknown_obs).id, observations(:minimal_unknown_obs).id], :Observation, :in_species_list, species_list: species_lists(:unknown_species_list).id) end def test_observation_of_children assert_query([observations(:agaricus_campestras_obs).id, observations(:agaricus_campestris_obs).id, observations(:agaricus_campestros_obs).id, observations(:agaricus_campestrus_obs).id], :Observation, :of_children, name: names(:agaricus)) end def test_observation_of_name User.current = rolf names = Name.where("text_name like 'Agaricus camp%'").to_a name = names.pop names.each { |n| name.merge_synonyms(n) } observations(:agaricus_campestras_obs).update(user: mary) observations(:agaricus_campestros_obs).update(user: mary) spl = species_lists(:first_species_list) spl.observations << observations(:agaricus_campestrus_obs) spl.observations << observations(:agaricus_campestros_obs) proj = projects(:eol_project) proj.observations << observations(:agaricus_campestris_obs) proj.observations << observations(:agaricus_campestras_obs) assert_query(Observation.where(name: names(:fungi)), :Observation, :of_name, name: names(:fungi).id) assert_query([], :Observation, :of_name, name: names(:macrolepiota_rachodes).id) assert_query([observations(:agaricus_campestris_obs).id], :Observation, :of_name, name: names(:agaricus_campestris).id) assert_query([observations(:agaricus_campestros_obs).id, observations(:agaricus_campestras_obs).id, observations(:agaricus_campestrus_obs).id], :Observation, :of_name, name: names(:agaricus_campestris).id, synonyms: :exclusive) assert_query([observations(:agaricus_campestros_obs).id, observations(:agaricus_campestras_obs).id, observations(:agaricus_campestrus_obs).id, observations(:agaricus_campestris_obs).id], :Observation, :of_name, name: names(:agaricus_campestris).id, synonyms: :all) assert_query([observations(:coprinus_comatus_obs).id], :Observation, :of_name, name: names(:agaricus_campestris).id, nonconsensus: :exclusive) assert_query([observations(:agaricus_campestris_obs).id, observations(:coprinus_comatus_obs).id], :Observation, :of_name, name: names(:agaricus_campestris).id, nonconsensus: :all) end def test_observation_pattern_search # notes assert_query([observations(:agaricus_campestras_obs).id, observations(:agaricus_campestros_obs).id, observations(:agaricus_campestrus_obs).id, observations(:strobilurus_diminutivus_obs).id], :Observation, :pattern_search, pattern: '"somewhere else"') # where assert_query([observations(:strobilurus_diminutivus_obs).id], :Observation, :pattern_search, pattern: "pipi valley") # location expect = Observation.where(location_id: locations(:burbank)). includes(:name). order("names.text_name, names.author,observations.id DESC").to_a assert_query(expect, :Observation, :pattern_search, pattern: "burbank", by: :name) # name expect = Observation. where("names.text_name LIKE 'agaricus%'").includes(:name). order("names.text_name, names.author, observations.id DESC") assert_query(expect.map(&:id), :Observation, :pattern_search, pattern: "agaricus", by: :name) end def test_project_all assert_query(Project.all, :Project, :all) end def test_project_by_rss_log assert_query(Project.joins(:rss_log).distinct, :Project, :by_rss_log) end def test_project_in_set assert_query([projects(:eol_project).id], :Project, :in_set, ids: [projects(:eol_project).id]) assert_query([], :Project, :in_set, ids: []) end def test_project_pattern_search assert_query([], :Project, :pattern_search, pattern: "no project has this") # title assert_query(Project.where("summary LIKE '%bolete%' OR title LIKE '%bolete%'"), :Project, :pattern_search, pattern: "bolete") # summary assert_query(Project.where("summary LIKE '%two lists%' OR title LIKE '%two lists%'"), :Project, :pattern_search, pattern: "two lists") assert_query(Project.all, :Project, :pattern_search, pattern: "") end def test_rss_log_all ids = RssLog.all.map(&:id) assert_query(ids, :RssLog, :all) end def test_rss_log_in_set rsslog_set_ids = [rss_logs(:species_list_rss_log).id, rss_logs(:name_rss_log).id] assert_query(rsslog_set_ids, :RssLog, :in_set, ids: rsslog_set_ids) end def test_sequence_all expect = Sequence.all.order("created_at").to_a assert_query(expect, :Sequence, :all) assert_query(Sequence.where("locus LIKE 'ITS%'"), :Sequence, :all, locus_has: "ITS") assert_query([sequences(:alternate_archive)], :Sequence, :all, archive: "UNITE") assert_query([sequences(:deposited_sequence)], :Sequence, :all, accession_has: "968605") assert_query([sequences(:deposited_sequence)], :Sequence, :all, notes_has: "deposited_sequence") obs = observations(:locally_sequenced_obs) assert_query([sequences(:local_sequence)], :Sequence, :all, observations: [obs.id]) end def test_sequence_filters sequences = Sequence.all seq1 = sequences[0] seq2 = sequences[1] seq3 = sequences[2] seq4 = sequences[3] seq1.update_attribute(:observation, observations(:minimal_unknown_obs)) seq2.update_attribute(:observation, observations(:detailed_unknown_obs)) seq3.update_attribute(:observation, observations(:agaricus_campestris_obs)) seq4.update_attribute(:observation, observations(:peltigera_obs)) assert_query([seq1, seq2], :Sequence, :all, obs_date: ["2006", "2006"]) assert_query([seq1, seq2], :Sequence, :all, observers: users(:mary)) assert_query([seq1, seq2], :Sequence, :all, names: "Fungi") assert_query([seq4], :Sequence, :all, synonym_names: "Petigera") assert_query([seq1, seq2, seq3], :Sequence, :all, locations: "Burbank") assert_query([seq2], :Sequence, :all, projects: "Bolete Project") assert_query([seq1, seq2], :Sequence, :all, species_lists: "List of mysteries") assert_query([seq4], :Sequence, :all, confidence: "2") assert_query([seq1, seq2, seq3], :Sequence, :all, north: "90", south: "0", west: "-180", east: "-100") end def test_sequence_in_set list_set_ids = [sequences(:fasta_formatted_sequence).id, sequences(:bare_formatted_sequence).id] assert_query(list_set_ids, :Sequence, :in_set, ids: list_set_ids) end def test_sequence_pattern_search assert_query([], :Sequence, :pattern_search, pattern: "nonexistent") assert_query(Sequence.where("locus LIKE 'ITS%'"), :Sequence, :pattern_search, pattern: "ITS") assert_query([sequences(:alternate_archive)], :Sequence, :pattern_search, pattern: "UNITE") assert_query([sequences(:deposited_sequence)], :Sequence, :pattern_search, pattern: "deposited_sequence") end def test_species_list_all expect = SpeciesList.all.order("title").to_a assert_query(expect, :SpeciesList, :all) end def test_species_list_at_location assert_query(SpeciesList.where(location: locations(:burbank)), :SpeciesList, :at_location, location: locations(:burbank)) assert_query( [], :SpeciesList, :at_location, location: locations(:unused_location) ) end def test_species_list_at_where assert_query([], :SpeciesList, :at_where, user_where: "nowhere", location: "nowhere") assert_query([species_lists(:where_no_mushrooms_list)], :SpeciesList, :at_where, user_where: "no mushrooms", location: "no mushrooms") end def test_species_list_by_rss_log assert_query([species_lists(:first_species_list).id], :SpeciesList, :by_rss_log) end def test_species_list_by_user assert_query([species_lists(:first_species_list).id, species_lists(:another_species_list).id], :SpeciesList, :by_user, user: rolf, by: :id) assert_query(SpeciesList.where(user: mary), :SpeciesList, :by_user, user: mary) assert_query([], :SpeciesList, :by_user, user: dick) end def test_species_list_for_project assert_query([], :SpeciesList, :for_project, project: projects(:empty_project)) assert_query(projects(:bolete_project).species_lists, :SpeciesList, :for_project, project: projects(:bolete_project)) assert_query( projects(:two_list_project).species_lists, :SpeciesList, :for_project, project: projects(:two_list_project) ) end def test_species_list_in_set list_set_ids = [species_lists(:first_species_list).id, species_lists(:unknown_species_list).id] assert_query(list_set_ids, :SpeciesList, :in_set, ids: list_set_ids) end def test_species_list_pattern_search assert_query([], :SpeciesList, :pattern_search, pattern: "nonexistent pattern") # in title assert_query(SpeciesList.where(title: "query_first_list"), :SpeciesList, :pattern_search, pattern: "query_first_list") # in notes pattern = species_lists(:query_notes_list).notes assert_query(SpeciesList.where(notes: pattern), :SpeciesList, :pattern_search, pattern: pattern) # in location assert_query( SpeciesList.where(location: locations(:burbank)), :SpeciesList, :pattern_search, pattern: locations(:burbank).name ) # in where pattern = species_lists(:where_list).where assert_query(SpeciesList.where(where: pattern), :SpeciesList, :pattern_search, pattern: pattern) assert_query(SpeciesList.all, :SpeciesList, :pattern_search, pattern: "") end def test_herbarium_record_pattern_search assert_query([], :HerbariumRecord, :pattern_search, pattern: "no herbarium record has this") assert_query(HerbariumRecord.where("initial_det LIKE '%Agaricus%'"), :HerbariumRecord, :pattern_search, pattern: "Agaricus") assert_query(HerbariumRecord.where("notes LIKE '%rare%'"), :HerbariumRecord, :pattern_search, pattern: "rare") assert_query(HerbariumRecord.all, :HerbariumRecord, :pattern_search, pattern: "") end def test_user_all expect = User.all.order("name").to_a assert_query(expect, :User, :all) expect = User.all.order("login").to_a assert_query(expect, :User, :all, by: :login) end def test_user_in_set assert_query([rolf.id, mary.id, junk.id], :User, :in_set, ids: [junk.id, mary.id, rolf.id], by: :reverse_name) end def test_user_pattern_search assert_query([], :User, :pattern_search, pattern: "nonexistent pattern") # in login assert_query(User.where(login: users(:spammer).login), :User, :pattern_search, pattern: users(:spammer).login) # in name assert_query(User.where(name: users(:mary).name), :User, :pattern_search, pattern: users(:mary).name) assert_query(User.all, :User, :pattern_search, pattern: "") # sorted by location should include Users without location # (Differs from searches on other Classes or by other sort orders) assert_query(User.all, :User, :pattern_search, pattern: "", by: "location") end ############################################################################## # # :section: Filters # ############################################################################## def test_filtering_content ##### has_images filter ##### expect = Observation.where.not(thumb_image_id: nil) assert_query(expect, :Observation, :all, has_images: "yes") expect = Observation.where(thumb_image_id: nil) assert_query(expect, :Observation, :all, has_images: "no") ##### has_specimen filter ##### expect = Observation.where(specimen: true) assert_query(expect, :Observation, :all, has_specimen: "yes") expect = Observation.where(specimen: false) assert_query(expect, :Observation, :all, has_specimen: "no") ##### lichen filters ##### expect_obs = Observation.where("lifeform LIKE '%lichen%'").to_a expect_names = Name.where("lifeform LIKE '%lichen%'"). reject(&:correct_spelling_id).to_a assert_query(expect_obs, :Observation, :all, lichen: "yes") assert_query(expect_names, :Name, :all, lichen: "yes") expect_obs = Observation.where("lifeform NOT LIKE '% lichen %'").to_a expect_names = Name.where("lifeform NOT LIKE '% lichen %'"). reject(&:correct_spelling_id).to_a assert_query(expect_obs, :Observation, :all, lichen: "no") assert_query(expect_names, :Name, :all, lichen: "no") ##### region filter ##### expect = Location.where("name LIKE '%California%'") assert_query(expect, :Location, :all, region: "California, USA") assert_query(expect, :Location, :all, region: "USA, California") expect = Observation.where("`where` LIKE '%California, USA'") assert_query(expect, :Observation, :all, region: "California, USA") expect = Location.where("name LIKE '%, USA' OR name LIKE '%, Canada'") assert(expect.include?(locations(:albion))) # usa assert(expect.include?(locations(:elgin_co))) # canada assert_query(expect, :Location, :all, region: "North America") ##### clade filter ##### expect_names = Name.where("classification LIKE '%Agaricales%'"). reject(&:correct_spelling_id).to_a expect_names << names(:agaricales) expect_obs = expect_names.map(&:observations).flatten assert_query(expect_obs, :Observation, :all, clade: "Agaricales") assert_query(expect_names, :Name, :all, clade: "Agaricales") end ############################################################################## # # :section: Other stuff # ############################################################################## def test_whiny_nil_in_map_locations query = Query.lookup(:User, :in_set, ids: [rolf.id, 1000, mary.id]) query.query assert_equal(2, query.results.length) end def test_location_ordering albion = locations(:albion) elgin_co = locations(:elgin_co) User.current = rolf assert_equal(:postal, User.current_location_format) assert_query([albion, elgin_co], :Location, :in_set, ids: [albion.id, elgin_co.id], by: :name) User.current = roy assert_equal(:scientific, User.current_location_format) assert_query([elgin_co, albion], :Location, :in_set, ids: [albion.id, elgin_co.id], by: :name) obs1 = observations(:minimal_unknown_obs) obs2 = observations(:detailed_unknown_obs) obs1.update(location: albion) obs2.update(location: elgin_co) User.current = rolf assert_equal(:postal, User.current_location_format) assert_query([obs1, obs2], :Observation, :in_set, ids: [obs1.id, obs2.id], by: :location) User.current = roy assert_equal(:scientific, User.current_location_format) assert_query([obs2, obs1], :Observation, :in_set, ids: [obs1.id, obs2.id], by: :location) end end
unit About; {$MODE Delphi} { Disk Image Manager - About window Copyright (c) Damien Guard. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 } interface uses LCLIntf, Forms, ExtCtrls, StdCtrls, Graphics; type TfrmAbout = class(TForm) btnOK: TButton; imgAppIcon: TImage; lblTitle: TLabel; bvLine: TBevel; lblVersion: TLabel; timFade: TTimer; lblWeb: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure lblWebClick(Sender: TObject); procedure timFadeTimer(Sender: TObject); end; var frmAbout: TfrmAbout; implementation uses Main; {$R *.lfm} procedure TfrmAbout.FormCreate(Sender: TObject); begin Caption := 'About ' + Application.Title; lblTitle.Caption := Application.Title; lblVersion.Caption := 'Compiled: ' + {$I %DATE%} + ' ' + {$I %TIME%}; end; procedure TfrmAbout.timFadeTimer(Sender: TObject); begin if (timFade.Tag > 0) then if (frmAbout.AlphaBlendValue < 250) then frmAbout.AlphaBlendValue := frmAbout.AlphaBlendValue + timFade.Tag else begin timFade.Enabled := False; frmAbout.AlphaBlendValue := 255; end else if (frmAbout.AlphaBlendValue > 5) then frmAbout.AlphaBlendValue := frmAbout.AlphaBlendValue + timFade.Tag else begin timFade.Enabled := False; frmAbout.AlphaBlendValue := 0; Close; end; end; procedure TfrmAbout.FormShow(Sender: TObject); begin frmAbout.Font := frmMain.Font; frmAbout.AlphaBlendValue := 0; lblVersion.Font.Color := clBtnShadow; timFade.Tag := 4; timFade.Enabled := True; end; procedure TfrmAbout.lblWebClick(Sender: TObject); begin OpenDocument(PChar(TLabel(Sender).Caption)); end; procedure TfrmAbout.btnOKClick(Sender: TObject); begin timFade.Tag := -4; timFade.Enabled := True; end; end.
using System; using System.IO; using AsmResolver.IO; using Xunit; namespace AsmResolver.Tests.IO { public class BinaryStreamReaderTest { [Fact] public void EmptyArray() { var reader = ByteArrayDataSource.CreateReader(new byte[0]); Assert.Equal(0u, reader.Length); Assert.Throws<EndOfStreamException>(() => reader.ReadByte()); Assert.Equal(0, reader.ReadBytes(new byte[10], 0, 10)); } [Fact] public void ReadByte() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x80, 0x80 }); Assert.Equal((byte) 0x80, reader.ReadByte()); Assert.Equal(1u, reader.Offset); Assert.Equal((sbyte) -128, reader.ReadSByte()); Assert.Throws<EndOfStreamException>(() => reader.ReadByte()); } [Fact] public void ReadInt16() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x80, 0x02, 0x80 }); Assert.Equal((ushort) 0x8001, reader.ReadUInt16()); Assert.Equal(2u, reader.Offset); Assert.Equal((short) -32766, reader.ReadInt16()); Assert.Equal(4u, reader.Offset); } [Fact] public void ReadInt32() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x04, 0x03, 0x02, 0x81, 0x08, 0x07, 0x06, 0x85 }); Assert.Equal(0x81020304u, reader.ReadUInt32()); Assert.Equal(4u, reader.Offset); Assert.Equal(-2063202552, reader.ReadInt32()); Assert.Equal(8u, reader.Offset); } [Fact] public void ReadInt64() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x80, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x88, }); Assert.Equal(0x8001020304050607ul, reader.ReadUInt64()); Assert.Equal(8u, reader.Offset); Assert.Equal(-8644366967197856241, reader.ReadInt64()); Assert.Equal(16u, reader.Offset); } [Fact] public void NewForkSubRange() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); var fork = reader.ForkAbsolute(2, 3); Assert.Equal(2u, fork.StartOffset); Assert.Equal(2u, fork.Offset); Assert.Equal(3u, fork.Length); } [Fact] public void NewForkInvalidStart() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); Assert.Throws<ArgumentOutOfRangeException>(() => reader.ForkAbsolute(9, 3)); } [Fact] public void NewForkTooLong() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); Assert.Throws<EndOfStreamException>(() => reader.ForkAbsolute(6, 4)); } [Fact] public void ForkReadsSameData() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); var fork = reader.ForkAbsolute(0, 2); Assert.Equal(0x0201, fork.ReadUInt16()); } [Fact] public void ForkMovesIndependentOfOriginal() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); var fork = reader.ForkAbsolute(0, 2); fork.ReadUInt16(); Assert.Equal(0u, reader.Offset); Assert.Equal(2u, fork.Offset); } [Fact] public void ForkStartAtMiddle() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); var fork = reader.ForkAbsolute(4, 2); Assert.Equal(0x0605, fork.ReadUInt16()); } [Fact] public void ForkOfFork() { var reader = ByteArrayDataSource.CreateReader(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }); var fork = reader.ForkAbsolute(2, 4); var fork2 = fork.ForkAbsolute(3, 2); Assert.Equal(0x04, fork2.ReadByte()); } } }
package typingsSlinky.dineroJs import typingsSlinky.dineroJs.mod.Currency import typingsSlinky.dineroJs.mod.RoundingMode import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object dineroJsStrings { @js.native sealed trait AED extends Currency @scala.inline def AED: AED = "AED".asInstanceOf[AED] @js.native sealed trait AFN extends Currency @scala.inline def AFN: AFN = "AFN".asInstanceOf[AFN] @js.native sealed trait ALL extends Currency @scala.inline def ALL: ALL = "ALL".asInstanceOf[ALL] @js.native sealed trait AMD extends Currency @scala.inline def AMD: AMD = "AMD".asInstanceOf[AMD] @js.native sealed trait ANG extends Currency @scala.inline def ANG: ANG = "ANG".asInstanceOf[ANG] @js.native sealed trait AOA extends Currency @scala.inline def AOA: AOA = "AOA".asInstanceOf[AOA] @js.native sealed trait ARS extends Currency @scala.inline def ARS: ARS = "ARS".asInstanceOf[ARS] @js.native sealed trait AUD extends Currency @scala.inline def AUD: AUD = "AUD".asInstanceOf[AUD] @js.native sealed trait AWG extends Currency @scala.inline def AWG: AWG = "AWG".asInstanceOf[AWG] @js.native sealed trait AZN extends Currency @scala.inline def AZN: AZN = "AZN".asInstanceOf[AZN] @js.native sealed trait BAM extends Currency @scala.inline def BAM: BAM = "BAM".asInstanceOf[BAM] @js.native sealed trait BBD extends Currency @scala.inline def BBD: BBD = "BBD".asInstanceOf[BBD] @js.native sealed trait BDT extends Currency @scala.inline def BDT: BDT = "BDT".asInstanceOf[BDT] @js.native sealed trait BGN extends Currency @scala.inline def BGN: BGN = "BGN".asInstanceOf[BGN] @js.native sealed trait BHD extends Currency @scala.inline def BHD: BHD = "BHD".asInstanceOf[BHD] @js.native sealed trait BIF extends Currency @scala.inline def BIF: BIF = "BIF".asInstanceOf[BIF] @js.native sealed trait BMD extends Currency @scala.inline def BMD: BMD = "BMD".asInstanceOf[BMD] @js.native sealed trait BND extends Currency @scala.inline def BND: BND = "BND".asInstanceOf[BND] @js.native sealed trait BOB extends Currency @scala.inline def BOB: BOB = "BOB".asInstanceOf[BOB] @js.native sealed trait BOV extends Currency @scala.inline def BOV: BOV = "BOV".asInstanceOf[BOV] @js.native sealed trait BRL extends Currency @scala.inline def BRL: BRL = "BRL".asInstanceOf[BRL] @js.native sealed trait BSD extends Currency @scala.inline def BSD: BSD = "BSD".asInstanceOf[BSD] @js.native sealed trait BTN extends Currency @scala.inline def BTN: BTN = "BTN".asInstanceOf[BTN] @js.native sealed trait BWP extends Currency @scala.inline def BWP: BWP = "BWP".asInstanceOf[BWP] @js.native sealed trait BYN extends Currency @scala.inline def BYN: BYN = "BYN".asInstanceOf[BYN] @js.native sealed trait BZD extends Currency @scala.inline def BZD: BZD = "BZD".asInstanceOf[BZD] @js.native sealed trait CAD extends Currency @scala.inline def CAD: CAD = "CAD".asInstanceOf[CAD] @js.native sealed trait CDF extends Currency @scala.inline def CDF: CDF = "CDF".asInstanceOf[CDF] @js.native sealed trait CHE extends Currency @scala.inline def CHE: CHE = "CHE".asInstanceOf[CHE] @js.native sealed trait CHF extends Currency @scala.inline def CHF: CHF = "CHF".asInstanceOf[CHF] @js.native sealed trait CHW extends Currency @scala.inline def CHW: CHW = "CHW".asInstanceOf[CHW] @js.native sealed trait CLF extends Currency @scala.inline def CLF: CLF = "CLF".asInstanceOf[CLF] @js.native sealed trait CLP extends Currency @scala.inline def CLP: CLP = "CLP".asInstanceOf[CLP] @js.native sealed trait CNY extends Currency @scala.inline def CNY: CNY = "CNY".asInstanceOf[CNY] @js.native sealed trait COP extends Currency @scala.inline def COP: COP = "COP".asInstanceOf[COP] @js.native sealed trait COU extends Currency @scala.inline def COU: COU = "COU".asInstanceOf[COU] @js.native sealed trait CRC extends Currency @scala.inline def CRC: CRC = "CRC".asInstanceOf[CRC] @js.native sealed trait CUC extends Currency @scala.inline def CUC: CUC = "CUC".asInstanceOf[CUC] @js.native sealed trait CUP extends Currency @scala.inline def CUP: CUP = "CUP".asInstanceOf[CUP] @js.native sealed trait CVE extends Currency @scala.inline def CVE: CVE = "CVE".asInstanceOf[CVE] @js.native sealed trait CZK extends Currency @scala.inline def CZK: CZK = "CZK".asInstanceOf[CZK] @js.native sealed trait DJF extends Currency @scala.inline def DJF: DJF = "DJF".asInstanceOf[DJF] @js.native sealed trait DKK extends Currency @scala.inline def DKK: DKK = "DKK".asInstanceOf[DKK] @js.native sealed trait DOP extends Currency @scala.inline def DOP: DOP = "DOP".asInstanceOf[DOP] @js.native sealed trait DZD extends Currency @scala.inline def DZD: DZD = "DZD".asInstanceOf[DZD] @js.native sealed trait EGP extends Currency @scala.inline def EGP: EGP = "EGP".asInstanceOf[EGP] @js.native sealed trait ERN extends Currency @scala.inline def ERN: ERN = "ERN".asInstanceOf[ERN] @js.native sealed trait ETB extends Currency @scala.inline def ETB: ETB = "ETB".asInstanceOf[ETB] @js.native sealed trait EUR extends Currency @scala.inline def EUR: EUR = "EUR".asInstanceOf[EUR] @js.native sealed trait FJD extends Currency @scala.inline def FJD: FJD = "FJD".asInstanceOf[FJD] @js.native sealed trait FKP extends Currency @scala.inline def FKP: FKP = "FKP".asInstanceOf[FKP] @js.native sealed trait GBP extends Currency @scala.inline def GBP: GBP = "GBP".asInstanceOf[GBP] @js.native sealed trait GEL extends Currency @scala.inline def GEL: GEL = "GEL".asInstanceOf[GEL] @js.native sealed trait GHS extends Currency @scala.inline def GHS: GHS = "GHS".asInstanceOf[GHS] @js.native sealed trait GIP extends Currency @scala.inline def GIP: GIP = "GIP".asInstanceOf[GIP] @js.native sealed trait GMD extends Currency @scala.inline def GMD: GMD = "GMD".asInstanceOf[GMD] @js.native sealed trait GNF extends Currency @scala.inline def GNF: GNF = "GNF".asInstanceOf[GNF] @js.native sealed trait GTQ extends Currency @scala.inline def GTQ: GTQ = "GTQ".asInstanceOf[GTQ] @js.native sealed trait GYD extends Currency @scala.inline def GYD: GYD = "GYD".asInstanceOf[GYD] @js.native sealed trait HALF_AWAY_FROM_ZERO extends RoundingMode @scala.inline def HALF_AWAY_FROM_ZERO: HALF_AWAY_FROM_ZERO = "HALF_AWAY_FROM_ZERO".asInstanceOf[HALF_AWAY_FROM_ZERO] @js.native sealed trait HALF_DOWN extends RoundingMode @scala.inline def HALF_DOWN: HALF_DOWN = "HALF_DOWN".asInstanceOf[HALF_DOWN] @js.native sealed trait HALF_EVEN extends RoundingMode @scala.inline def HALF_EVEN: HALF_EVEN = "HALF_EVEN".asInstanceOf[HALF_EVEN] @js.native sealed trait HALF_ODD extends RoundingMode @scala.inline def HALF_ODD: HALF_ODD = "HALF_ODD".asInstanceOf[HALF_ODD] @js.native sealed trait HALF_TOWARDS_ZERO extends RoundingMode @scala.inline def HALF_TOWARDS_ZERO: HALF_TOWARDS_ZERO = "HALF_TOWARDS_ZERO".asInstanceOf[HALF_TOWARDS_ZERO] @js.native sealed trait HALF_UP extends RoundingMode @scala.inline def HALF_UP: HALF_UP = "HALF_UP".asInstanceOf[HALF_UP] @js.native sealed trait HKD extends Currency @scala.inline def HKD: HKD = "HKD".asInstanceOf[HKD] @js.native sealed trait HNL extends Currency @scala.inline def HNL: HNL = "HNL".asInstanceOf[HNL] @js.native sealed trait HRK extends Currency @scala.inline def HRK: HRK = "HRK".asInstanceOf[HRK] @js.native sealed trait HTG extends Currency @scala.inline def HTG: HTG = "HTG".asInstanceOf[HTG] @js.native sealed trait HUF extends Currency @scala.inline def HUF: HUF = "HUF".asInstanceOf[HUF] @js.native sealed trait IDR extends Currency @scala.inline def IDR: IDR = "IDR".asInstanceOf[IDR] @js.native sealed trait ILS extends Currency @scala.inline def ILS: ILS = "ILS".asInstanceOf[ILS] @js.native sealed trait INR extends Currency @scala.inline def INR: INR = "INR".asInstanceOf[INR] @js.native sealed trait IQD extends Currency @scala.inline def IQD: IQD = "IQD".asInstanceOf[IQD] @js.native sealed trait IRR extends Currency @scala.inline def IRR: IRR = "IRR".asInstanceOf[IRR] @js.native sealed trait ISK extends Currency @scala.inline def ISK: ISK = "ISK".asInstanceOf[ISK] @js.native sealed trait JMD extends Currency @scala.inline def JMD: JMD = "JMD".asInstanceOf[JMD] @js.native sealed trait JOD extends Currency @scala.inline def JOD: JOD = "JOD".asInstanceOf[JOD] @js.native sealed trait JPY extends Currency @scala.inline def JPY: JPY = "JPY".asInstanceOf[JPY] @js.native sealed trait KES extends Currency @scala.inline def KES: KES = "KES".asInstanceOf[KES] @js.native sealed trait KGS extends Currency @scala.inline def KGS: KGS = "KGS".asInstanceOf[KGS] @js.native sealed trait KHR extends Currency @scala.inline def KHR: KHR = "KHR".asInstanceOf[KHR] @js.native sealed trait KMF extends Currency @scala.inline def KMF: KMF = "KMF".asInstanceOf[KMF] @js.native sealed trait KPW extends Currency @scala.inline def KPW: KPW = "KPW".asInstanceOf[KPW] @js.native sealed trait KRW extends Currency @scala.inline def KRW: KRW = "KRW".asInstanceOf[KRW] @js.native sealed trait KWD extends Currency @scala.inline def KWD: KWD = "KWD".asInstanceOf[KWD] @js.native sealed trait KYD extends Currency @scala.inline def KYD: KYD = "KYD".asInstanceOf[KYD] @js.native sealed trait KZT extends Currency @scala.inline def KZT: KZT = "KZT".asInstanceOf[KZT] @js.native sealed trait LAK extends Currency @scala.inline def LAK: LAK = "LAK".asInstanceOf[LAK] @js.native sealed trait LBP extends Currency @scala.inline def LBP: LBP = "LBP".asInstanceOf[LBP] @js.native sealed trait LKR extends Currency @scala.inline def LKR: LKR = "LKR".asInstanceOf[LKR] @js.native sealed trait LRD extends Currency @scala.inline def LRD: LRD = "LRD".asInstanceOf[LRD] @js.native sealed trait LSL extends Currency @scala.inline def LSL: LSL = "LSL".asInstanceOf[LSL] @js.native sealed trait LYD extends Currency @scala.inline def LYD: LYD = "LYD".asInstanceOf[LYD] @js.native sealed trait MAD extends Currency @scala.inline def MAD: MAD = "MAD".asInstanceOf[MAD] @js.native sealed trait MDL extends Currency @scala.inline def MDL: MDL = "MDL".asInstanceOf[MDL] @js.native sealed trait MGA extends Currency @scala.inline def MGA: MGA = "MGA".asInstanceOf[MGA] @js.native sealed trait MKD extends Currency @scala.inline def MKD: MKD = "MKD".asInstanceOf[MKD] @js.native sealed trait MMK extends Currency @scala.inline def MMK: MMK = "MMK".asInstanceOf[MMK] @js.native sealed trait MNT extends Currency @scala.inline def MNT: MNT = "MNT".asInstanceOf[MNT] @js.native sealed trait MOP extends Currency @scala.inline def MOP: MOP = "MOP".asInstanceOf[MOP] @js.native sealed trait MRU extends Currency @scala.inline def MRU: MRU = "MRU".asInstanceOf[MRU] @js.native sealed trait MUR extends Currency @scala.inline def MUR: MUR = "MUR".asInstanceOf[MUR] @js.native sealed trait MVR extends Currency @scala.inline def MVR: MVR = "MVR".asInstanceOf[MVR] @js.native sealed trait MWK extends Currency @scala.inline def MWK: MWK = "MWK".asInstanceOf[MWK] @js.native sealed trait MXN extends Currency @scala.inline def MXN: MXN = "MXN".asInstanceOf[MXN] @js.native sealed trait MXV extends Currency @scala.inline def MXV: MXV = "MXV".asInstanceOf[MXV] @js.native sealed trait MYR extends Currency @scala.inline def MYR: MYR = "MYR".asInstanceOf[MYR] @js.native sealed trait MZN extends Currency @scala.inline def MZN: MZN = "MZN".asInstanceOf[MZN] @js.native sealed trait NAD extends Currency @scala.inline def NAD: NAD = "NAD".asInstanceOf[NAD] @js.native sealed trait NGN extends Currency @scala.inline def NGN: NGN = "NGN".asInstanceOf[NGN] @js.native sealed trait NIO extends Currency @scala.inline def NIO: NIO = "NIO".asInstanceOf[NIO] @js.native sealed trait NOK extends Currency @scala.inline def NOK: NOK = "NOK".asInstanceOf[NOK] @js.native sealed trait NPR extends Currency @scala.inline def NPR: NPR = "NPR".asInstanceOf[NPR] @js.native sealed trait NZD extends Currency @scala.inline def NZD: NZD = "NZD".asInstanceOf[NZD] @js.native sealed trait OMR extends Currency @scala.inline def OMR: OMR = "OMR".asInstanceOf[OMR] @js.native sealed trait PAB extends Currency @scala.inline def PAB: PAB = "PAB".asInstanceOf[PAB] @js.native sealed trait PEN extends Currency @scala.inline def PEN: PEN = "PEN".asInstanceOf[PEN] @js.native sealed trait PGK extends Currency @scala.inline def PGK: PGK = "PGK".asInstanceOf[PGK] @js.native sealed trait PHP extends Currency @scala.inline def PHP: PHP = "PHP".asInstanceOf[PHP] @js.native sealed trait PKR extends Currency @scala.inline def PKR: PKR = "PKR".asInstanceOf[PKR] @js.native sealed trait PLN extends Currency @scala.inline def PLN: PLN = "PLN".asInstanceOf[PLN] @js.native sealed trait PYG extends Currency @scala.inline def PYG: PYG = "PYG".asInstanceOf[PYG] @js.native sealed trait QAR extends Currency @scala.inline def QAR: QAR = "QAR".asInstanceOf[QAR] @js.native sealed trait RON extends Currency @scala.inline def RON: RON = "RON".asInstanceOf[RON] @js.native sealed trait RSD extends Currency @scala.inline def RSD: RSD = "RSD".asInstanceOf[RSD] @js.native sealed trait RUB extends Currency @scala.inline def RUB: RUB = "RUB".asInstanceOf[RUB] @js.native sealed trait RWF extends Currency @scala.inline def RWF: RWF = "RWF".asInstanceOf[RWF] @js.native sealed trait SAR extends Currency @scala.inline def SAR: SAR = "SAR".asInstanceOf[SAR] @js.native sealed trait SBD extends Currency @scala.inline def SBD: SBD = "SBD".asInstanceOf[SBD] @js.native sealed trait SCR extends Currency @scala.inline def SCR: SCR = "SCR".asInstanceOf[SCR] @js.native sealed trait SDG extends Currency @scala.inline def SDG: SDG = "SDG".asInstanceOf[SDG] @js.native sealed trait SEK extends Currency @scala.inline def SEK: SEK = "SEK".asInstanceOf[SEK] @js.native sealed trait SGD extends Currency @scala.inline def SGD: SGD = "SGD".asInstanceOf[SGD] @js.native sealed trait SHP extends Currency @scala.inline def SHP: SHP = "SHP".asInstanceOf[SHP] @js.native sealed trait SLL extends Currency @scala.inline def SLL: SLL = "SLL".asInstanceOf[SLL] @js.native sealed trait SOS extends Currency @scala.inline def SOS: SOS = "SOS".asInstanceOf[SOS] @js.native sealed trait SRD extends Currency @scala.inline def SRD: SRD = "SRD".asInstanceOf[SRD] @js.native sealed trait SSP extends Currency @scala.inline def SSP: SSP = "SSP".asInstanceOf[SSP] @js.native sealed trait STN extends Currency @scala.inline def STN: STN = "STN".asInstanceOf[STN] @js.native sealed trait SVC extends Currency @scala.inline def SVC: SVC = "SVC".asInstanceOf[SVC] @js.native sealed trait SYP extends Currency @scala.inline def SYP: SYP = "SYP".asInstanceOf[SYP] @js.native sealed trait SZL extends Currency @scala.inline def SZL: SZL = "SZL".asInstanceOf[SZL] @js.native sealed trait THB extends Currency @scala.inline def THB: THB = "THB".asInstanceOf[THB] @js.native sealed trait TJS extends Currency @scala.inline def TJS: TJS = "TJS".asInstanceOf[TJS] @js.native sealed trait TMT extends Currency @scala.inline def TMT: TMT = "TMT".asInstanceOf[TMT] @js.native sealed trait TND extends Currency @scala.inline def TND: TND = "TND".asInstanceOf[TND] @js.native sealed trait TOP extends Currency @scala.inline def TOP: TOP = "TOP".asInstanceOf[TOP] @js.native sealed trait TRY extends Currency @scala.inline def TRY: TRY = "TRY".asInstanceOf[TRY] @js.native sealed trait TTD extends Currency @scala.inline def TTD: TTD = "TTD".asInstanceOf[TTD] @js.native sealed trait TWD extends Currency @scala.inline def TWD: TWD = "TWD".asInstanceOf[TWD] @js.native sealed trait TZS extends Currency @scala.inline def TZS: TZS = "TZS".asInstanceOf[TZS] @js.native sealed trait UAH extends Currency @scala.inline def UAH: UAH = "UAH".asInstanceOf[UAH] @js.native sealed trait UGX extends Currency @scala.inline def UGX: UGX = "UGX".asInstanceOf[UGX] @js.native sealed trait USD extends Currency @scala.inline def USD: USD = "USD".asInstanceOf[USD] @js.native sealed trait USN extends Currency @scala.inline def USN: USN = "USN".asInstanceOf[USN] @js.native sealed trait UYI extends Currency @scala.inline def UYI: UYI = "UYI".asInstanceOf[UYI] @js.native sealed trait UYU extends Currency @scala.inline def UYU: UYU = "UYU".asInstanceOf[UYU] @js.native sealed trait UYW extends Currency @scala.inline def UYW: UYW = "UYW".asInstanceOf[UYW] @js.native sealed trait UZS extends Currency @scala.inline def UZS: UZS = "UZS".asInstanceOf[UZS] @js.native sealed trait VES extends Currency @scala.inline def VES: VES = "VES".asInstanceOf[VES] @js.native sealed trait VND extends Currency @scala.inline def VND: VND = "VND".asInstanceOf[VND] @js.native sealed trait VUV extends Currency @scala.inline def VUV: VUV = "VUV".asInstanceOf[VUV] @js.native sealed trait WST extends Currency @scala.inline def WST: WST = "WST".asInstanceOf[WST] @js.native sealed trait XAF extends Currency @scala.inline def XAF: XAF = "XAF".asInstanceOf[XAF] @js.native sealed trait XAG extends Currency @scala.inline def XAG: XAG = "XAG".asInstanceOf[XAG] @js.native sealed trait XAU extends Currency @scala.inline def XAU: XAU = "XAU".asInstanceOf[XAU] @js.native sealed trait XBA extends Currency @scala.inline def XBA: XBA = "XBA".asInstanceOf[XBA] @js.native sealed trait XBB extends Currency @scala.inline def XBB: XBB = "XBB".asInstanceOf[XBB] @js.native sealed trait XBC extends Currency @scala.inline def XBC: XBC = "XBC".asInstanceOf[XBC] @js.native sealed trait XBD extends Currency @scala.inline def XBD: XBD = "XBD".asInstanceOf[XBD] @js.native sealed trait XCD extends Currency @scala.inline def XCD: XCD = "XCD".asInstanceOf[XCD] @js.native sealed trait XDR extends Currency @scala.inline def XDR: XDR = "XDR".asInstanceOf[XDR] @js.native sealed trait XOF extends Currency @scala.inline def XOF: XOF = "XOF".asInstanceOf[XOF] @js.native sealed trait XPD extends Currency @scala.inline def XPD: XPD = "XPD".asInstanceOf[XPD] @js.native sealed trait XPF extends Currency @scala.inline def XPF: XPF = "XPF".asInstanceOf[XPF] @js.native sealed trait XPT extends Currency @scala.inline def XPT: XPT = "XPT".asInstanceOf[XPT] @js.native sealed trait XSU extends Currency @scala.inline def XSU: XSU = "XSU".asInstanceOf[XSU] @js.native sealed trait XTS extends Currency @scala.inline def XTS: XTS = "XTS".asInstanceOf[XTS] @js.native sealed trait XUA extends Currency @scala.inline def XUA: XUA = "XUA".asInstanceOf[XUA] @js.native sealed trait XXX extends Currency @scala.inline def XXX: XXX = "XXX".asInstanceOf[XXX] @js.native sealed trait YER extends Currency @scala.inline def YER: YER = "YER".asInstanceOf[YER] @js.native sealed trait ZAR extends Currency @scala.inline def ZAR: ZAR = "ZAR".asInstanceOf[ZAR] @js.native sealed trait ZMW extends Currency @scala.inline def ZMW: ZMW = "ZMW".asInstanceOf[ZMW] @js.native sealed trait ZWL extends Currency @scala.inline def ZWL: ZWL = "ZWL".asInstanceOf[ZWL] }
require "spec_helper" describe GraphsController do describe "routing" do it "routes to #tree_graph" do expect(get("/tree_graph")).to route_to("graphs#tree_graph") end it "routes to #view_graph" do expect(get("/view_graph/path")).to route_to("graphs#view_graph", :path => "path") end it "routes to #setup_graph" do expect(get("/setup_graph/path")).to route_to("graphs#setup_graph", :path => "path") end it "routes to #list_graph" do expect(get("/list_graph")).to route_to("graphs#list_graph") expect(get("/list_graph/path")).to route_to("graphs#list_graph", :path => "path") end it "routes to #tag_graph" do expect(get("/tag_graph")).to route_to("graphs#tag_graph") expect(get("/tag_graph/tag_list")).to route_to("graphs#tag_graph", :tag_list => "tag_list") expect(delete("/tag_graph/tag_list")).to route_to("graphs#delete_tag_graph", :tag_list => "tag_list") end it "routes to #autocomplete_graph" do expect(get("/autocomplete_graph")).to route_to("graphs#autocomplete_graph") end it "routes to #tagselect_graph" do expect(get("/tagselect_graph")).to route_to("graphs#tagselect_graph") end it "routes to #accordion_graph" do expect(get("/accordion_graph")).to route_to("graphs#accordion_graph") end end end
import "./index.scss"; import * as React from "react"; import Informations from "./informations"; export enum SavingThrows { Strength = "Strength", Dexterity = "Dexterity", Constitution = "Constitution", Intelligence = "Intelligence", Wisdom = "Wisdom", Charisma = "Charisma", } export enum Skills { Acrobatics = "Acrobatics", AnimalHandling = "Animal Handling", Arcana = "Arcana", Athletics = "Athletics", Deception = "Deception", History = "History", Insight = "Insight", Intimidation = "Intimidation", Investigation = "Investigation", Nature = "Nature", Medicine = "Medicine", Perception = "Perception", Performance = "Performance", Persuasion = "Persuasion", Religion = "Religion", SleightofHand = "Sleight of Hand", Stealth = "Stealth", Survival = "Survival", } export interface IPlayer { readonly name: string; readonly playerName: string; readonly characterClass: string; readonly background: string; readonly race: string; readonly allignment: string; readonly experience: string; readonly strength: number; readonly dexterity: number; readonly constitution: number; readonly intelligence: number; readonly wisdom: number; readonly charisma: number; readonly maximumHitPoints: number; readonly currentHitPoints: number; readonly armorClass: number; readonly initiative: number; readonly speed: number; readonly hitDice: string; readonly personalityTraits: string[]; readonly ideals: string[]; readonly bonds: string[]; readonly flaws: string[]; readonly inventory: string[]; readonly armorProficiencies: string[]; readonly weaponProficiencies: string[]; readonly otherProficiencies: string[]; readonly hasInspiration: boolean; readonly features: string[]; readonly profienciencyBonus: number; readonly savingThrows: SavingThrows[]; readonly skills: Skills[]; readonly languagues: string[]; } export interface IPlayerProps { readonly player: IPlayer; } const Player = ({ player: { name }, player }: IPlayerProps) => { return ( <div className="player__wrapper"> <div className="player__top-container"> <div className="player__name-container">{name}</div> <Informations stats={player} /> </div> <div className="player__bottom-container"> <div className="player__bottom-left-container"> {/* <Stats /> */} <div className="player__skills-column"> <div className="player__inspiration"></div> <div className="player__proficiency-bonus"></div> {/* <SavingThrows /> */} {/* <Skills /> */} </div> <div className="player__passive-wisdom"></div> <div className="player__proficiencies-container"></div> </div> <div className="player__bottom-middle-container"> <div className="player__bottom-middle-top-container"> <div> <div className="player__armor-class"></div> <div className="player__initiative"></div> <div className="player__speed"></div> </div> <div className="player__current-hp-container"> <span className="player__maximum-hit-points"></span> <div></div> </div> <div className="player__temporary-hp"></div> <div> <div className="player__hit-dice"></div> {/* <DeathSaves player={player}} /> */} </div> </div> <div className="player__attacks-and-spellcasting">{/* TODO */}</div> {/* <Inventory /> */} </div> <div className="player__right-container"></div> </div> </div> ); }; export default Player;
module Cranium::FileUtils def self.line_count(file_path) File.read(file_path).each_line.count end end
--- title: Sofás a conjunto con un reposapiés subtitle: Sofás layout: default modal-id: 3 img: sofas_2.jpg thumbnail: sofas_2.jpg alt: sofas_2 category: sofas description: Dos sofás que, junto a su reposapiés, quedaron estupendos al lado de su mesita. ---
package io.exponential.androidactivityandfragmentlifecycle; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class AFragment extends Fragment { private static final String ARG_CITY = "city"; private String city; private Callbacks callbacks; private static final String TAG = "AFragment"; OnClickListener displayNameHandler = new OnClickListener() { @Override public void onClick(View v) { String name = ((EditText) getView().findViewById(R.id.fragment_a_name)) .getText().toString(); if (callbacks != null) { callbacks.updateName(name); } } }; // Factory method without arguments public static AFragment newInstance(String city) { Log.v(TAG, "S:lcm:newInstance"); AFragment aFragment = new AFragment(); Bundle args = new Bundle(); args.putString(ARG_CITY, city); aFragment.setArguments(args); Log.v(TAG, "E:lcm:newInstance"); return aFragment; } public AFragment() { // Required empty public constructor Log.v(TAG, "S:lcm:Constructor"); Log.v(TAG, "E:lcm:Constructor"); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.v(TAG, "S:lcm:onAttach"); try { callbacks = (Callbacks) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement Callbacks"); } Log.v(TAG, "E:lcm:onAttach"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.v(TAG, "S:lcm:onCreate"); if (getArguments() != null) { city = getArguments().getString(ARG_CITY); } Log.v(TAG, "E:lcm:onCreate"); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.v(TAG, "S:lcm:onCreateView"); View view = inflater.inflate(R.layout.fragment_a, container, false); // Update the UI based on args passed into newInstance() ((TextView) view.findViewById(R.id.fragment_a_city)).setText(city); // Event handlers Button displayName = (Button) view.findViewById(R.id.fragment_a_display_name); displayName.setOnClickListener(displayNameHandler); Log.v(TAG, "E:lcm:onCreateView"); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.v(TAG, "S:lcm:onActivityCreated"); Log.v(TAG, "E:lcm:onActivityCreated"); } @Override public void onStart() { super.onStart(); Log.v(TAG, "S:lcm:onStart"); Log.v(TAG, "E:lcm:onStart"); } @Override public void onResume() { super.onResume(); Log.v(TAG, "S:lcm:onResume"); Log.v(TAG, "E:lcm:onResume"); } @Override public void onPause() { super.onPause(); Log.v(TAG, "S:lcm:onPause"); Log.v(TAG, "E:lcm:onPause"); } @Override public void onStop() { super.onStop(); Log.v(TAG, "S:lcm:onStop"); Log.v(TAG, "E:lcm:onStop"); } @Override public void onDestroyView() { super.onDestroyView(); Log.v(TAG, "S:lcm:onDestroyView"); Log.v(TAG, "E:lcm:onDestroyView"); } @Override public void onDestroy() { super.onDestroy(); Log.v(TAG, "S:lcm:onDestroy"); Log.v(TAG, "E:lcm:onDestroy"); } @Override public void onDetach() { super.onDetach(); Log.v(TAG, "S:lcm:onDetach"); Log.v(TAG, "E:lcm:onDetach"); callbacks = null; } public interface Callbacks { public void updateName(String name); } // AFragment has no public methods as the containing Activity never passed data down to the // Fragment after the Fragment is created. }
# java_gitignore Java项目中不进行版本管理文件的配置 ## idea gitignore [idea gitignore](https://github.com/CavaliersFor/java_gitignore/blob/master/IDEA_gitignore)
CREATE TABLE IF NOT EXISTS "proxy_endpoint_schemas" ( "id" SERIAL PRIMARY KEY, "endpoint_id" INTEGER NOT NULL, "name" TEXT NOT NULL, "request_schema_id" INTEGER, "request_type" TEXT NOT NULL, "request_schema" TEXT, "response_same_as_request" BOOLEAN NOT NULL DEFAULT TRUE, "response_schema_id" INTEGER, "response_type" TEXT NOT NULL, "response_schema" TEXT, "data" TEXT, UNIQUE ("endpoint_id", "name"), FOREIGN KEY("endpoint_id") REFERENCES "proxy_endpoints"("id") ON DELETE CASCADE, FOREIGN KEY("request_schema_id") REFERENCES "schemas"("id") ON DELETE SET NULL, FOREIGN KEY("response_schema_id") REFERENCES "schemas"("id") ON DELETE SET NULL );
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace MirthDotNet.Model { [Serializable] public class Connector { [XmlAttribute("version")] public string Version { get; set; } [XmlElement("metaDataId")] public string MetaDataId { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlElement("transportName")] public string TransportName { get; set; } [XmlElement("mode")] public string Mode { get; set; } [XmlElement("enabled")] public bool Enabled { get; set; } [XmlElement("waitForPrevious")] public bool WaitForPrevious { get; set; } [XmlElement("properties")] public ConnectorProperties Properties { get; set; } [XmlElement("filter")] public ConnectorFilter Filter { get; set; } [XmlElement("transformer")] public ConnectorTransformer Transformer { get; set; } } }
is_question(elem::HTMLElement) = any(is_question, elem.children) is_question(elem::HTMLText) = occursin(r"^[0-9]+\. ", elem.text) struct Question content responses::Vector{Response} label id end function question(contents, responses, label; detect_label=false) matched = 0 for elem in contents for node in PreOrderDFS(elem) if node isa HTMLText m = match(r"([0-9]+)\. ", node.text) if detect_label && m !== nothing label = m.captures[1] matched += 1 end node.text = replace(node.text, r"[0-9]+\. " => "") end end end detect_label && matched == 0 && @warn "Failed to detect label, using default ($label)" matched > 1 && @warn "Multiple lables detected, using last one ($label)" Question(contents, responses, label, string(uuid4())) end function Base.show(io::IO, q::Question) print(io, q.label, ": ") for c in q.content println(io, c) end print(io, "\n") for r in q.responses println(io, " ", r) end end
use std::collections::HashMap; use std::sync::{Arc, RwLock}; use super::{Editor, Result}; use completion::Completer; use config::{Config, EditMode}; use edit::init_state; use keymap::{Cmd, InputState}; use keys::KeyPress; use tty::Sink; mod common; mod emacs; mod history; mod vi_cmd; mod vi_insert; fn init_editor(mode: EditMode, keys: &[KeyPress]) -> Editor<()> { let config = Config::builder().edit_mode(mode).build(); let mut editor = Editor::<()>::with_config(config); editor.term.keys.extend(keys.iter().cloned()); editor } struct SimpleCompleter; impl Completer for SimpleCompleter { type Candidate = String; fn complete(&self, line: &str, _pos: usize) -> Result<(usize, Vec<String>)> { Ok((0, vec![line.to_owned() + "t"])) } } #[test] fn complete_line() { let mut out = Sink::new(); let mut s = init_state(&mut out, "rus", 3); let config = Config::default(); let mut input_state = InputState::new(&config, Arc::new(RwLock::new(HashMap::new()))); let keys = &[KeyPress::Enter]; let mut rdr = keys.iter(); let completer = SimpleCompleter; let cmd = super::complete_line( &mut rdr, &mut s, &mut input_state, &completer, None, &Config::default(), ).unwrap(); assert_eq!(Some(Cmd::AcceptLine), cmd); assert_eq!("rust", s.line.as_str()); assert_eq!(4, s.line.pos()); } // `keys`: keys to press // `expected_line`: line after enter key fn assert_line(mode: EditMode, keys: &[KeyPress], expected_line: &str) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline(">>").unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected_line`: line after enter key fn assert_line_with_initial( mode: EditMode, initial: (&str, &str), keys: &[KeyPress], expected_line: &str, ) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial(">>", initial).unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_cursor(mode: EditMode, initial: (&str, &str), keys: &[KeyPress], expected: (&str, &str)) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial("", initial).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); assert_eq!(expected.0.len(), editor.term.cursor); } // `entries`: history entries before `keys` pressed // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_history(mode: EditMode, entries: &[&str], keys: &[KeyPress], expected: (&str, &str)) { let mut editor = init_editor(mode, keys); for entry in entries { editor.history.add(*entry); } let actual_line = editor.readline("").unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); assert_eq!(expected.0.len(), editor.term.cursor); } #[test] fn unknown_esc_key() { for mode in &[EditMode::Emacs, EditMode::Vi] { assert_line(*mode, &[KeyPress::UnknownEscSeq, KeyPress::Enter], ""); } }
update c_taxcategory_trl set name = 'Regular Tax Rate 19% (Germany)', istranslated='Y', updatedby=99, /*user-id used to indicate "manual migration"*/ updated='2019-06-25 08:58:32.935051+03' /*select now();*/ where c_taxcategory_id=1000009 and ad_language='en_US';
###Pages * [services](https://boxing199.github.io/miid-front/services.html) * [about company](https://boxing199.github.io/miid-front/about.html) * [for developers](https://boxing199.github.io/miid-front/for_developers.html) * [main sliders](https://boxing199.github.io/miid-front/main.html) * [catalog](https://boxing199.github.io/miid-front/catalog.html) * [details](https://boxing199.github.io/miid-front/details.html) ###Design * [design](https://www.figma.com/file/K0iROWKAzycQsELhVvtmd3qN/%D0%9C%D0%98%D0%98%D0%94?node-id=0%3A1)
<?php namespace PaymentAssist\Type; class Economic { /** * @var float */ private $unem_prob; /** * @var int */ private $unem_index; /** * @var float */ private $econscore; /** * @var int */ private $econband; /** * @return float */ public function getUnem_prob() { return $this->unem_prob; } /** * @param float $unem_prob * @return Economic */ public function withUnem_prob($unem_prob) { $new = clone $this; $new->unem_prob = $unem_prob; return $new; } /** * @return int */ public function getUnem_index() { return $this->unem_index; } /** * @param int $unem_index * @return Economic */ public function withUnem_index($unem_index) { $new = clone $this; $new->unem_index = $unem_index; return $new; } /** * @return float */ public function getEconscore() { return $this->econscore; } /** * @param float $econscore * @return Economic */ public function withEconscore($econscore) { $new = clone $this; $new->econscore = $econscore; return $new; } /** * @return int */ public function getEconband() { return $this->econband; } /** * @param int $econband * @return Economic */ public function withEconband($econband) { $new = clone $this; $new->econband = $econband; return $new; } }
export type Align = 'left' | 'right' | undefined; export type DateType = 'picker' | 'range' | undefined;
//! Test that the GC is not confused by an object that contains pointers to //! itself. extern crate cell_gc; #[macro_use] extern crate cell_gc_derive; mod aux; use aux::pairs::*; #[test] fn root_self_references() { cell_gc::with_heap(|hs| { // Create a root object that contains pointers to itself. let root = alloc_null_pair(hs); root.set_head(Value::Pair(root.clone())); root.set_tail(Value::Pair(root.clone())); hs.force_gc(); // After GC, the root object should be unchanged. assert_eq!(root.head(), Value::Pair(root.clone())); assert_eq!(root.tail(), Value::Pair(root.clone())); }); }
<?php /** * Created by PhpStorm. * User: mac * Date: 2017/10/12 * Time: 下午5:49 */ namespace app\modules\admin\controllers; use app\models\Conf; use app\models\Coupon; use app\models\CouponItem; use app\models\Dish; use app\models\WechatPromotion; use Yii; use yii\base\Exception; use yii\data\ActiveDataProvider; use yii\helpers\ArrayHelper; class PromotionController extends N8Base { public $cMenu = [ 'default'=>[ 'promotion-index'=>['label'=>'促销简报','url'=>['/admin/promotion/index']], 'promotion-wechat'=>['label'=>'微信端特惠','url'=>['/admin/promotion/wechat']], 'promotion-coupon'=>['label'=>'优惠券','url'=>['/admin/promotion/coupon']], 'promotion-upoff'=>['label'=>'满减','url'=>['/admin/promotion/upoff']], ] ]; public function actionIndex(){ $this->menus = $this->cMenu['default']; $this->initActiveMenu('promotion-index'); return $this->render('index'); } /** * 微信端特惠 */ public function actionWechat(){ $model = new WechatPromotion(); if(Yii::$app->request->isPost){ $model->load(Yii::$app->request->post()); if($model->save()){ return $this->redirect(['/admin/promotion/wechat']); } } $query = WechatPromotion::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query ]); $this->menus = $this->cMenu['default']; $this->initActiveMenu('promotion-wechat'); return $this->render('wechat',[ 'dataProvider'=>$dataProvider, 'model'=>$model, 'dishes'=>ArrayHelper::map(Dish::find()->all(),'id','title') ]); } public function actionUpdateWechat($id){ $model = WechatPromotion::findOne($id); if(Yii::$app->request->isPost){ $model->load(Yii::$app->request->post()); if($model->save()){ return $this->redirect(['/admin/promotion/wechat']); } } $this->menus = $this->cMenu['default']; $menu = ['label'=>'更新微信特惠','url'=>['/admin/promotion/update-wechat','id'=>$id]]; $this->initActiveMenu('promotion-update-wechat',$menu); return $this->render('update-wechat',[ 'model'=>$model, 'dishes'=>ArrayHelper::map(Dish::find()->all(),'id','title') ]); } public function actionDeleteWechat($id){ Yii::$app->response->format = 'json'; try { $model = WechatPromotion::findOne($id); $model->delete(); return ['done'=>true,'data'=>'删除成功']; }catch(Exception $e){ return ['done'=>false,'error'=>$e->getMessage()]; } } public function actionCoupon(){ $model = new Coupon(); if(Yii::$app->request->isPost){ $model->load(Yii::$app->request->post()); // $model->begin_at = strtotime($model->begin_at); $model->end_at = empty($model->end_at) ? 0 : strtotime($model->end_at); if($model->save()){ CouponItem::initCouponItems($model->id); return $this->redirect(['/admin/promotion/coupon']); } } $query = Coupon::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query ]); $this->menus = $this->cMenu['default']; $this->initActiveMenu('promotion-coupon'); return $this->render('coupon',[ 'model'=>$model, 'dataProvider'=>$dataProvider ]); } public function actionUpdateCoupon($id){ $model = Coupon::findOne($id); if(Yii::$app->request->isPost){ $model->load(Yii::$app->request->post()); $model->begin_at = strtotime($model->begin_at); $model->end_at = empty($model->end_at) ? 0 : strtotime($model->end_at); if($model->save()){ CouponItem::initCouponItems($model->id); return $this->redirect(['/admin/promotion/coupon']); } } $model->begin_at = date('Y-m-d H:i:s',$model->begin_at); $model->end_at = empty($model->end_at) ? '' : date('Y-m-d H:i:s',$model->end_at); $this->menus = $this->cMenu['default']; $menu = ['label'=>'更新优惠券活动信息','url'=>['/admin/promotion/update-coupon','id'=>$id]]; $this->initActiveMenu('promotion-update-coupon',$menu); return $this->render('update-coupon',[ 'model'=>$model, ]); } public function actionDeleteCoupon($id){ Yii::$app->response->format = 'json'; try { $model = Coupon::findOne($id); $check = CouponItem::find()->where(['coupon_id'=>$id])->andWhere(['>','user_id',0])->count(); if($check>0){ throw new Exception("不允许删除,已经有人领取了某些优惠券"); } CouponItem::deleteAll(['coupon_id'=>$id]); $model->delete(); return ['done'=>true,'data'=>'删除成功']; }catch(Exception $e){ return ['done'=>false,'error'=>$e->getMessage()]; } } /** * 一个优惠券活动的券列表 * @param $id * @return string */ public function actionCouponItems($id){ $query = CouponItem::find()->where(['coupon_id'=>$id]); $dataProvider = new ActiveDataProvider([ 'query' => $query ]); $this->menus = $this->cMenu['default']; $menu = ['label'=>'券列表','url'=>['/admin/promotion/coupon-items','id'=>$id]]; $this->initActiveMenu('promotion-coupon-items',$menu); return $this->render('coupon-items',[ 'dataProvider'=>$dataProvider ]); } public function actionUpoff(){ $conf = Conf::readConf('up_off'); if(Yii::$app->request->isPost){ Yii::$app->response->format = 'json'; try { $state = Yii::$app->request->post('state'); $upMoney = Yii::$app->request->post('up_money'); $offMoney = Yii::$app->request->post('off_money'); $beginTime = Yii::$app->request->post('begin_time'); $endTime = Yii::$app->request->post('end_time'); //todo $conf = [ 'state'=>$state, 'up_money'=>$upMoney, 'off_money'=>$offMoney, 'begin_time'=>strtotime($beginTime), 'end_time'=>$endTime == 0 ? 0 : strtotime($endTime), ]; Conf::writeConf('up_off',$conf); return ['done'=>true]; }catch(Exception $e){ return ['done'=>false,'error'=>$e->getMessage()]; } } $this->menus = $this->cMenu['default']; $this->initActiveMenu('promotion-upoff'); return $this->render('upoff',[ 'conf'=>$conf ]); } }
--- id: getPrototypeOf title: Object.getPrototypeOf() --- ## 语法 ```ts getPrototypeOf(o: any): any; ``` ## 描述 该方法返回指定对象的原型(内部[[Prototype]]属性的值),即 `Object.getPrototypeOf(obj) === obj.__proto__` 返回 true. > TIP > > \_\_proto\_\_ 并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,虽然目前很多现代浏览器的 JS 引擎中都提供了这个私有属性,但依旧不建议在生产中使用该属性,避免对环境产生依赖。生产环境中,我们可以使用 > `Object.getPrototypeOf()` 来获取实例对象的原型,然后再来为原型添加方法/属性。 ## 示例 ```js function Animal(name) { this.name = name } Animal.prototype.say = function() { return `I'm ${this.name}` } function Cat(name, color) { // 继承属性 Animal.call(this, name) this.color = color } // 继承方法 Cat.prototype = new Animal() Cat.prototype.bark = function() { return '喵' } const persian = new Cat('咪咪', 'white') Object.getPrototypeOf(persian) === persian.__proto__ // true ``` 再看一个例子。 ```js const proto = {} const obj = Object.create(proto) Object.getPrototypeOf(obj) === proto // true ``` ## 扩展 Object.getPrototypeOf() 可用来判断 JavaScript 数据类型。 ```js Object.getPrototypeOf('') === String.prototype // true Object.getPrototypeOf(new String('')) === String.prototype // true Object.getPrototypeOf(/^$/) === RegExp.prototype // true Object.getPrototypeOf(/^$/) === Object.prototype // false ``` 通过前两个例子可以看出,该方法和 `Object.prototype.toString.call()` 有共同的缺点,就是无法正确分辨 **基本数据类型** 和 **引用类型**,因此请配合 **typeof** 一起使用。 关于判断数据类型的若干方法,可阅读我的文章 [JS 判断数据类型的多种方式](https://www.yanceyleo.com/p/5c84fb02a22a8632e5857b6d) ## 其他 在 ES5 中,如果参数不是一个对象类型,那么它会导致 TypeError。在 ES6+ 中,非对象参数被强制转换为对象。 ```js // TypeError: "foo" is not an object (ES5) Object.getPrototypeOf('foo') // ES6+ Object.getPrototypeOf('foo') // String.prototype ```
/* Controls the verbosity of the status log Default verbosity is zero, which is the least verbose messages. As the value increases, the amount of messages also increases. 0 - Normal logs 1 - More information on connections and error connections. 2 - Verbose Error messages 3 - Error messages about connections. */ const util = require('util') class LogsAdapter { constructor (localConfig = {}) { // Default to debugLevel 0 if not specified. this.debugLevel = localConfig.debugLevel if (!this.debugLevel) this.debugLevel = 0 this.logHandler = localConfig.statusLog if (!this.logHandler) { throw new Error( 'statusLog must be specified when instantiating Logs adapter library.' ) } } // Print out the data, if the log level is less than or equal to the debug // level set when instantiating the library. statusLog (level, str, object) { if (level <= this.debugLevel) { if (object === undefined) { this.logHandler('status: ' + str) } else { this.logHandler('status: ' + str + ' ' + util.inspect(object)) } } } } module.exports = LogsAdapter
# frozen_string_literal: true module Algebra class Monomial # Class of parsers, which take input string symbol by symbol, `nil` as EOF, # and return parsed monomial. Basic usage of the parsers is as the # following: # ``` # parser = Parser.new # string = " \t -123.4\t xy^2z^3\t t^6 " # string.each_char(&parser.method(:take)) # parser.take(nil) # parser.monomial # (-123.4, [:x, :y, :z, :t], [1, 2, 3, 6]) # ``` # # Parsers support the following rules. # # 1. A numeric coefficient can be provided in the start of string with # optional `+` or `-` sign. The coefficient can be integer (that is, # presented as a sequence of digits), or can have fractional part (dot # symbol `.` and another sequence of digits for the part). If the dot # symbol is provided, one of parts, integer or fractional, can be # empty, but not both. Examples of valid strings: # # * `123` -- positive integer; # * `-2` -- negative integer; # * `+1.5` -- positive number with fractional part; # * `-3.45` -- negative number with fractional part; # * `1.` -- positive number with present integer and absent fractional # parts; # * `-.1` -- negative number with absent integer and present # fractional parts. # # No whitespace is allowed between sign (if there is any), integer # part, dot,and fractional part, so the following examples are invalid # strings and would raise an exception during parsing: # # * `- 2`; # * `+ 1.5`; # * `-3. 45`; # * `1 .`; # * `- . 1`. # # Other examples of invalid strings: # # * `1 + 3i` -- complex numbers are unsupported; # * `0xFFF` -- only decimal digits are supported; # * `123,345` -- only dot is supported as delimiter between integer # and fractional parts; # * `.` -- both integer and fractional parts are empty. # # 2. One or many variable parts can be provided from the start of string, # after coefficient, or after another variable part. Variable part # consists of required name of variable (one symbol from `a`, ..., `z` # range) in the start and optional degree part after the name. The # degree part consists of `^` symbol in the start and a sequence of # digits after the symbol. The very first variable part in a string # without coefficient can have an optional `+` or `-` sign. Examples of # valid strings: # # * `x` -- just one variable part; # * `123x` -- one variable part after numeric coefficient; # * `+xy^2z^3` -- three variable parts, two of them with degree parts, # `+` sign in the start. # # Any number of spaces and tabular spaces is supported between # coefficient and first variable part, and also between variable parts, # so the following strings are valid too: # # * `123 x`; # * `+x y^2 z^3`. # # No whitespace is allowed between sign, if there is any, and first # variable part, between name and `^` symbol, if there is degree part, # between `^` and digits in degree part. Examples of invalid strings: # # * `- x`; # * `y^ 2`; # * `y ^23`. # # 3. Any number of spaces and tabular spaces is allowed in the start of # input string before sign, coefficient or first variable part, and in # its end after coefficient, if there is no variable parts, or last # variable part. But a coefficient or a variable part are required in # input string, so strings with just spaces and whitespaces are # invalid. # # 4. Default sign, if there is no any, is `+`. Default coefficient, if # there is no any, is 1. class Parser require_relative 'parser/state' require_relative 'parser/nodes/base/node' require_relative 'parser/nodes/begin' require_relative 'parser/nodes/deg' require_relative 'parser/nodes/dot' require_relative 'parser/nodes/end' require_relative 'parser/nodes/exp' require_relative 'parser/nodes/frac_part' require_relative 'parser/nodes/int_part' require_relative 'parser/nodes/sign' require_relative 'parser/nodes/var' require_relative 'parser/nodes/white' require_relative 'parser/errors' # Initializes instance of the class def initialize @state = State.new end # Routes input to current node in the state # @param [String, NilClass] input # input symbol or `nil` to signal EOF # @raise [Parser::Nodes::Base::Node::Errors::Input::NoProcessor] # if no processor found for the input def take(input) state.node.take(input, state) end # Returns parsed monomial # @return [Algebra::Monomial] # parsed monomial # @raise [Errors::Node::NotEnd] # if node in the parser's state is not {Nodes.end} def monomial raise Errors::Node::NotEnd, state unless state.node == Nodes.end Monomial.new(state.coef.to_f * state.mul, state.vars) end private # State of parser # @return [Algebra::Monomial::Parser::State] # state attr_reader :state end end end
package Tuba::DB::Object::ModelRun; # Tuba::DB::Mixin::Object::ModelRun; use Tuba::Util qw[new_uuid]; __PACKAGE__->meta->primary_key_generator(sub { return new_uuid(); }); 1;
#!/bin/bash # aliases.sh # Caleb Evans # Enable aliases to be run as root alias sudo='sudo ' mkcd() { mkdir -p "$1" && cd "$1" } # Colorize directory listings alias ls='ls --color=auto' alias l='ls -la --color=auto' # Colorize grep matches (but not for piped output) alias grep='grep --color=auto' alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' # Colorize diff output if type colordiff &> /dev/null; then alias diff='colordiff' fi # Colorize tree output if type tree &> /dev/null; then alias tree='tree -C' fi
# mudstring A C/C++ library for working with MUD/MUSH/MU* ANSI strings.
from . import Bench201 from . import BenchNatsss from .Networks import get_network, get_num_networks, get_search_space_names from .Metrics import get_metrics, get_metric_names
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. #include "SampleInputAsset.h" #include "ODBlock.h" #include <PsFile.h> using namespace SampleFramework; SampleInputAsset::SampleInputAsset(File* file, const char *path) : SampleAsset(SampleAsset::ASSET_INPUT, path) , m_SettingsBlock(NULL) , m_File(file) { m_SampleInputData.reserve(128); PX_ASSERT(file); if (!m_Mapping.loadScript(file)) { printf("ODS parse error: %s in file: %s\n", m_Mapping.lastError, path); PX_ASSERT(0); } m_SettingsBlock = m_Mapping.getBlock("InputMapping"); if (!m_SettingsBlock) { printf("No \"InputEventSettings\" block found!\n"); PX_ASSERT(0); } else { LoadData(m_SettingsBlock); } } SampleInputAsset::~SampleInputAsset() { if(m_File) { fclose(m_File); } } void SampleInputAsset::LoadData(ODBlock* odsSettings) { odsSettings->reset(); while (odsSettings->moreSubBlocks()) { ODBlock* subBlock = odsSettings->nextSubBlock(); subBlock->reset(); SampleInputData inputData; if (!strcmp(subBlock->ident(), "map")) { if (subBlock->moreTerminals()) { const char* p = subBlock->nextTerminal(); strcpy(inputData.m_UserInputName, p); } if (subBlock->moreTerminals()) { const char* p = subBlock->nextTerminal(); strcpy(inputData.m_InputEventName, p); } m_SampleInputData.push_back(inputData); } } } bool SampleInputAsset::isOk(void) const { return true; }
#[cfg(not(feature = "std"))] use crate::simulate_std::prelude::*; use bytes::Bytes; use core::fmt; use crate::{command::common::PbToBytes, pb::msg}; #[derive(Default, Debug, Clone)] pub struct FriendImage { pub image_id: String, pub md5: Bytes, pub size: i32, pub url: String, pub flash: bool, } impl From<FriendImage> for Vec<msg::elem::Elem> { fn from(i: FriendImage) -> Vec<msg::elem::Elem> { let image = msg::NotOnlineImage { file_path: Some(i.image_id.clone()), res_id: Some(i.image_id.clone()), old_pic_md5: Some(false), pic_md5: Some(i.md5.to_vec()), download_path: Some(i.image_id), original: Some(1), pb_reserve: Some(vec![0x78, 0x02]), ..Default::default() }; if i.flash { let flash = msg::MsgElemInfoServtype3 { flash_c2c_pic: Some(image), ..Default::default() } .to_bytes(); let flash_elem = msg::elem::Elem::CommonElem(msg::CommonElem { service_type: Some(3), pb_elem: Some(flash.to_vec()), ..Default::default() }); let text_hint = msg::elem::Elem::Text(msg::Text { str: Some("[闪照]请使用新版手机QQ查看闪照。".to_owned()), ..Default::default() }); vec![flash_elem, text_hint] } else { vec![msg::elem::Elem::NotOnlineImage(image)] } } } impl From<msg::NotOnlineImage> for FriendImage { fn from(e: msg::NotOnlineImage) -> Self { let url = if let Some(orig_url) = &e.orig_url { format!("https://c2cpicdw.qpic.cn{}", orig_url) } else { let download_path = if let Some(path) = &e.download_path { path } else { e.res_id() }; format!( "https://c2cpicdw.qpic.cn/offpic_new/0{}{}/0?term=3", if !download_path.starts_with('/') { "/" } else { "" }, download_path ) }; Self { image_id: e.file_path().to_owned(), size: e.file_len(), url, md5: Bytes::copy_from_slice(e.pic_md5()), flash: false, } } } impl TryFrom<msg::CommonElem> for FriendImage { type Error = msg::CommonElem; fn try_from(e: msg::CommonElem) -> Result<Self, Self::Error> { if let Ok(flash) = msg::MsgElemInfoServtype3::from_bytes(e.pb_elem()) { if let Some(p) = flash.flash_c2c_pic { let mut friend_image: FriendImage = p.into(); //todo:url check friend_image.flash = true; return Ok(friend_image); } } Err(e) } } impl fmt::Display for FriendImage { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[FriendImage: {}]", self.url) } }
create table S3ContentRepository( uuid char(36) not null primary key, accessKeyId varchar(32) not null, secretAccessKey varchar(64) not null, bucketName varchar(1024) not null, prefix varchar(1014) );