text
stringlengths
27
775k
################################################################################ # # Copyright (c) 2002-2020 Marcus Holland-Moritz. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the same terms as Perl itself. # ################################################################################ use Test; use Convert::Binary::C @ARGV; $^W = 1; BEGIN { plan tests => 49 } my $c = Convert::Binary::C->new( IntSize => 4, ShortSize => 2, Alignment => 4 ); $c->parse(<<ENDC); struct flex1 { int a; char b; struct { char a; short b; char c; int d[][4]; } c; char d[5]; struct { char a; short b[][4]; } e[]; }; struct flex2 { int a; struct { char a[2]; short b; } b[]; }; struct flex3 { int a; int b[][2][3][4]; }; typedef int incomplete[]; typedef int incomplete2[1]; ENDC ok($c->sizeof('flex1'), 24); ok($c->offsetof('flex1', 'e[1].a'), 24); ok($c->offsetof('flex1', 'e[0].b[0][0]'), 24); ok($c->sizeof('flex2'), 4); ok($c->offsetof('flex2', 'b[0].b'), 6); ok($c->sizeof('flex3'), 4); ok($c->sizeof('flex3.b'), 0); ok($c->sizeof('flex3.b[0]'), 96); ok($c->sizeof('flex3.b[0][1]'), 48); ok($c->sizeof('flex3.b[0][1][2]'), 16); ok($c->sizeof('flex3.b[0][1][2][3]'), 4); ok($c->offsetof('flex3', 'b[0]'), 4); ok($c->offsetof('flex3', 'b[0][0]'), 4); ok($c->offsetof('flex3', 'b[0][0][0]'), 4); ok($c->offsetof('flex3', 'b[0][0][0][0]'), 4); ok($c->offsetof('flex3', 'b[1]'), 100); ok($c->offsetof('flex3', 'b[0][1]'), 52); ok($c->offsetof('flex3', 'b[0][0][1]'), 20); ok($c->offsetof('flex3', 'b[0][0][0][1]'), 8); ok($c->sizeof('incomplete'), 0); ok($c->offsetof('incomplete', '[10]'), 40); my($u, $p); my $d = pack 'C*', 1 .. 4; $u = $c->unpack('flex2', $d); ok(scalar @{$u->{b}}, 0); $d .= pack 'C', 5; $u = $c->unpack('flex2', $d); ok(scalar @{$u->{b}}, 1); ok(scalar @{$u->{b}[0]{a}}, 2); ok($u->{b}[0]{a}[0], 5); ok(not defined $u->{b}[0]{b}); $d .= pack 'C', 6; $u = $c->unpack('flex2', $d); ok(scalar @{$u->{b}}, 1); ok(scalar @{$u->{b}[0]{a}}, 2); ok($u->{b}[0]{a}[0], 5); ok($u->{b}[0]{a}[1], 6); ok(not defined $u->{b}[0]{b}); $d .= pack 'C', 7; $u = $c->unpack('flex2', $d); ok(scalar @{$u->{b}}, 1); ok(scalar @{$u->{b}[0]{a}}, 2); ok($u->{b}[0]{a}[0], 5); ok($u->{b}[0]{a}[1], 6); ok(exists $u->{b}[0]{b}); ok(not defined $u->{b}[0]{b}); $d .= pack 'C', 8; $u = $c->unpack('flex2', $d); ok(scalar @{$u->{b}}, 1); ok(scalar @{$u->{b}[0]{a}}, 2); ok($u->{b}[0]{a}[0], 5); ok($u->{b}[0]{a}[1], 6); ok(exists $u->{b}[0]{b}); ok(defined $u->{b}[0]{b}); $d .= pack 'C', 9; $u = $c->unpack('flex2', $d); ok(scalar @{$u->{b}}, 2); $d = pack 'C*', map { $_ % 256 } 1 .. (10*$c->sizeof('flex3.b[0]')); $u = $c->unpack('flex3.b', $d); $p = $c->pack('flex3.b', $u); ok($d, $p); for my $member (qw( b[0] b[0][1] b[0][1][2] b[0][1][2][3] )) { $d = pack 'C*', 1 .. $c->sizeof("flex3.$member"); $u = $c->unpack("flex3.$member", $d); $p = $c->pack("flex3.$member", $u); ok($d, $p); }
#!/usr/bin/env bash # make sure error stop script set -e # Save some useful information REPO=`git config remote.origin.url` SSH_REPO=${REPO/https:\/\/github.com\//git@github.com:} HEAD_HASH=`git rev-parse --verify HEAD` # latest commit hash HEAD_HASH=${HEAD_HASH: -7} # get the last 7 characters of hash # install system dependencies sudo apt update sudo apt install -y ruby ruby-dev gem # install bundler sudo gem install bundler # install packages bundle install # remove old site rm -rf ./_site if [ "$CI" = true ]; then git config user.name "GitHub Action" git config user.email "user@example.com" fi git fetch git worktree add _site gh-pages # collect and build bundle exec rake collect bundle exec rake build (cd _site; git add .) (cd _site; git diff-index --quiet HEAD || git commit -am "Auto deploy commit ${HEAD_HASH} to GitHub Pages at ${date}") git push origin gh-pages
package data import ( "bytes" "fmt" "testing" "github.com/akrylysov/pogreb" "github.com/akrylysov/pogreb/fs" "github.com/stretchr/testify/assert" ) var testUser = User{UUID: "uuid11"} var testAccount1 = Account{ Name: "Test 1", Currency: "USD", IncludeInTotal: false, ShowInList: true, } var testAccount2 = Account{ Name: "Test 2", Currency: "EUR", IncludeInTotal: false, ShowInList: true, } var dbService *DBService func resetDb() (err error) { if dbService != nil { it := dbService.db.Items() for { k, _, err := it.Next() if err == pogreb.ErrIterationDone { break } else if err != nil { return err } err = dbService.db.Delete(k) if err != nil { return err } } return } opts := pogreb.Options{FileSystem: fs.Mem} dbService, err = Open(opts) return } func getAllUsers(s *DBService) ([]*User, error) { users := make([]*User, 0) it := s.db.Items() for { k, value, err := it.Next() if err == pogreb.ErrIterationDone { break } else if err != nil { return nil, err } if !bytes.HasPrefix(k, []byte(userKeyPrefix)) { continue } username, err := decodeUserKey(k) if err != nil { return nil, fmt.Errorf("failed to decode username from key %v: %w", string(k), err) } user := &User{} if err := user.decode(value); err != nil { return nil, fmt.Errorf("failed to read value of user %v: %w", username, err) } user.username = *username users = append(users, user) } return users, nil } func createTestAccounts(s *DBService) error { saveUser := testUser saveAccount := testAccount1 if err := s.CreateAccount(&saveUser, &saveAccount); err != nil { return err } testAccount1.UUID = saveAccount.UUID saveAccount = testAccount2 if err := s.CreateAccount(&saveUser, &saveAccount); err != nil { return err } testAccount2.UUID = saveAccount.UUID return nil } func assertIndexEquals(t *testing.T, prefix string, expectKeys ...string) { index, err := dbService.getReferencedKeys([]byte(testUser.createAccountKeyPrefix())) assert.NoError(t, err) indexValues := make([]string, len(index)) for i := range index { indexValues[i] = string(index[i]) } assert.ElementsMatch(t, expectKeys, indexValues) }
% Problem Solving with Prolog by John Stobo % terminating %query: hidden_flatten(i,o,o). hidden_flatten([],L,L). hidden_flatten([[H|T]|L],S,F) :- !, hidden_flatten(L,S,Lf), hidden_flatten([H|T],Lf,F). hidden_flatten([H|T],S,[H|L]) :- hidden_flatten(T,S,L).
#include <cmath> #include <cstdint> #include <cstdio> #ifdef __SSE2__ #include <emmintrin.h> #elif __ARM_NEON #include <arm_neon.h> #endif #include <random> #include "halide_blur.h" #include "halide_blur_classic_auto_schedule.h" #include "halide_blur_auto_schedule.h" #include "benchmark_util.h" #include "halide_benchmark.h" #include "HalideBuffer.h" namespace { using namespace Halide::Runtime; using namespace Halide::Tools; bool is_one(const char *key) { const char *value = getenv(key); return value && value[0] == '1' && value[1] == 0; } void blur_slow(const Buffer<uint16_t> &in, Buffer<uint16_t> &tmp, Buffer<uint16_t> &out) { for (int y = 0; y < tmp.height(); y++) for (int x = 0; x < tmp.width(); x++) tmp(x, y) = (in(x, y) + in(x+1, y) + in(x+2, y))/3; for (int y = 0; y < out.height(); y++) for (int x = 0; x < out.width(); x++) out(x, y) = (tmp(x, y) + tmp(x, y+1) + tmp(x, y+2))/3; } void blur_fast(const Buffer<uint16_t> &in, Buffer<uint16_t> &out) { #ifdef __SSE2__ __m128i one_third = _mm_set1_epi16(21846); #pragma omp parallel for for (int yTile = 0; yTile < out.height(); yTile += 32) { __m128i tmp[(128/8) * (32 + 2)]; for (int xTile = 0; xTile < out.width(); xTile += 128) { __m128i *tmpPtr = tmp; for (int y = 0; y < 32+2; y++) { const uint16_t *inPtr = &(in(xTile, yTile+y)); for (int x = 0; x < 128; x += 8) { __m128i a = _mm_load_si128((const __m128i*)(inPtr)); __m128i b = _mm_loadu_si128((const __m128i*)(inPtr+1)); __m128i c = _mm_loadu_si128((const __m128i*)(inPtr+2)); __m128i sum = _mm_add_epi16(_mm_add_epi16(a, b), c); __m128i avg = _mm_mulhi_epi16(sum, one_third); _mm_store_si128(tmpPtr++, avg); inPtr+=8; } } tmpPtr = tmp; for (int y = 0; y < 32; y++) { __m128i *outPtr = (__m128i *)(&(out(xTile, yTile+y))); for (int x = 0; x < 128; x += 8) { __m128i a = _mm_load_si128(tmpPtr+(2*128)/8); __m128i b = _mm_load_si128(tmpPtr+128/8); __m128i c = _mm_load_si128(tmpPtr++); __m128i sum = _mm_add_epi16(_mm_add_epi16(a, b), c); __m128i avg = _mm_mulhi_epi16(sum, one_third); _mm_store_si128(outPtr++, avg); } } } } #elif __ARM_NEON uint16x4_t one_third = vdup_n_u16(21846); #pragma omp parallel for for (int yTile = 0; yTile < out.height(); yTile += 32) { uint16x8_t tmp[(128/8) * (32 + 2)]; for (int xTile = 0; xTile < out.width(); xTile += 128) { uint16_t *tmpPtr = (uint16_t*)tmp; for (int y = 0; y < 32+2; y++) { const uint16_t *inPtr = &(in(xTile, yTile+y)); for (int x = 0; x < 128; x += 8) { uint16x8_t a = vld1q_u16(inPtr); uint16x8_t b = vld1q_u16(inPtr+1); uint16x8_t c = vld1q_u16(inPtr+2); uint16x8_t sum = vaddq_u16(vaddq_u16(a, b), c); uint16x4_t sumlo = vget_low_u16(sum); uint16x4_t sumhi = vget_high_u16(sum); uint16x4_t avglo = vshrn_n_u32(vmull_u16(sumlo, one_third), 16); uint16x4_t avghi = vshrn_n_u32(vmull_u16(sumhi, one_third), 16); uint16x8_t avg = vcombine_u16(avglo, avghi); vst1q_u16(tmpPtr, avg); tmpPtr+=8; inPtr+=8; } } tmpPtr = (uint16_t*)tmp; for (int y = 0; y < 32; y++) { uint16_t *outPtr = &(out(xTile, yTile+y)); for (int x = 0; x < 128; x += 8) { uint16x8_t a = vld1q_u16(tmpPtr+(2*128)); uint16x8_t b = vld1q_u16(tmpPtr+128); uint16x8_t c = vld1q_u16(tmpPtr); uint16x8_t sum = vaddq_u16(vaddq_u16(a, b), c); uint16x4_t sumlo = vget_low_u16(sum); uint16x4_t sumhi = vget_high_u16(sum); uint16x4_t avglo = vshrn_n_u32(vmull_u16(sumlo, one_third), 16); uint16x4_t avghi = vshrn_n_u32(vmull_u16(sumhi, one_third), 16); uint16x8_t avg = vcombine_u16(avglo, avghi); vst1q_u16(outPtr, avg); tmpPtr+=8; outPtr+=8; } } } } #else // No intrinsics enabled, do a naive thing. for (int y = 0; y < out.height(); y++) { for (int x = 0; x < out.width(); x++) { int tmp[3] = { (in(x, y) + in(x+1, y) + in(x+2, y))/3, (in(x, y+1) + in(x+1, y+1) + in(x+2, y+1))/3, (in(x, y+2) + in(x+1, y+2) + in(x+2, y+2))/3, }; out(x, y) = (tmp[0] + tmp[1] + tmp[2])/3; } } #endif } } // namespace int main(int argc, char **argv) { #ifndef HALIDE_RUNTIME_HEXAGON const int width = 6408; const int height = 4802; #else // The Hexagon simulator can't allocate as much memory as the above wants. const int width = 648; const int height = 482; #endif Buffer<uint16_t> input(width, height); Buffer<uint16_t> output(width-8, height-2); constexpr uint32_t seed = 0; std::mt19937 rng(seed); input.for_each_value([&rng](uint16_t &f) { f = rng() & 0xfff; }); // Timing code three_way_bench( [&]() { halide_blur(input, output); }, [&]() { halide_blur_classic_auto_schedule(input, output); }, [&]() { halide_blur_auto_schedule(input, output); } ); if (!is_one("HL_THREE_WAY_BENCH_SKIP_MANUAL")) { Buffer<uint16_t> out_slow(width-8, height-2); Buffer<uint16_t> out_fast(width-8, height-2); Halide::Tools::BenchmarkConfig config; config.accuracy = 0.005; Buffer<uint16_t> tmp(width-8, height); const auto f1 = [&]() { blur_slow(input, tmp, out_slow); out_slow.copy_to_host(); }; f1(); double t1 = Halide::Tools::benchmark(f1, config); std::cout << "'Slow' non-Halide time: " << t1 * 1e3 << " ms\n"; const auto f2 = [&]() { blur_fast(input, out_fast); out_fast.copy_to_host(); }; f2(); double t2 = Halide::Tools::benchmark(f2, config); std::cout << "'Fast' non-Halide time: " << t2 * 1e3 << " ms\n"; for (int y = 64; y < input.height() - 64; y++) { for (int x = 64; x < input.width() - 64; x++) { if (out_slow(x, y) != out_fast(x, y) || out_slow(x, y) != output(x, y)) { printf("difference at (%d,%d): %d %d %d\n", x, y, out_slow(x, y), out_fast(x, y), output(x, y)); abort(); } } } } return 0; }
package com.braunster.chatsdk.activities; /** * Created by DELL on 10/21/2017. */ import android.os.Handler; import android.os.SystemClock; import android.util.Log; public class RideTimer { /** Called when the activity is first created. */ private long startTime = 0L; private Handler myHandler = new Handler(); long timeInMillies = 0L; long timeSwap = 0L; long finalTime = 0L; public void starttime() { startTime = SystemClock.uptimeMillis(); myHandler.postDelayed(updateTimerMethod, 0); } public void stoptime() { timeSwap += timeInMillies; myHandler.removeCallbacks(updateTimerMethod); } private Runnable updateTimerMethod = new Runnable() { public void run() { timeInMillies = SystemClock.uptimeMillis() - startTime; finalTime = timeSwap + timeInMillies; int seconds = (int) (finalTime / 1000); int minutes = seconds / 60; seconds = seconds % 60; int milliseconds = (int) (finalTime % 1000); FirstMainActivity.counttime.setText("" + minutes + ":" + String.format("%02d", seconds) + ":" + String.format("%03d", milliseconds)); myHandler.postDelayed(this, 0); } }; }
use std::fmt; use crc::crc32::Hasher32; use crc::crc32::Digest; use crc::crc32::IEEE; use crc::crc32::CASTAGNOLI; use crc::crc32::KOOPMAN; use prelude::*; use util::fmt_slice2hex; // ------------------------------------------------------------------------------------------------- #[derive(Debug, Default, Clone, Copy)] pub struct Crc32Ieee(); impl MTAlgorithm for Crc32Ieee { type Value = Crc32Value; type Context = Crc32IeeeContext; } // ------------------------------------------------------------------------------------------------- impl MTContext for Crc32IeeeContext { type Out = Crc32Value; fn new() -> Self { Crc32IeeeContext::default() } fn update(&mut self, msg: &[u8]) { self.context.write(msg) } fn finish(self) -> Self::Out { let digest = self.context.sum32(); Crc32Value(unsafe { ::std::mem::transmute(digest.to_be()) }) } } //#[derive(Clone)] pub struct Crc32IeeeContext { context: Digest, } impl Default for Crc32IeeeContext { fn default() -> Self { Crc32IeeeContext { context: Digest::new(IEEE), } } } impl fmt::Debug for Crc32IeeeContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "mt::fun::Crc32IeeeContext{{context: crc::crc32::Digest}}") } } // ------------------------------------------------------------------------------------------------- #[derive(Debug, Default, Clone, Copy)] pub struct Crc32Castagnoli(); impl MTAlgorithm for Crc32Castagnoli { type Value = Crc32Value; type Context = Crc32CastagnoliContext; } // ------------------------------------------------------------------------------------------------- impl MTContext for Crc32CastagnoliContext { type Out = Crc32Value; fn new() -> Self { Crc32CastagnoliContext::default() } fn update(&mut self, msg: &[u8]) { self.context.write(msg) } fn finish(self) -> Self::Out { let digest = self.context.sum32(); Crc32Value(unsafe { ::std::mem::transmute(digest.to_be()) }) } } //#[derive(Clone)] pub struct Crc32CastagnoliContext { context: Digest, } impl Default for Crc32CastagnoliContext { fn default() -> Self { Crc32CastagnoliContext { context: Digest::new(CASTAGNOLI), } } } impl fmt::Debug for Crc32CastagnoliContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "mt::fun::Crc32CastagnoliContext{{context: crc::crc32::Digest}}") } } // ------------------------------------------------------------------------------------------------- #[derive(Debug, Default, Clone, Copy)] pub struct Crc32Koopman(); impl MTAlgorithm for Crc32Koopman { type Value = Crc32Value; type Context = Crc32KoopmanContext; } // ------------------------------------------------------------------------------------------------- impl MTContext for Crc32KoopmanContext { type Out = Crc32Value; fn new() -> Self { Crc32KoopmanContext::default() } fn update(&mut self, msg: &[u8]) { self.context.write(msg) } fn finish(self) -> Self::Out { let digest = self.context.sum32(); Crc32Value(unsafe { ::std::mem::transmute(digest.to_be()) }) } } //#[derive(Clone)] pub struct Crc32KoopmanContext { context: Digest, } impl Default for Crc32KoopmanContext { fn default() -> Self { Crc32KoopmanContext { context: Digest::new(KOOPMAN), } } } impl fmt::Debug for Crc32KoopmanContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "mt::fun::Crc32KoopmanContext{{context: crc::crc32::Digest}}") } } // ------------------------------------------------------------------------------------------------- #[derive(Clone, Copy, PartialEq, Eq)] pub struct Crc32Value(pub [u8; 4]); impl fmt::Debug for Crc32Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CRC32:")?; fmt_slice2hex(f, &self.0[..]) } } impl MTHash for Crc32Value { fn hash<H: MTContext>(&self, state: &mut H) { state.update(self.0.as_ref()) } } #[cfg(test)] mod tests { use abc::MTAlgorithm; use super::Crc32Ieee; use super::Crc32Castagnoli; use super::Crc32Koopman; #[test] fn crc32_works() { let result = Crc32Ieee::eval_hash(&b"123".as_ref()); let as_string = format!("{:?}", result); let sample = "CRC32:884863d2"; assert_eq!(as_string, sample); let result = Crc32Ieee::eval_hash(&result); let as_string = format!("{:?}", result); let sample = "CRC32:512d162c"; assert_eq!(as_string, sample); let result = Crc32Castagnoli::eval_hash(&b"123".as_ref()); let as_string = format!("{:?}", result); let sample = "CRC32:107b2fb2"; assert_eq!(as_string, sample); let result = Crc32Castagnoli::eval_hash(&result); let as_string = format!("{:?}", result); let sample = "CRC32:ee23e9ca"; assert_eq!(as_string, sample); let result = Crc32Koopman::eval_hash(&b"123".as_ref()); let as_string = format!("{:?}", result); let sample = "CRC32:6bd5eae9"; assert_eq!(as_string, sample); let result = Crc32Koopman::eval_hash(&result); let as_string = format!("{:?}", result); let sample = "CRC32:e05b34cd"; assert_eq!(as_string, sample); } }
# Web Components - Master Badge ![Web Components Badge](../../img/badges/WebComponents.png "Performance - Apprentice Badge") ----- ## Goal - You have already completed the Apprentice and Journeyman levels of this category, to be sure you are properly prepared to mentor others as a master. - You have demonstrated that you have mentored & taught others how to improve their usage of the web components APIs. - You have demonstrated that you have a master-level understanding and skill in the topic. - You have sought out and obtained newly relevant & advanced knowledge on the topic. - You have completed project work that furthers our discipline in the topic. ----- ## Project Plan(s) **Create a project plan that outlines:** 1) What you wish to build 2) Why it is important 3) How it will benefit our discipline - [ ] Have your project plan approved by a master in this skill - [ ] Complete your project and present your learning to a gathering of web developers - [ ] Live as legend and mentor for others in this category ----- ## Current Web Components Masters: ----- *Is this badge missing something? Submit a PR and review it with a master in this category*
package discord import ( "context" "fmt" "github.com/bwmarrin/discordgo" "github.com/leighmacdonald/gbans/internal/config" "github.com/leighmacdonald/gbans/internal/model" "github.com/leighmacdonald/gbans/pkg/logparse" "github.com/leighmacdonald/gbans/pkg/util" "github.com/leighmacdonald/steamid/v2/steamid" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "strings" "sync" "time" ) var ( dg *discordgo.Session connectedMu *sync.RWMutex connected = false errCommandFailed = errors.New("Command failed") errTooLarge = errors.Errorf("Max message length is %d", discordMaxMsgLen) ) func Start(ctx context.Context, token string, eventChan chan model.ServerEvent) { d, err := discordgo.New("Bot " + token) if err != nil { log.Errorf("Failed to connect to dg. Bot unavailable") return } defer func() { if errDisc := dg.Close(); errDisc != nil { log.Errorf("Failed to cleanly shutdown discord: %v", errDisc) } }() dg = d dg.UserAgent = "gbans (https://github.com/leighmacdonald/gbans)" dg.AddHandler(onReady) dg.AddHandler(onConnect) dg.AddHandler(onDisconnect) dg.AddHandler(onInteractionCreate) // In this example, we only care about receiving message events. dg.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsGuildMessages) // Open a websocket connection to Discord and begin listening. err = dg.Open() if err != nil { log.Fatalf("Error opening discord connection: %v,", err) return } go discordMessageQueueReader(ctx, eventChan) if err2 := botRegisterSlashCommands(); err2 != nil { log.Errorf("Failed to register discord slash commands: %v", err2) } <-ctx.Done() } // discordMessageQueueReader functions by registering event handlers for the two user message events // Discord will rate limit you once you start approaching 5-10 servers of active users. Because of this // we queue messages and periodically send them out as multiline string blocks instead. func discordMessageQueueReader(ctx context.Context, eventChan chan model.ServerEvent) { messageTicker := time.NewTicker(time.Second * 10) var sendQueue []string for { select { case dm := <-eventChan: prefix := "" if dm.EventType == logparse.SayTeam { prefix = "(team) " } name := "" sid := steamid.SID64(0) if dm.Source != nil && dm.Source.SteamID.Valid() { sid = dm.Source.SteamID name = dm.Source.PersonaName } sendQueue = append(sendQueue, fmt.Sprintf("[%s] %d **%s** %s%s", dm.Server.ServerName, sid, name, prefix, dm.Extra)) case <-messageTicker.C: if len(sendQueue) == 0 { continue } msg := strings.Join(sendQueue, "\n") for _, m := range util.StringChunkDelimited(msg, discordWrapperTotalLen) { for _, channelID := range config.Relay.ChannelIDs { if err := sendChannelMessage(dg, channelID, m, true); err != nil { log.Errorf("Failed to send bulk message log: %v", err) } } } sendQueue = nil case <-ctx.Done(): return } } } func onReady(_ *discordgo.Session, _ *discordgo.Ready) { log.Infof("Bot is connected & ready") } func onConnect(s *discordgo.Session, _ *discordgo.Connect) { log.Info("Connected to session ws API") d := discordgo.UpdateStatusData{ IdleSince: nil, Activities: []*discordgo.Activity{ { Name: "Cheeseburgers", Type: discordgo.ActivityTypeStreaming, URL: "https://" + config.HTTP.Addr(), State: "state field", Details: "Blah", Instance: true, Flags: 1 << 0, }, }, AFK: false, Status: "https://github.com/leighmacdonald/gbans", } if err := s.UpdateStatusComplex(d); err != nil { log.WithError(err).Errorf("Failed to update status complex") } connectedMu.Lock() connected = true connectedMu.Unlock() } func onDisconnect(_ *discordgo.Session, _ *discordgo.Disconnect) { connectedMu.Lock() connected = false connectedMu.Unlock() log.Info("Disconnected from session ws API") } func sendChannelMessage(s *discordgo.Session, c string, msg string, wrap bool) error { connectedMu.RLock() if !connected { connectedMu.RUnlock() log.Warnf("Tried to send message to disconnected client") return nil } connectedMu.RUnlock() if wrap { msg = discordMsgWrapper + msg + discordMsgWrapper } if len(msg) > discordMaxMsgLen { return errTooLarge } _, err := s.ChannelMessageSend(c, msg) if err != nil { return errors.Wrapf(err, "Failed sending success (paged) response for interaction") } return nil } func sendInteractionMessageEdit(s *discordgo.Session, i *discordgo.Interaction, msg string) error { connectedMu.RLock() if !connected { connectedMu.RUnlock() log.Warnf("Tried to send message to disconnected client") return nil } connectedMu.RUnlock() msg = discordMsgWrapper + msg + discordMsgWrapper if len(msg) > discordMaxMsgLen { return errTooLarge } return s.InteractionResponseEdit(config.Discord.AppID, i, &discordgo.WebhookEdit{Content: msg}) } func Send(channelId string, message string, wrap bool) error { return sendChannelMessage(dg, channelId, message, wrap) } func init() { connectedMu = &sync.RWMutex{} }
// © 2022 Adrian Clark // This file is licensed to you under the MIT license. namespace Aydsko.iRacingData.Common; internal class LinkResult { [JsonPropertyName("link")] public string Link { get; set; } = default!; } [JsonSerializable(typeof(LinkResult)), JsonSourceGenerationOptions(WriteIndented = true)] internal partial class LinkResultContext : JsonSerializerContext { }
// Copyright © Amer Koleci and Contributors. // Licensed under the MIT License (MIT). See LICENSE in the repository root for more information. #pragma once #include "Core/RefCount.h" #include "Graphics/PixelFormat.h" #include "Math/Color.h" namespace Alimer { /* Constants */ static constexpr uint32_t kMaxFramesInFlight = 2; static constexpr uint32_t kMaxColorAttachments = 8; static constexpr uint32_t kMaxViewportsAndScissors = 8; static constexpr uint32_t kMaxVertexBufferBindings = 8; static constexpr uint32_t kMaxVertexAttributes = 16; static constexpr uint32_t kMaxVertexAttributeOffset = 2047u; static constexpr uint32_t kMaxVertexBufferStride = 2048u; static constexpr uint32_t kMaxCommandLists = 32u; static constexpr uint32_t kMaxConstantBufferBindings = 14u; static constexpr uint32_t kMaxSRVBindings = 128u; static constexpr uint32_t kMaxSamplerBindings = 16u; //static constexpr uint32_t kMaxDescriptorBindings = 32; static constexpr uint32_t kInvalidBindlessIndex = static_cast<uint32_t>(-1); static constexpr uint32_t kAllMipLevels = static_cast<uint32_t>(-1); static constexpr uint32_t kAllArraySlices = static_cast<uint32_t>(-1); /* Enums */ enum class GraphicsAPI : uint8_t { Vulkan, Direct3D12, Count }; enum class ShaderFormat : uint8_t { DXIL = 0, SPIRV, }; enum class ValidationMode : uint32_t { /// No validation is enabled. Disabled, /// Print warnings and errors Enabled, /// Print all warnings, errors and info messages Verbose, /// Enable GPU-based validation GPU }; enum class GPUAdapterType : uint8_t { Unknown, Software, Integrated, Discrete, }; enum class GPUVendorId : uint32_t { /// Adapter vendor is unknown Unknown = 0, /// Adapter vendor is NVidia Nvidia = 0x10DE, /// Adapter vendor is AMD AMD = 0x1002, /// Adapter vendor is Intel Intel = 0x8086, /// Adapter vendor is ARM ARM = 0x13B5, /// Adapter vendor is Imagination Technologies ImgTec = 0x1010, /// Adapter vendor is Qualcomm Qualcomm = 0x5143, /// Adapter vendor is Samsung Samsung = 0x1099, /// Adapter vendor is Microsoft (software rasterizer) Microsoft = 0x1414, /// Adapter vendor is Apple Apple = 0x0106B, /// Adapter vendor is Mesa (software rasterizer) Mesa = 0x10005, /// Adapter vendor is Broadcom (Raspberry Pi) Broadcom = 0x014e4, }; enum class QueueType : uint8_t { Graphics, Compute, Count }; enum class ResourceStates : uint32_t { Undefined = 0, Common = 0x00000001, ConstantBuffer = 0x00000002, VertexBuffer = 0x00000004, IndexBuffer = 0x00000008, IndirectArgument = 0x00000010, ShaderResource = 0x00000020, UnorderedAccess = 0x00000040, RenderTarget = 0x00000080, DepthWrite = 0x00000100, DepthRead = 0x00000200, StreamOut = 0x00000400, CopyDest = 0x00000800, CopySource = 0x00001000, ResolveDest = 0x00002000, ResolveSource = 0x00004000, Present = 0x00008000, AccelStructRead = 0x00010000, AccelStructWrite = 0x00020000, AccelStructBuildInput = 0x00040000, AccelStructBuildBlas = 0x00080000, ShadingRateSurface = 0x00100000, }; ALIMER_DEFINE_ENUM_BITWISE_OPERATORS(ResourceStates); enum class SampleCount : uint8_t { None = 0, Count1 = 1, Count2 = 2, Count4 = 4, Count8 = 8, Count16 = 16, Count32 = 32, Count64 = 64, All = (Count64 << 1) - 1, }; enum class BufferUsage : uint32_t { None = 0, MapRead = 1 << 0, MapWrite = 1 << 1, Index = 1 << 2, Vertex = 1 << 3, Constant = 1 << 4, ShaderRead = 1 << 5, ShaderWrite = 1 << 6, ShaderReadWrite = ShaderRead | ShaderWrite, /// Supports indirect buffer access for indirect draw/dispatch. Indirect = 1 << 7, /// Supports predication access for conditional rendering. Predication = 1 << 8, /// Supports ray tracing acceleration structure usage. RayTracingAccelerationStructure = 1 << 9, /// Supports ray tracing shader table usage. RayTracingShaderTable = 1 << 10, }; ALIMER_DEFINE_ENUM_BITWISE_OPERATORS(BufferUsage); enum class CompareFunction : uint32_t { Never = 0, Less, Equal, LessEqual, Greater, NotEqual, GreaterEqual, Always, }; enum class VertexStepRate : uint32_t { Vertex = 0, Instance = 1 }; enum class PrimitiveTopology : uint32_t { PointList, LineList, LineStrip, TriangleList, TriangleStrip, Patches1, Patches2, Patches3, Patches4, Patches5, Patches6, Patches7, Patches8, Patches9, Patches10, Patches11, Patches12, Patches13, Patches14, Patches15, Patches16, Patches17, Patches18, Patches19, Patches20, Patches21, Patches22, Patches23, Patches24, Patches25, Patches26, Patches27, Patches28, Patches29, Patches30, Patches31, Patches32, Count }; enum class VertexAttributeLocation : uint32_t { Position = 0, Normal = 1, Tangent = 2, Color = 3, TexCoord0 = 4, TexCoord1 = 5, TexCoord2 = 6, TexCoord3 = 7, TexCoord4 = 8, TexCoord5 = 9, TexCoord6 = 10, TexCoord7 = 11, BlendWeight = 12, BlendIndices = 13, Count }; enum class VertexFormat : uint32_t { Undefined = 0, UChar2, UChar4, Char2, Char4, UChar2Norm, UChar4Norm, Char2Norm, Char4Norm, UShort2, UShort4, Short2, Short4, UShort2Norm, UShort4Norm, Short2Norm, Short4Norm, Half2, Half4, Float, Float2, Float3, Float4, UInt, UInt2, UInt3, UInt4, Int, Int2, Int3, Int4, }; enum class IndexType : uint32_t { UInt16 = 0, UInt32 }; enum class LoadAction : uint32_t { Clear, Load, Discard, }; enum class StoreAction : uint32_t { Store, Discard, }; enum class ShaderStages : uint32_t { None = 0x0000, Vertex = 0x0001, Hull = 0x0002, Domain = 0x0004, Geometry = 0x0008, Fragment = 0x0010, Compute = 0x0020, Amplification = 0x0040, Mesh = 0x0080, AllGraphics = 0x00FE, All = 0x3FFF, }; ALIMER_DEFINE_ENUM_BITWISE_OPERATORS(ShaderStages); enum class PresentMode : uint32_t { Immediate = 0, Mailbox, Fifo }; /* Forward declarations */ class Buffer; class Texture; class TextureView; class Sampler; class Shader; class SwapChain; using BufferRef = RefPtr<Buffer>; using TextureRef = RefPtr<Texture>; using SamplerRef = RefPtr<Sampler>; using ShaderRef = RefPtr<Shader>; using SwapChainRef = RefPtr<SwapChain>; /* Structs */ struct BufferDescriptor { const char* label = nullptr; uint64_t size = 0; BufferUsage usage = BufferUsage::None; }; struct ShaderStage { ShaderStages stage = ShaderStages::None; std::vector<u8> bytecode; }; using ShaderStageList = std::vector<ShaderStage>; struct VertexBufferLayout { uint32_t stride = 0; VertexStepRate stepRate = VertexStepRate::Vertex; }; struct VertexAttribute { VertexAttributeLocation location = VertexAttributeLocation::Position; VertexFormat format = VertexFormat::Undefined; uint32_t offset = 0; uint32_t bufferIndex = 0; }; struct VertexLayout { VertexBufferLayout buffers[kMaxVertexBufferBindings]; VertexAttribute attributes[kMaxVertexAttributes]; }; struct DispatchIndirectCommand { uint32_t x; uint32_t y; uint32_t z; }; struct DrawIndexedIndirectCommand { uint32_t indexCount; uint32_t instanceCount; uint32_t firstIndex; int32_t vertexOffset; uint32_t firstInstance; }; struct DrawIndirectCommand { uint32_t vertexCount; uint32_t instanceCount; uint32_t firstVertex; uint32_t firstInstance; }; class ALIMER_API GPUObject2 : public RefCounted { protected: GPUObject2() = default; virtual ~GPUObject2() = default; public: // Non-copyable and non-movable GPUObject2(const GPUObject2&) = delete; GPUObject2(const GPUObject2&&) = delete; GPUObject2& operator=(const GPUObject2&) = delete; GPUObject2& operator=(const GPUObject2&&) = delete; }; class ALIMER_API GPUResource : public GPUObject2 { }; class ALIMER_API GPUShaderModule : public GPUObject2 { public: [[nodiscard]] virtual ShaderStages GetStage() const = 0; }; /* Helper methods */ ALIMER_API const char* ToString(GPUVendorId vendorId); ALIMER_API const char* ToString(GPUAdapterType type); ALIMER_API const char* ToString(CompareFunction func); ALIMER_API const char* ToString(ShaderStages stage); enum class VertexFormatBaseType { Float, Uint, Sint, }; struct VertexFormatInfo { VertexFormat format; uint32_t byteSize; uint32_t componentCount; uint32_t componentByteSize; VertexFormatBaseType baseType; }; ALIMER_API const VertexFormatInfo& GetVertexFormatInfo(VertexFormat format); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PusherServer { /// <summary> /// A Web Hook Event /// </summary> public class WebHookEvent { } }
import Element from "./Element.js" export default class Social extends Element{ constructor(title,list){ super() var t = document.createElement("div"); t.innerHTML = title; t.style.textAlign= "right"; t.style.fontWeight = "bold"; t.style.paddingTop = "5px" for (let node of list){ if(!node.href || !node.innerHTML) continue; this._el.appendChild(this.socialIcon(node.innerHTML,node.href)) } this._el.appendChild(t); //title appended last because we're in float:right } socialIcon(name,target){ var d = document.createElement("DIV"); var l = document.createElement("A"); var c = document.createElement("DIV"); d.className = "rs"; l.target = "_blank" l.href = target; l.title = name; c.style.backgroundImage = 'url("/data/sprites/'+name.toLowerCase()+'.png")'; c.id=encodeURIComponent(name); l.appendChild(c); d.appendChild(l); return d } }
var searchData= [ ['tsc_5fseed',['tsc_seed',['../d2/dfe/structrng_1_1tsc__seed.html',1,'rng']]] ];
@extends('restricted.layout.site') @section('title', 'Criar Cliente') @section('content') <div aria-label="breadcrumb" style="margin:30px;"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{{ route('user.homePanel') }}">Home</a></li> <li class="breadcrumb-item"><a href="{{ route('customer.all') }}">Cliente</a></li> <li class="breadcrumb-item active" aria-current="page"><a href="javascript:void(0);">Criando Cliente</a></li> </ol> </div> <h3 class="TitleSection">Adicionando Cliente</h3> <div class="row formUsers"> <form class="col-md-12" method="post" action="{{ route('customer.save') }}"> {{ csrf_field() }} @include('restricted.modules.customers._form') <button type="submit" class="btn btn-outline-primary btn-lg">Salvar</button> </form> </div> @endsection
""" Set the contents of variables and registers using raw data """ import os, time import unittest2 import lldb from lldbtest import * import lldbutil @skipUnlessDarwin class SetDataTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @dsym_test def test_set_data_dsym(self): """Test setting the contents of variables and registers using raw data.""" self.buildDsym() self.setData() def setData(self): """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("br s -p First"); self.runCmd("br s -p Second"); self.runCmd("run", RUN_SUCCEEDED) self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['2']) process = self.dbg.GetSelectedTarget().GetProcess() frame = process.GetSelectedThread().GetFrameAtIndex(0) x = frame.FindVariable("myFoo").GetChildMemberWithName("x") my_data = lldb.SBData.CreateDataFromSInt32Array(lldb.eByteOrderLittle, 8, [4]) err = lldb.SBError() self.assertTrue (x.SetData(my_data, err)) self.runCmd("continue") self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['4']) frame = process.GetSelectedThread().GetFrameAtIndex(0) x = frame.FindVariable("string") if process.GetAddressByteSize() == 8: my_data = lldb.SBData.CreateDataFromUInt64Array(process.GetByteOrder(), 8, [0]) else: my_data = lldb.SBData.CreateDataFromUInt32Array(process.GetByteOrder(), 4, [0]) err = lldb.SBError() self.assertTrue (x.SetData(my_data, err)) self.expect("fr var -d run-target string", VARIABLES_DISPLAYED_CORRECTLY, substrs = ['NSString *', 'nil']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
package db import ( "database/sql" "fmt" "log" _ "github.com/mattn/go-sqlite3" ) var ( db *sql.DB dbPath = "./todo.db" queries = map[string]string{} prep = map[string]*sql.Stmt{} ) func Load() { var err error db, err = sql.Open("sqlite3", dbPath) if err != nil { log.Fatalf("unable to open db: %q", err) } err = createSchema() if err != nil { log.Fatalf("unable to create schema: %q", err) } } func Close() { db.Close() } func createSchema() error { _, err := db.Exec(`CREATE TABLE IF NOT EXISTS todos ( id INTEGER NOT NULL PRIMARY KEY, text TEXT, done INTEGER);`) return err } func getPrep(name string) (*sql.Stmt, error) { if p, ok := prep[name]; ok { return p, nil } if s, ok := queries[name]; ok { p, err := db.Prepare(s) if err != nil { return nil, fmt.Errorf("can't prepare %q: %q", s, err) } prep[name] = p return p, nil } return nil, fmt.Errorf("no query named %q is defined", name) }
package com.github.bordertech.webfriends.api.common.context; /** * Element with a custom context (marker interface). */ public interface CustomContext extends AllowedContext { }
// Credit: // https://github.com/davidtheclark/tabbable const candidateSelector = 'input,select,textarea,a[href],button,[tabindex],' + 'audio[controls],video[controls],' + '[contenteditable]:not([contenteditable="false"])' export interface Tabbables { documentOrder: number tabIndex: number node: HTMLElement | HTMLInputElement } const matches: Element['matches'] = typeof Element === 'undefined' ? () => false : Element.prototype.matches || // @ts-ignore Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector const tabbable = (el: HTMLElement, includeRootNode = false): HTMLElement[] => { const regularTabbables: HTMLElement[] = [] const orderedTabbables: Tabbables[] = [] let candidates: HTMLElement[] | NodeListOf<HTMLElement> = el.querySelectorAll( candidateSelector ) if (includeRootNode && matches.call(el, candidateSelector)) { candidates = Array.prototype.slice.apply(candidates) as HTMLElement[] candidates.unshift(el) } let i, candidate, candidateTabindex for (i = 0; i < candidates.length; i++) { candidate = candidates[i] if (!isNodeMatchingSelectorTabbable(candidate)) continue candidateTabindex = getTabindex(candidate) if (candidateTabindex === 0) { regularTabbables.push(candidate) } else { orderedTabbables.push({ documentOrder: i, tabIndex: candidateTabindex, node: candidate, }) } } return orderedTabbables .sort(sortOrderedTabbables) .map((a) => a.node) .concat(regularTabbables) } const isNodeMatchingSelectorTabbable = (node: HTMLElement) => !( !isNodeMatchingSelectorFocusable(node) || (node.tagName === 'INPUT' && (node as HTMLInputElement).type === 'radio' && !isTabbableRadio(node as HTMLInputElement)) || getTabindex(node) < 0 ) const isNodeMatchingSelectorFocusable = (node: HTMLElement) => !( (node as HTMLInputElement).disabled || (isInput(node) && (node as HTMLInputElement).type === 'hidden') || // offsetParent being null will allow detecting cases where an element // is invisible or inside an invisible element, as long as the element // does not use position: fixed. For them, their visibility has to be // checked directly as well. node.offsetParent === null || getComputedStyle(node).visibility === 'hidden' ) const getTabindex = (node: HTMLElement) => { const tabindexAttr = parseInt(node.getAttribute('tabindex') || '', 10) if (!isNaN(tabindexAttr)) return tabindexAttr // Browsers do not return `tabIndex` correctly for contentEditable nodes; // so if they don't have a tabindex attribute specifically set, assume it's 0. if (node.contentEditable === 'true') return 0 return node.tabIndex } // @ts-ignore const sortOrderedTabbables = (a: Tabbables, b: Tabbables) => a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex const isInput = (node: HTMLElement) => node.tagName === 'INPUT' const isTabbableRadio = (node: HTMLInputElement) => { if (!node.name) return true // This won't account for the edge case where you have radio groups with the // same in separate forms on the same page. if (node.ownerDocument) { const radioSet = node.ownerDocument.querySelectorAll( 'input[type="radio"][name="' + node.name + '"]' ) for (let i = 0; i < radioSet.length; i++) if ((radioSet[i] as HTMLInputElement).checked) return radioSet[i] === node return true } return false } export default tabbable
--- title: Kubernetes --- ## Installation 1. Digital Ocean cluster, dev mode ($30) ``` brew install kubectl brew install doctl ``` doctl 2. Helm ``` helm repo add portainer https://portainer.github.io/k8s/ helm repo update ``` Cluster: ``` doctl kubernetes cluster kubeconfig save 85be81c7-5e23-485b-b1fc-fd9559d61694 ``` kubectl create namespace portainer Go to Kubernetes Console > services > Portainer > External Endpoints
"use strict"; var noop = require("../util/noop"); var Environment = require("../environment/Environment"); var CloseableView = { onClose: noop, close: function() { var onCloseError; this.trigger("close"); onCloseError = ifOnCloseError(this); this.unbind(); this.remove(); this.isInDOM = false; if (onCloseError) { throw onCloseError; } }, closeAsChild: function() { var onCloseError; this.trigger("close"); onCloseError = ifOnCloseError(this); this.unbind(); if (Environment.isServer()) { this.remove(); } if (Environment.isClient()) { this.stopListening(); this.$el.off(); this.$el.removeData(); } this.isInDOM = false; if (onCloseError) { throw onCloseError; } } }; function ifOnCloseError(view) { try { view.onClose(); if (typeof view.hasChildViews === "function" && view.hasChildViews()) { view.closeChildViews(); } } catch (e) { console.error( "Error: There is an error in an onClose callback.\n" + "View with broken onClose is: " + view ); return e; } return null; } module.exports = CloseableView; // ---------------------------------------------------------------------------- // Copyright (C) 2018 Bloomberg Finance L.P. // // 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. // // ----------------------------- END-OF-FILE ----------------------------------
using System; public static class PlayAnalyzer { public static string AnalyzeOnField(int shirtNum) { throw new NotImplementedException($"Please implement the (static) PlayAnalyzer.AnalyzeOnField() method"); } public static string AnalyzeOffField(object report) { throw new NotImplementedException($"Please implement the (static) PlayAnalyzer.AnalyzeOffField() method"); } } // **** please do not modify the Manager class **** public class Manager { public string Name { get; } public string Activity { get; } public Manager(string name, string activity) { this.Name = name; this.Activity = activity; } } // **** please do not modify the Incident enum **** public enum Incident { RedCard, YellowCard, Foul, Injury }
(include-book "../test-stuff") (include-book "oslib/argv" :dir :system) ;; See theorem compare-disks-correctness-1 in test-stuff.lisp for a proof of ;; correctness of this procedure. (b* (((mv & image-path1 state) (getenv$ "REF_INPUT" state)) ((mv & image-path2 state) (getenv$ "INPUT" state)) ((mv equiv fat32-in-memory) (compare-disks image-path1 image-path2 fat32-in-memory state))) (mv (good-bye (if equiv 0 1)) fat32-in-memory state))
package org.apache.hadoop.hbase.regionserver.index.jobs; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; public abstract class BasicJob { protected static final Log LOG = LogFactory.getLog(BasicJob.class); protected static AtomicLong idCounter = new AtomicLong(0); protected static boolean printForDebug = true; private static long READY_PRINT_INTERVAL = 10 * 1000; public long id; public long startTime; protected JobStatus status; private String jobName; private String jobDetail; private long lastPrintTime; public abstract boolean checkReady(); public BasicJob(String jobName) { this.jobName = jobName; id = idCounter.getAndIncrement(); startTime = System.currentTimeMillis(); lastPrintTime = startTime; status = JobStatus.WAITING; jobDetail = null; } public boolean isReady() { long now = System.currentTimeMillis(); if (checkReady()) { printMessage("LCIndex job ready after " + (now - startTime) / 1000.0 + " seconds"); return true; } else if ((now - lastPrintTime) > READY_PRINT_INTERVAL) { lastPrintTime = now; printMessage("LCIndex job still not ready after " + (now - startTime) / 1000.0 + " seconds"); printRelatedJob(); } return false; } public abstract void printRelatedJob(); public abstract boolean correspondsTo(BasicJob j) throws IOException; public abstract void promoteRelatedJobs(boolean processNow) throws IOException; public abstract void work() throws IOException; public JobStatus getStatus() { return status; } public void setStatus(JobStatus status) { this.status = status; } protected void printMessage(String msg) { if (printForDebug) LOG.info(msg + ", this job=" + jobInfo()); } public String jobInfo() { return "[" + id + ":" + jobName + ":" + status + "]"; } public void printDone(double waitTime, double execTime) { printMessage("job " + jobInfo() + " waits " + waitTime + " seconds and runs " + execTime + " seconds for " + jobDetail); } protected void setJobDetail(String jobDetail) { this.jobDetail = jobDetail; } public enum JobStatus { WAITING, DOING, FINISHED } }
CREATE DATABASE test_db OWNER test; -- CREATE UNIQUE INDEX CONCURRENTLY ON bb_users(email, username, status, user_role, created_at, updated_at);
#!/bin/bash # Destroy existing vagrant boxes cd ub-riemanna vagrant destroy -f rm -rf ./.vagrant cd ../centos-riemannb vagrant destroy -f rm -rf ./.vagrant cd ../ub-riemannmc vagrant destroy -f rm -rf ./.vagrant cd ../ub-graphitea vagrant destroy -f rm -rf ./.vagrant cd ../centos-graphiteb vagrant destroy -f rm -rf ./.vagrant cd ../ub-graphitemc vagrant destroy -f rm -rf ./.vagrant cd ../host1 vagrant destroy -f rm -rf ./.vagrant cd ../host2 vagrant destroy -f rm -rf ./.vagrant cd ../ # Remove existing vagrant boxes vagrant box remove ub-riemanna --force vagrant box remove centos-riemannb --force vagrant box remove ub-riemannmc --force vagrant box remove ub-graphitea --force vagrant box remove centos-graphiteb --force vagrant box remove ub-graphitemc --force vagrant box remove host1 --force vagrant box remove host2 --force # Add newly built Vagrant boxes if [ -a ../../itmo-453-553/build/ub-riemanna-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/ub-riemanna-virtualbox*.box --name ub-riemanna else echo "File ../../itmo-453-553/build/ub-riemanna-virtualbox*.box doesn't exist" fi if [ -a ../../itmo-453-553/build/centos-riemannb-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/centos-riemannb-virtualbox*.box --name centos-riemannb else echo "File ../../itmo-453-553/build/centos-riemannb-virtualbox*.box doesn't exist" fi if [ -a ../../itmo-453-553/build/ub-riemannmc-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/ub-riemannmc-virtualbox*.box --name ub-riemannmc else echo "File ../../itmo-453-553/build/ub-riemannmc-virtualbox*.box doesn't exist" fi if [ -a ../../itmo-453-553/build/ub-graphitea-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/ub-graphitea-virtualbox*.box --name ub-graphitea else echo "File ../../itmo-453-553/build/ub-graphitea-virtualbox*.box doesn't exist" fi if [ -a ../../itmo-453-553/build/centos-graphiteb-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/centos-graphiteb-virtualbox*.box --name centos-graphiteb else echo "File ../../itmo-453-553/build/centos-graphiteb-virtualbox*.box doesn't exist" fi if [ -a ../../itmo-453-553/build/ub-graphitemc-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/ub-graphitemc-virtualbox*.box --name ub-graphitemc else echo "File ../../itmo-453-553/build/ub-graphitemc-virtualbox*.box doesn't exist" fi if [ -a ../../itmo-453-553/build/ub-host1-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/ub-host1-virtualbox*.box --name host1 else echo "File ../../itmo-453-553/build/ub-host1-virtualbox*.box doesn't exist" fi if [ -a ../../itmo-453-553/build/centos-host2-virtualbox*.box ] then vagrant box add ../../itmo-453-553/build/centos-host2-virtualbox*.box --name host2 else echo "File ../../itmo-453-553/build/centos-host2-virtualbox*.box doesn't exist" fi
package com.jintin.dagger import dagger.Binds import dagger.Module @Module abstract class HoneyLemonadeModule { // @Provides // fun provideLemon(water: Water): Lemon { // return Lyme(water) // } @Binds abstract fun provideLemon(lyme: Lyme): Lemon }
# zammad-workers Zammad workers using Sidekiq to improve on background jobs Currently it is still in development to target the most busiest job tasks in Zammad, which is Transactions Job.
# iwlist ... scan wifi networks ## scan available wifi networks ```shell sudo iwlist wlan0 scanning | grep ESSID ```
import 'dart:ui'; import 'package:flutter/material.dart'; class HelloPage extends StatefulWidget { @override _HelloPageState createState() => _HelloPageState(); } class _HelloPageState extends State<HelloPage> with TickerProviderStateMixin { AnimationController _animationController; @override void initState() { _animationController = AnimationController(duration: const Duration(seconds: 2), vsync: this); _animationController.forward(from: 0.0).whenComplete(_onCompleteAnimation); super.initState(); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.pink, body: _buildAnimation(), ); } Widget _buildAnimation() { final opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation( parent: _animationController, curve: Curves.fastOutSlowIn, )); return AnimatedBuilder( animation: _animationController, builder: (BuildContext context, Widget child) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FadeTransition( opacity: opacityAnimation, child: Transform( transform: _generateMatrix(opacityAnimation), child: Text( 'Welcome MeTalk!', style: TextStyle( fontSize: 40, color: Colors.white, ), ), ), ) ], ) ], ); }); } Matrix4 _generateMatrix(Animation animation) { final value = lerpDouble(60.0, 0, animation.value); return Matrix4.translationValues(0.0, value, 0.0); } void _onCompleteAnimation() { // homeに行くか、プロフィール設定をするか Navigator.of(context).pushNamed('/home'); } }
package primitives import ( "math/big" "testing" ) func TestBlockHeader_GetHash_Block125552(t *testing.T) { bh := BlockHeader{ Version: 1, HashPrevBlock: big.NewInt(0), HashMerkleRoot: big.NewInt(0), Time: 1305998791, Bits: 440_711_666, Nonce: 2_504_433_986, } bh.HashPrevBlock.SetString("81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000", 16) bh.HashMerkleRoot.SetString("e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b", 16) got, _ := bh.GetHash() want := "00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d" if got != want { t.Errorf("got = %s; want %s", got, want) } }
package practice /** First scala code */ object PrintFirst10Numbers extends App { for (i <- 1 to 10) println(i) }
# frozen_string_literal: true module Metar module Data class TemperatureAndDewPoint < Metar::Data::Base def self.parse(raw) return nil if !raw m = raw.match(%r{^(M?\d+|XX|//)\/(M?\d+|XX|//)?$}) return nil if !m temperature = Metar::Data::Temperature.parse(m[1]) dew_point = Metar::Data::Temperature.parse(m[2]) new(raw, temperature: temperature, dew_point: dew_point) end attr_reader :temperature attr_reader :dew_point def initialize(raw, temperature:, dew_point:) @raw = raw @temperature = temperature @dew_point = dew_point end end end end
/** * Copyright 2017 Matt Acosta * * 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. */ 'use strict'; import { ArgumentOutOfRangeException, Debug, Exception } from '../../../php-common'; import { INode } from './INode'; import { ISyntaxNode, ISyntaxNodeOrList } from '../syntax/ISyntaxNode'; import { NodeFlags } from './NodeFlags'; import { SyntaxDiagnostic } from '../../diagnostics/SyntaxDiagnostic'; /** * Provides a base class for all nodes in a tree (both terminal and non-terminal). */ export abstract class NodeBase implements INode { /** * A map of all diagnostics attached to nodes. * * Since nodes are more likely to not contain any diagnostics, this saves * memory by not adding a diagnostic field to every node. Diagnostics are * instead maintained using a weak reference to the associated node, so that * they can still be reclaimed automatically when the node is no longer * referenced. */ protected static readonly DiagnosticWeakMap: WeakMap<NodeBase, ReadonlyArray<SyntaxDiagnostic>> = new WeakMap(); /** * An empty diagnostic array. */ protected static readonly EmptyDiagnosticList: ReadonlyArray<SyntaxDiagnostic> = []; /** * A bit field storing information about this node. */ protected abstract _flags: NodeFlags; /** * The width of the token or token collection, with trivia. */ protected abstract _fullWidth: number; /** * Stores the hash code of the node. * * This prevents recalculating the hash code of every child on every lookup. * * Fun fact: The .NET CLR saves space by storing an object's hash code in * what is usually an unused chunk of memory that was already allocated as * part of the object's overhead. */ protected abstract hash: number; /** * Constructs a `NodeBase` object. * * @param {ReadonlyArray<SyntaxDiagnostic>} diagnostics * A list of diagnostics associated with the token or token collection. */ constructor(diagnostics: ReadonlyArray<SyntaxDiagnostic>) { // IMPORTANT: This is a performance critical method. // NOTE: This class does not implement any properties because everything // inherits from this class, and any operation that would cause `this` to // be dereferenced would also cause V8 to perform a map check which would // subsequently fail. if (diagnostics.length > 0) { NodeBase.DiagnosticWeakMap.set(this, diagnostics); } } /** * @inheritDoc */ public get containsDiagnostics(): boolean { return (this._flags & NodeFlags.ContainsDiagnostics) !== 0; } /** * @inheritDoc */ public get containsSkippedText(): boolean { return (this._flags & NodeFlags.ContainsSkippedText) !== 0; } /** * @inheritDoc */ public get count(): number { return 0; } /** * @inheritDoc */ public get diagnostics(): ReadonlyArray<SyntaxDiagnostic> { if (NodeBase.DiagnosticWeakMap.has(this)) { // Suppress TS2322: Result cannot be undefined due to if-condition. return <SyntaxDiagnostic[]>NodeBase.DiagnosticWeakMap.get(this); } // Do not create a new array on every call. return NodeBase.EmptyDiagnosticList; } /** * Gets the flags used to store metadata about this node and its children. */ public abstract get flags(): NodeFlags; /** * @inheritDoc */ public abstract get fullWidth(): number; /** * @inheritDoc */ public get isMissing(): boolean { return (this._flags & NodeFlags.IsNotMissing) === 0; } /** * @inheritDoc */ public get isList(): boolean { return false; } /** * @inheritDoc */ public get isToken(): boolean { return false; } /** * @inheritDoc */ public get isTrivia(): boolean { return false; } /** * @inheritDoc */ public get leadingTrivia(): INode | null { return null; } /** * @inheritDoc */ public get leadingTriviaWidth(): number { return this._fullWidth !== 0 ? this.getFirstToken().leadingTriviaWidth : 0; } /** * @inheritDoc */ public get width(): number { return this._fullWidth - this.leadingTriviaWidth; } /** * @inheritDoc */ public abstract childAt(index: number): INode | null; /** * @inheritDoc */ public abstract createSyntaxNode(parent: ISyntaxNode | null, offset: number): ISyntaxNodeOrList; /** * Determines if the current node is equal to a given node. */ public abstract equals(value: NodeBase): boolean; /** * @inheritDoc */ public abstract hashCode(): number; /** * @inheritDoc */ public indexAtOffset(relativeOffset: number): number { if (relativeOffset < 0 || relativeOffset >= this.fullWidth) { throw new ArgumentOutOfRangeException(); } let width = 0; const length = this.count; for (let i = 0; i < length; i++) { const child = this.childAt(i); if (child !== null) { width += child.fullWidth; if (relativeOffset < width) { return i; } } } // Offset was not within parent node. throw new Exception('Child node expected'); } /** * @inheritDoc */ public offsetAt(index: number): number { if (index < 0 || index >= this.count) { throw new ArgumentOutOfRangeException(); } let offset = 0; for (let i = 0; i < index; i++) { const child = this.childAt(i); if (child !== null) { offset += child.fullWidth; } } return offset; } /** * @inheritDoc */ public abstract withDiagnostics(diagnostics: ReadonlyArray<SyntaxDiagnostic>): INode; /** * Calculates the hash code of the node. */ protected abstract computeHashCode(): number; /** * Updates the flags and width of the current node given the flags and width * of a child node. */ protected abstract updateFlagsAndWidth(flags: NodeFlags, fullWidth: number): void; /** * Gets the first node that does not have any children. */ private getFirstToken(): INode { let length = this.count; let node: INode | null = this; // Terminal nodes (tokens and trivia) should not indirectly call this // method, as that indicates a missing override. Debug.assert(length !== 0); do { let firstChild: INode | null = null; for (let i = 0; i < length; i++) { const child: INode | null = node.childAt(i); if (child !== null) { firstChild = child; length = child.count; break; } } node = firstChild; } while (node !== null && length > 0); if (node === null) { // The parser should not have created this node. throw new Exception('Child node expected'); } return node; } /** * Gets the last node that does not have any children. */ private getLastToken(): INode { let length = this.count; let node: INode | null = this; // Terminal nodes (tokens and trivia) should not indirectly call this // method, as that indicates a missing override. Debug.assert(length !== 0); do { let lastChild: INode | null = null; for (let i = length - 1; i >= 0; i--) { const child: INode | null = node.childAt(i); if (child !== null) { lastChild = child; length = child.count; break; } } node = lastChild; } while (node !== null && length > 0); if (node === null) { // The parser should not have created this node. throw new Exception('Child node expected'); } return node; } }
package org.jetbrains.plugins.scala package lang package parser package parsing package expressions import com.intellij.lang.PsiBuilder import org.jetbrains.plugins.scala.lang.lexer.{ScalaTokenType, ScalaTokenTypes} import org.jetbrains.plugins.scala.lang.parser.parsing.builder.ScalaPsiBuilder import org.jetbrains.plugins.scala.lang.parser.parsing.types.CompoundType import org.jetbrains.plugins.scala.lang.parser.util.InScala3 /** * @author Alexander Podkhalyuzin * Date: 06.03.2008 */ /* * ResultExpr ::= Expr1 * | (Bindings | id ':' CompoundType) '=>' Block * * In Scala 3: * * BlockResult ::= [‘implicit’] FunParams ‘=>’ Block * | Expr1 */ object ResultExpr { def apply(stopOnOutdent: Boolean)(implicit builder: ScalaPsiBuilder): Boolean = { val resultMarker = builder.mark() val backupMarker = builder.mark() def parseFunctionEnd(): Boolean = builder.getTokenType match { case ScalaTokenTypes.tFUNTYPE | ScalaTokenType.ImplicitFunctionArrow => builder.advanceLexer() //Ate => or ?=> Block.Braceless(stopOnOutdent, needNode = true) backupMarker.drop() resultMarker.done(ScalaElementType.FUNCTION_EXPR) true case _ => resultMarker.drop() backupMarker.rollbackTo() false } def parseFunction(paramsMarker: PsiBuilder.Marker): Boolean = { val paramMarker = builder.mark() builder.advanceLexer() //Ate id if (ScalaTokenTypes.tCOLON == builder.getTokenType) { builder.advanceLexer() // ate ':' val pt = builder.mark() CompoundType.parse(builder) pt.done(ScalaElementType.PARAM_TYPE) } builder.getTokenType match { case ScalaTokenTypes.tFUNTYPE | ScalaTokenType.ImplicitFunctionArrow => val psm = paramsMarker.precede // 'parameter list' paramMarker.done(ScalaElementType.PARAM) paramsMarker.done(ScalaElementType.PARAM_CLAUSE) psm.done(ScalaElementType.PARAM_CLAUSES) return parseFunctionEnd() case _ => builder error ErrMsg("fun.sign.expected") } parseFunctionEnd() } builder.getTokenType match { case ScalaTokenTypes.tLPARENTHESIS => Bindings() return parseFunctionEnd() case ScalaTokenTypes.kIMPLICIT => val pmarker = builder.mark() builder.advanceLexer() //ate implicit builder.getTokenType match { case ScalaTokenTypes.tIDENTIFIER => return parseFunction(pmarker) case InScala3(ScalaTokenTypes.tLPARENTHESIS) => pmarker.drop() Bindings() return parseFunctionEnd() case _ => resultMarker.drop() backupMarker.rollbackTo() return false } case ScalaTokenTypes.tIDENTIFIER | ScalaTokenTypes.tUNDER => val pmarker = builder.mark() return parseFunction(pmarker) case _ => backupMarker.drop() } resultMarker.drop() false } }
require 'zlib' module ActiveRecord module ShardFor class HashModuloRouter < ConnectionRouter # @param [String] key sharding key def route(key) hash(key) % connection_count end private def hash(v) Zlib.crc32(v.to_s) end end end end
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.domain; import java.util.Objects; public abstract class Entity<T> { private T id; protected Entity(T id) { this.id = id; } public T getId() { return id; } public void identifyBy(final T id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Entity)) { return false; } Entity entity = (Entity) o; return Objects.equals(id, entity.id); } @Override public int hashCode() { return Objects.hash(id); } }
using JetBrains.Annotations; namespace XyrusWorx.Diagnostics { [PublicAPI] public enum LogVerbosity { Debug = -2, Verbose = -1, Normal = 0, WarningsAndErrors = 1, ErrorsOnly = 2 } }
(FITCH-COMBINE-SCORES1 (7 4 (:TYPE-PRESCRIPTION MIN-NIL-INF)) ) (FITCH-COMBINE-SCORES1-CAR (741 591 (:REWRITE DEFAULT-CAR)) (564 425 (:REWRITE DEFAULT-CDR)) (370 284 (:REWRITE DEFAULT-+-2)) (284 284 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (284 284 (:REWRITE NORMALIZE-ADDENDS)) (284 284 (:REWRITE DEFAULT-+-1)) (243 243 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (243 243 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (221 121 (:REWRITE SIMPLIFY-SUMS-<)) (221 121 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (221 121 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (221 121 (:REWRITE DEFAULT-<-2)) (121 121 (:REWRITE DEFAULT-<-1)) (121 121 (:REWRITE |(< (- x) (- y))|)) (96 32 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (96 32 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (96 32 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (95 95 (:REWRITE |(< (+ c x) d)|)) (72 24 (:REWRITE |(equal (+ d x) (+ c y))|)) (72 24 (:REWRITE |(equal (+ c x) (+ d y))|)) (48 24 (:REWRITE |(equal (+ c x) d)|)) (32 32 (:REWRITE FOLD-CONSTS-IN-+)) (32 32 (:REWRITE |(equal (- x) (- y))|)) (32 32 (:REWRITE |(+ c (+ d x))|)) (26 26 (:REWRITE |(< d (+ c x))|)) (24 24 (:REWRITE |(< (+ c x y) d)|)) ) (FITCH-COMBINE-SCORES1-LEN (57 21 (:REWRITE SIMPLIFY-SUMS-<)) (57 21 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (57 21 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (57 21 (:REWRITE DEFAULT-<-2)) (45 45 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (45 45 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (38 31 (:REWRITE DEFAULT-+-2)) (31 31 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (31 31 (:REWRITE NORMALIZE-ADDENDS)) (22 16 (:REWRITE DEFAULT-CDR)) (21 21 (:REWRITE DEFAULT-<-1)) (21 21 (:REWRITE |(< (- x) (- y))|)) (12 12 (:REWRITE |(< (+ c x) d)|)) (12 9 (:REWRITE DEFAULT-CAR)) (9 3 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (9 3 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (9 3 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE |(< (+ c x y) d)|)) (6 6 (:REWRITE |(+ c (+ d x))|)) (3 3 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (3 3 (:REWRITE |(equal (- x) (- y))|)) (3 3 (:REWRITE |(< d (+ c x))|)) (3 3 (:REWRITE |(< 0 (- x))|)) ) (FITCH-COMBINE-SCORES1-RATIONAL-OR-NIL-LISTP (370 311 (:REWRITE DEFAULT-CAR)) (354 283 (:REWRITE DEFAULT-CDR)) (210 144 (:REWRITE DEFAULT-+-2)) (144 144 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (144 144 (:REWRITE NORMALIZE-ADDENDS)) (144 144 (:REWRITE DEFAULT-+-1)) (122 122 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (122 122 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (111 55 (:REWRITE SIMPLIFY-SUMS-<)) (111 55 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (111 55 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (111 55 (:REWRITE DEFAULT-<-2)) (72 24 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (72 24 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (72 24 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (55 55 (:REWRITE DEFAULT-<-1)) (55 55 (:REWRITE |(< (- x) (- y))|)) (48 16 (:REWRITE |(equal (+ d x) (+ c y))|)) (48 16 (:REWRITE |(equal (+ c x) (+ d y))|)) (47 47 (:REWRITE |(< (+ c x) d)|)) (32 16 (:REWRITE |(equal (+ c x) d)|)) (24 24 (:REWRITE |(equal (- x) (- y))|)) (11 11 (:REWRITE FOLD-CONSTS-IN-+)) (11 11 (:REWRITE |(+ c (+ d x))|)) (10 10 (:REWRITE |(< (+ c x y) d)|)) (8 8 (:REWRITE |(< d (+ c x))|)) ) (CONSP-NOT-LEN-0 (7 4 (:REWRITE DEFAULT-+-2)) (6 3 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (6 3 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (6 3 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (4 4 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (4 4 (:REWRITE NORMALIZE-ADDENDS)) (4 4 (:REWRITE DEFAULT-+-1)) (3 3 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-=-0)) (3 3 (:REWRITE DEFAULT-CDR)) (3 3 (:REWRITE |(equal (- x) 0)|)) (3 3 (:REWRITE |(equal (- x) (- y))|)) ) (FITCH-COMBINE-SCORES1 (1952 24 (:DEFINITION FITCH-COMBINE-SCORES1)) (908 60 (:REWRITE |(< (if a b c) x)|)) (438 414 (:REWRITE DEFAULT-CDR)) (366 318 (:REWRITE DEFAULT-CAR)) (354 232 (:REWRITE DEFAULT-+-2)) (232 232 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (232 232 (:REWRITE NORMALIZE-ADDENDS)) (232 232 (:REWRITE DEFAULT-+-1)) (146 66 (:REWRITE SIMPLIFY-SUMS-<)) (146 66 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (146 66 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (146 66 (:REWRITE DEFAULT-<-2)) (140 70 (:TYPE-PRESCRIPTION MIN-NIL-INF)) (126 126 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (126 126 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (96 32 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (96 32 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (96 32 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (66 66 (:REWRITE DEFAULT-<-1)) (66 66 (:REWRITE |(< (- x) (- y))|)) (48 48 (:REWRITE |(< (+ c x) d)|)) (36 12 (:REWRITE |(equal (+ d x) (+ c y))|)) (36 12 (:REWRITE |(equal (+ c x) (+ d y))|)) (32 32 (:REWRITE |(equal (- x) (- y))|)) (32 16 (:REWRITE |(equal (+ c x) d)|)) (26 26 (:REWRITE FOLD-CONSTS-IN-+)) (26 26 (:REWRITE |(+ c (+ d x))|)) (24 24 (:REWRITE |(< (+ c x y) d)|)) (18 18 (:REWRITE |(< d (+ c x))|)) ) (FITCH-COMBINE-SCORES (184 184 (:REWRITE DEFAULT-CDR)) (168 84 (:REWRITE DEFAULT-+-2)) (114 48 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (114 48 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (114 48 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (84 84 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (84 84 (:REWRITE NORMALIZE-ADDENDS)) (84 84 (:REWRITE DEFAULT-+-1)) (48 48 (:REWRITE |(equal (- x) (- y))|)) (8 4 (:REWRITE |(equal (+ c x) d)|)) (6 2 (:REWRITE |(equal (+ d x) (+ c y))|)) (6 2 (:REWRITE |(equal (+ c x) (+ d y))|)) (1 1 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-=-0)) (1 1 (:REWRITE |(equal (- x) 0)|)) ) (FITCH-COMBINE-SCORES-LEN (1152 6 (:DEFINITION FITCH-COMBINE-SCORES1)) (798 12 (:DEFINITION MIN-NIL-INF)) (690 42 (:REWRITE |(< (if a b c) x)|)) (276 12 (:DEFINITION PLUS-NIL-INF)) (240 30 (:REWRITE |(+ (if a b c) x)|)) (132 12 (:REWRITE |(+ (+ x y) z)|)) (102 42 (:REWRITE SIMPLIFY-SUMS-<)) (102 42 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (102 42 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (102 42 (:REWRITE DEFAULT-<-2)) (90 90 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (90 90 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (79 57 (:REWRITE DEFAULT-CDR)) (76 62 (:REWRITE DEFAULT-+-2)) (73 52 (:REWRITE DEFAULT-CAR)) (68 62 (:REWRITE DEFAULT-+-1)) (62 62 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (62 62 (:REWRITE NORMALIZE-ADDENDS)) (60 6 (:REWRITE |(< x (if a b c))|)) (42 42 (:REWRITE DEFAULT-<-1)) (42 42 (:REWRITE |(< (- x) (- y))|)) (24 24 (:REWRITE |(< (+ c x) d)|)) (18 6 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (18 6 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (18 6 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (12 12 (:REWRITE FOLD-CONSTS-IN-+)) (12 12 (:REWRITE |(< (+ c x y) d)|)) (12 12 (:REWRITE |(+ c (+ d x))|)) (6 6 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (6 6 (:REWRITE |(equal (- x) (- y))|)) (6 6 (:REWRITE |(< d (+ c x))|)) (6 6 (:REWRITE |(< 0 (- x))|)) (6 6 (:DEFINITION FIX)) ) (FITCH-COMBINE-SCORES-CHAR-SCORELISTP (2056 14 (:DEFINITION FITCH-COMBINE-SCORES1)) (1389 28 (:DEFINITION MIN-NIL-INF)) (1179 71 (:REWRITE |(< (if a b c) x)|)) (521 479 (:REWRITE DEFAULT-CAR)) (489 434 (:REWRITE DEFAULT-CDR)) (485 25 (:DEFINITION PLUS-NIL-INF)) (457 271 (:REWRITE DEFAULT-+-2)) (404 46 (:REWRITE |(+ (if a b c) x)|)) (279 271 (:REWRITE DEFAULT-+-1)) (271 271 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (271 271 (:REWRITE NORMALIZE-ADDENDS)) (250 110 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (250 110 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (250 110 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (242 22 (:REWRITE |(+ (+ x y) z)|)) (179 71 (:REWRITE SIMPLIFY-SUMS-<)) (179 71 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (179 71 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (179 71 (:REWRITE DEFAULT-<-2)) (150 150 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (150 150 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (110 110 (:REWRITE |(equal (- x) (- y))|)) (80 8 (:REWRITE |(< x (if a b c))|)) (71 71 (:REWRITE DEFAULT-<-1)) (71 71 (:REWRITE |(< (- x) (- y))|)) (44 44 (:REWRITE |(< (+ c x) d)|)) (42 14 (:REWRITE |(equal (+ d x) (+ c y))|)) (42 14 (:REWRITE |(equal (+ c x) (+ d y))|)) (28 14 (:REWRITE |(equal (+ c x) d)|)) (22 22 (:REWRITE FOLD-CONSTS-IN-+)) (22 22 (:REWRITE |(< (+ c x y) d)|)) (22 22 (:REWRITE |(+ c (+ d x))|)) (11 11 (:REWRITE |(< d (+ c x))|)) (8 8 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (8 8 (:REWRITE |(< 0 (- x))|)) (8 8 (:DEFINITION FIX)) ) (FITCH-COMBINE-SCORES-RATIONAL-OR-NIL-LISTP (2056 14 (:DEFINITION FITCH-COMBINE-SCORES1)) (1389 28 (:DEFINITION MIN-NIL-INF)) (1179 71 (:REWRITE |(< (if a b c) x)|)) (539 472 (:REWRITE DEFAULT-CAR)) (485 25 (:DEFINITION PLUS-NIL-INF)) (449 395 (:REWRITE DEFAULT-CDR)) (419 252 (:REWRITE DEFAULT-+-2)) (404 46 (:REWRITE |(+ (if a b c) x)|)) (260 252 (:REWRITE DEFAULT-+-1)) (252 252 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (252 252 (:REWRITE NORMALIZE-ADDENDS)) (242 22 (:REWRITE |(+ (+ x y) z)|)) (224 97 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (224 97 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (224 97 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (179 71 (:REWRITE SIMPLIFY-SUMS-<)) (179 71 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (179 71 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (179 71 (:REWRITE DEFAULT-<-2)) (150 150 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (150 150 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (97 97 (:REWRITE |(equal (- x) (- y))|)) (80 8 (:REWRITE |(< x (if a b c))|)) (71 71 (:REWRITE DEFAULT-<-1)) (71 71 (:REWRITE |(< (- x) (- y))|)) (44 44 (:REWRITE |(< (+ c x) d)|)) (42 14 (:REWRITE |(equal (+ d x) (+ c y))|)) (42 14 (:REWRITE |(equal (+ c x) (+ d y))|)) (28 14 (:REWRITE |(equal (+ c x) d)|)) (22 22 (:REWRITE FOLD-CONSTS-IN-+)) (22 22 (:REWRITE |(< (+ c x y) d)|)) (22 22 (:REWRITE |(+ c (+ d x))|)) (11 11 (:REWRITE |(< d (+ c x))|)) (8 8 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (8 8 (:REWRITE |(< 0 (- x))|)) (8 8 (:DEFINITION FIX)) ) (FITCH-INITIAL-SCORELIST1 (10 10 (:REWRITE DEFAULT-CAR)) (6 6 (:REWRITE DEFAULT-CDR)) (2 2 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (2 2 (:REWRITE NORMALIZE-ADDENDS)) (2 2 (:REWRITE DEFAULT-+-2)) (2 2 (:REWRITE DEFAULT-+-1)) (2 1 (:TYPE-PRESCRIPTION MIN-NIL-INF)) ) (FITCH-INITIAL-SCORELIST1-LEN (17 10 (:REWRITE DEFAULT-+-2)) (10 10 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (10 10 (:REWRITE NORMALIZE-ADDENDS)) (10 10 (:REWRITE DEFAULT-+-1)) (9 8 (:REWRITE DEFAULT-CDR)) (9 3 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (9 3 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (9 3 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (6 6 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (6 6 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (3 3 (:REWRITE SIMPLIFY-SUMS-<)) (3 3 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (3 3 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (3 3 (:REWRITE DEFAULT-CAR)) (3 3 (:REWRITE DEFAULT-<-2)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE |(equal (- x) (- y))|)) (3 3 (:REWRITE |(< (- x) (- y))|)) (3 3 (:REWRITE |(< (+ c x) d)|)) ) (FITCH-INITIAL-SCORELIST1-RATIONAL-OR-NIL-LISTP (66 59 (:REWRITE DEFAULT-CAR)) (51 47 (:REWRITE DEFAULT-CDR)) (5 5 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (5 5 (:REWRITE NORMALIZE-ADDENDS)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (4 4 (:REWRITE SIMPLIFY-SUMS-<)) (4 4 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (4 4 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (4 4 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (4 4 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE |(< (- x) (- y))|)) (4 4 (:REWRITE |(< (+ c x) d)|)) ) (FITCH-INITIAL-SCORELIST (66 66 (:REWRITE DEFAULT-CDR)) (60 30 (:REWRITE DEFAULT-+-2)) (35 14 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (35 14 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (35 14 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (30 30 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (30 30 (:REWRITE NORMALIZE-ADDENDS)) (30 30 (:REWRITE DEFAULT-+-1)) (14 14 (:REWRITE |(equal (- x) (- y))|)) (6 3 (:REWRITE |(equal (+ c x) d)|)) (3 1 (:REWRITE |(equal (+ d x) (+ c y))|)) (3 1 (:REWRITE |(equal (+ c x) (+ d y))|)) ) (FITCH-INITIAL-SCORELIST-LEN (63 3 (:DEFINITION FITCH-INITIAL-SCORELIST1)) (39 3 (:DEFINITION MIN-NIL-INF)) (30 3 (:REWRITE |(< (if a b c) x)|)) (17 10 (:REWRITE DEFAULT-+-2)) (15 3 (:DEFINITION PLUS-NIL-INF)) (14 13 (:REWRITE DEFAULT-CDR)) (10 10 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (10 10 (:REWRITE NORMALIZE-ADDENDS)) (10 10 (:REWRITE DEFAULT-+-1)) (9 9 (:REWRITE DEFAULT-CAR)) (9 3 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (9 3 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (9 3 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (6 6 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (6 6 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (3 3 (:REWRITE SIMPLIFY-SUMS-<)) (3 3 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (3 3 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (3 3 (:REWRITE DEFAULT-<-2)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE |(equal (- x) (- y))|)) (3 3 (:REWRITE |(< (- x) (- y))|)) (3 3 (:REWRITE |(< (+ c x) d)|)) ) (FITCH-INITIAL-SCORELIST-SEQUENCE-SCORELISTP (124 116 (:REWRITE DEFAULT-CAR)) (91 87 (:REWRITE DEFAULT-CDR)) (88 46 (:REWRITE DEFAULT-+-2)) (86 6 (:DEFINITION FITCH-INITIAL-SCORELIST1)) (57 25 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (57 25 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (57 25 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (48 6 (:DEFINITION MIN-NIL-INF)) (46 46 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (46 46 (:REWRITE NORMALIZE-ADDENDS)) (46 46 (:REWRITE DEFAULT-+-1)) (25 25 (:REWRITE |(equal (- x) (- y))|)) (20 4 (:DEFINITION PLUS-NIL-INF)) (20 2 (:REWRITE |(< (if a b c) x)|)) (12 4 (:REWRITE |(equal (+ d x) (+ c y))|)) (12 4 (:REWRITE |(equal (+ c x) (+ d y))|)) (8 4 (:REWRITE |(equal (+ c x) d)|)) (6 6 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (6 6 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (4 4 (:REWRITE SIMPLIFY-SUMS-<)) (4 4 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (4 4 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE |(< (- x) (- y))|)) (4 4 (:REWRITE |(< (+ c x) d)|)) ) (FITCH-SCORE-SUBTREE (629 34 (:DEFINITION INTEGER-ABS)) (615 221 (:REWRITE DEFAULT-+-2)) (323 17 (:REWRITE |(+ (if a b c) x)|)) (286 221 (:REWRITE DEFAULT-+-1)) (221 221 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (187 17 (:REWRITE NUMERATOR-NEGATIVE)) (170 17 (:DEFINITION LENGTH)) (119 107 (:REWRITE DEFAULT-CAR)) (119 17 (:DEFINITION LEN)) (118 42 (:REWRITE DEFAULT-UNARY-MINUS)) (112 100 (:REWRITE DEFAULT-CDR)) (86 70 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (71 71 (:REWRITE FOLD-CONSTS-IN-+)) (70 70 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (68 68 (:TYPE-PRESCRIPTION NUMERATOR-POSITIVE . 2)) (68 68 (:TYPE-PRESCRIPTION NUMERATOR-POSITIVE . 1)) (68 68 (:TYPE-PRESCRIPTION NUMERATOR-NEGATIVE . 2)) (68 68 (:TYPE-PRESCRIPTION NUMERATOR-NEGATIVE . 1)) (68 48 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (68 48 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (65 65 (:REWRITE |(< (- x) (- y))|)) (54 46 (:REWRITE DEFAULT-<-2)) (52 46 (:REWRITE DEFAULT-<-1)) (51 51 (:REWRITE |(< (- x) 0)|)) (40 40 (:LINEAR SUBTREEP-SMALLER)) (34 34 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-<-0)) (29 11 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (29 11 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (26 8 (:REWRITE |(equal (+ d x) (+ c y))|)) (26 8 (:REWRITE |(< (+ d x) (+ c y))|)) (19 1 (:REWRITE |(< (if a b c) x)|)) (18 18 (:REWRITE REDUCE-INTEGERP-+)) (18 18 (:REWRITE INTEGERP-MINUS-X)) (18 18 (:META META-INTEGERP-CORRECT)) (18 8 (:REWRITE |(equal (+ c x) d)|)) (17 17 (:TYPE-PRESCRIPTION LEN)) (17 17 (:REWRITE INTEGERP==>NUMERATOR-=-X)) (17 17 (:REWRITE INTEGERP==>DENOMINATOR-=-1)) (17 17 (:REWRITE DEFAULT-REALPART)) (17 17 (:REWRITE DEFAULT-NUMERATOR)) (17 17 (:REWRITE DEFAULT-IMAGPART)) (17 17 (:REWRITE DEFAULT-DENOMINATOR)) (17 17 (:REWRITE DEFAULT-COERCE-2)) (17 17 (:REWRITE DEFAULT-COERCE-1)) (14 1 (:DEFINITION POSP)) (12 6 (:REWRITE |(< (+ c x) d)|)) (11 11 (:REWRITE |(equal (- x) (- y))|)) (8 4 (:REWRITE |(< d (+ c x y))|)) (4 2 (:REWRITE |(equal (+ c x y) d)|)) (2 2 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (2 2 (:REWRITE |(< 0 (- x))|)) (1 1 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-=-0)) (1 1 (:REWRITE |(equal (- x) 0)|)) ) (FITCH-SCORE-SUBTREE-LEN (51902 94 (:DEFINITION FITCH-COMBINE-SCORES)) (43580 188 (:DEFINITION FITCH-COMBINE-SCORES1)) (28074 526 (:DEFINITION MIN-NIL-INF)) (24240 1466 (:REWRITE |(< (if a b c) x)|)) (10426 10426 (:TYPE-PRESCRIPTION FITCH-COMBINE-SCORES1)) (9406 526 (:DEFINITION PLUS-NIL-INF)) (7615 5933 (:REWRITE DEFAULT-CDR)) (7528 940 (:REWRITE |(+ (if a b c) x)|)) (4216 150 (:DEFINITION FITCH-INITIAL-SCORELIST)) (4136 376 (:REWRITE |(+ (+ x y) z)|)) (3665 1505 (:REWRITE SIMPLIFY-SUMS-<)) (3665 1505 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (3665 1505 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (3665 1505 (:REWRITE DEFAULT-<-2)) (3159 3159 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (3159 3159 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (3154 150 (:DEFINITION FITCH-INITIAL-SCORELIST1)) (2386 2040 (:REWRITE DEFAULT-+-2)) (2228 2040 (:REWRITE DEFAULT-+-1)) (2040 2040 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (2040 2040 (:REWRITE NORMALIZE-ADDENDS)) (1880 188 (:REWRITE |(< x (if a b c))|)) (1505 1505 (:REWRITE DEFAULT-<-1)) (1505 1505 (:REWRITE |(< (- x) (- y))|)) (1054 274 (:REWRITE NOT-CONSP-ASSOC-NOT-ASSOC-HQUAL)) (902 902 (:REWRITE |(< (+ c x) d)|)) (780 780 (:TYPE-PRESCRIPTION STRIP-CARS-GEN)) (764 764 (:TYPE-PRESCRIPTION GOOD-TAXON-INDEX-HALIST)) (580 40 (:DEFINITION ZERO-SCORES)) (479 479 (:TYPE-PRESCRIPTION FITCH-COMBINE-SCORES)) (464 271 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (456 271 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (456 271 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (442 90 (:REWRITE MEMBER-STRIP-CARS-GOOD-TAXON-BDD-ASSOC)) (382 382 (:REWRITE GOOD-TAXON-INDEX-HALIST-WHEN-NOT-CONSP)) (376 376 (:REWRITE FOLD-CONSTS-IN-+)) (376 376 (:REWRITE |(< (+ c x y) d)|)) (376 376 (:REWRITE |(+ c (+ d x))|)) (344 172 (:TYPE-PRESCRIPTION INTEGER-ASSOC-HQUAL-INTEGER-HALISTP)) (344 86 (:REWRITE ATOM-CDR-ASSOC-GOOD-TAXON-LIST)) (312 312 (:REWRITE SUBSET-SAME-MEMBERS)) (312 312 (:REWRITE MEMBER-PERM-GIVES-MEMBER)) (312 312 (:REWRITE MEMBER-DIFFERENCE-MEMBER)) (312 156 (:TYPE-PRESCRIPTION BOUND-TO-NAT-HET-NUMBER)) (292 292 (:REWRITE PROPER-SUBTREE-MEMBER-GEN)) (292 292 (:REWRITE NOT-MEMBER-SUBSET)) (280 40 (:DEFINITION HONS-MAKE-LIST-ACC)) (271 271 (:REWRITE |(equal (- x) (- y))|)) (262 70 (:REWRITE MEMBER-TAXA-ASSOC-HQUAL)) (240 40 (:DEFINITION MAKE-LIST-AC)) (238 64 (:REWRITE ASSOC-CAR-FROM-SUBSET)) (220 44 (:DEFINITION RATIONAL-OR-NIL-LISTP)) (198 6 (:REWRITE ASSOC-HQUAL-VALID-SEQUENCES-LENGTH-N)) (188 188 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (188 188 (:REWRITE |(< d (+ c x))|)) (188 188 (:REWRITE |(< 0 (- x))|)) (188 188 (:DEFINITION FIX)) (172 172 (:TYPE-PRESCRIPTION INTEGER-HALISTP)) (172 172 (:TYPE-PRESCRIPTION GOOD-INDEX-TAXON-HALIST)) (148 148 (:TYPE-PRESCRIPTION GOOD-TAXON-BDD-ALIST)) (112 46 (:REWRITE CONSP-NOT-LEN-0)) (86 86 (:REWRITE GOOD-INDEX-TAXON-HALIST-WHEN-NOT-CONSP)) (84 84 (:REWRITE GOOD-TAXON-BDD-ALIST-WHEN-NOT-CONSP)) (72 72 (:TYPE-PRESCRIPTION BOUND-TO-NAT-LIST)) (70 70 (:REWRITE MEMBER-GIVES-ASSOC-HQUAL)) (48 48 (:TYPE-PRESCRIPTION MAKE-LEAF-SCORE-LIST)) (46 46 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-=-0)) (46 46 (:REWRITE |(equal (- x) 0)|)) (40 40 (:REWRITE ZP-OPEN)) (40 8 (:REWRITE |(+ y x)|)) (39 39 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-<-0)) (39 39 (:REWRITE REDUCE-INTEGERP-+)) (39 39 (:REWRITE INTEGERP-MINUS-X)) (39 39 (:REWRITE |(< (- x) 0)|)) (39 39 (:META META-INTEGERP-CORRECT)) (14 14 (:REWRITE ASSOC-HQUAL-STATE-SCORELIST-MAP)) (8 8 (:TYPE-PRESCRIPTION ZERO-SCORES)) ) (FITCH-SCORE-SUBTREE-CHAR-SCORELISTP (50900 92 (:DEFINITION FITCH-COMBINE-SCORES)) (42700 184 (:DEFINITION FITCH-COMBINE-SCORES1)) (27484 516 (:DEFINITION MIN-NIL-INF)) (23728 1436 (:REWRITE |(< (if a b c) x)|)) (10196 10196 (:TYPE-PRESCRIPTION FITCH-COMBINE-SCORES1)) (9212 516 (:DEFINITION PLUS-NIL-INF)) (7606 5955 (:REWRITE DEFAULT-CDR)) (7368 920 (:REWRITE |(+ (if a b c) x)|)) (4160 148 (:DEFINITION FITCH-INITIAL-SCORELIST)) (4048 368 (:REWRITE |(+ (+ x y) z)|)) (3586 1474 (:REWRITE SIMPLIFY-SUMS-<)) (3586 1474 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (3586 1474 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (3586 1474 (:REWRITE DEFAULT-<-2)) (3112 148 (:DEFINITION FITCH-INITIAL-SCORELIST1)) (3094 3094 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (3094 3094 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (2142 1901 (:REWRITE DEFAULT-+-2)) (2085 1901 (:REWRITE DEFAULT-+-1)) (1901 1901 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (1901 1901 (:REWRITE NORMALIZE-ADDENDS)) (1840 184 (:REWRITE |(< x (if a b c))|)) (1687 241 (:DEFINITION LEN)) (1474 1474 (:REWRITE DEFAULT-<-1)) (1474 1474 (:REWRITE |(< (- x) (- y))|)) (1054 274 (:REWRITE NOT-CONSP-ASSOC-NOT-ASSOC-HQUAL)) (884 884 (:REWRITE |(< (+ c x) d)|)) (780 780 (:TYPE-PRESCRIPTION STRIP-CARS-GEN)) (692 692 (:TYPE-PRESCRIPTION GOOD-TAXON-INDEX-HALIST)) (580 40 (:DEFINITION ZERO-SCORES)) (469 469 (:TYPE-PRESCRIPTION FITCH-COMBINE-SCORES)) (368 368 (:REWRITE FOLD-CONSTS-IN-+)) (368 368 (:REWRITE |(< (+ c x y) d)|)) (368 368 (:REWRITE |(+ c (+ d x))|)) (364 66 (:REWRITE MEMBER-STRIP-CARS-GOOD-TAXON-BDD-ASSOC)) (346 346 (:REWRITE GOOD-TAXON-INDEX-HALIST-WHEN-NOT-CONSP)) (320 160 (:TYPE-PRESCRIPTION INTEGER-ASSOC-HQUAL-INTEGER-HALISTP)) (320 80 (:REWRITE ATOM-CDR-ASSOC-GOOD-TAXON-LIST)) (312 312 (:REWRITE SUBSET-SAME-MEMBERS)) (312 312 (:REWRITE MEMBER-PERM-GIVES-MEMBER)) (312 312 (:REWRITE MEMBER-DIFFERENCE-MEMBER)) (295 206 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (295 206 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (295 206 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (292 292 (:REWRITE PROPER-SUBTREE-MEMBER-GEN)) (292 292 (:REWRITE NOT-MEMBER-SUBSET)) (288 144 (:TYPE-PRESCRIPTION BOUND-TO-NAT-HET-NUMBER)) (280 40 (:DEFINITION HONS-MAKE-LIST-ACC)) (240 40 (:DEFINITION MAKE-LIST-AC)) (206 206 (:REWRITE |(equal (- x) (- y))|)) (184 184 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (184 184 (:REWRITE |(< d (+ c x))|)) (184 184 (:REWRITE |(< 0 (- x))|)) (184 184 (:DEFINITION FIX)) (184 46 (:REWRITE MEMBER-TAXA-ASSOC-HQUAL)) (160 160 (:TYPE-PRESCRIPTION INTEGER-HALISTP)) (160 160 (:TYPE-PRESCRIPTION GOOD-INDEX-TAXON-HALIST)) (160 40 (:REWRITE ASSOC-CAR-FROM-SUBSET)) (112 112 (:TYPE-PRESCRIPTION GOOD-TAXON-BDD-ALIST)) (80 80 (:REWRITE GOOD-INDEX-TAXON-HALIST-WHEN-NOT-CONSP)) (72 72 (:TYPE-PRESCRIPTION BOUND-TO-NAT-LIST)) (66 66 (:REWRITE GOOD-TAXON-BDD-ALIST-WHEN-NOT-CONSP)) (48 48 (:TYPE-PRESCRIPTION MAKE-LEAF-SCORE-LIST)) (46 46 (:REWRITE MEMBER-GIVES-ASSOC-HQUAL)) (40 40 (:REWRITE ZP-OPEN)) (40 8 (:REWRITE |(+ y x)|)) (38 38 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-<-0)) (38 38 (:REWRITE REDUCE-INTEGERP-+)) (38 38 (:REWRITE INTEGERP-MINUS-X)) (38 38 (:REWRITE |(< (- x) 0)|)) (38 38 (:META META-INTEGERP-CORRECT)) (8 8 (:TYPE-PRESCRIPTION ZERO-SCORES)) (8 8 (:REWRITE ASSOC-HQUAL-STATE-SCORELIST-MAP)) ) (FITCH-SCORE-SUBTREE (8970 18 (:DEFINITION FITCH-COMBINE-SCORES)) (7800 36 (:DEFINITION FITCH-COMBINE-SCORES1)) (5118 90 (:DEFINITION MIN-NIL-INF)) (4416 270 (:REWRITE |(< (if a b c) x)|)) (1878 1878 (:TYPE-PRESCRIPTION FITCH-COMBINE-SCORES1)) (1746 90 (:DEFINITION PLUS-NIL-INF)) (1722 1429 (:REWRITE DEFAULT-CDR)) (1440 180 (:REWRITE |(+ (if a b c) x)|)) (833 119 (:DEFINITION LEN)) (792 72 (:REWRITE |(+ (+ x y) z)|)) (674 290 (:REWRITE SIMPLIFY-SUMS-<)) (674 290 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (674 290 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (674 290 (:REWRITE DEFAULT-<-2)) (596 596 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (596 596 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (573 13 (:DEFINITION HONS-ASSOC-EQUAL)) (546 427 (:REWRITE DEFAULT-+-2)) (504 18 (:DEFINITION FITCH-INITIAL-SCORELIST)) (463 427 (:REWRITE DEFAULT-+-1)) (427 427 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (427 427 (:REWRITE NORMALIZE-ADDENDS)) (378 18 (:DEFINITION FITCH-INITIAL-SCORELIST1)) (360 36 (:REWRITE |(< x (if a b c))|)) (290 290 (:REWRITE DEFAULT-<-1)) (290 290 (:REWRITE |(< (- x) (- y))|)) (162 162 (:REWRITE |(< (+ c x) d)|)) (150 30 (:DEFINITION RATIONAL-OR-NIL-LISTP)) (124 31 (:REWRITE NOT-CONSP-ASSOC-NOT-ASSOC-HQUAL)) (116 116 (:TYPE-PRESCRIPTION GOOD-TAXON-INDEX-HALIST)) (103 22 (:REWRITE MEMBER-STRIP-CARS-GOOD-TAXON-BDD-ASSOC)) (93 93 (:TYPE-PRESCRIPTION STRIP-CARS-GEN)) (90 90 (:TYPE-PRESCRIPTION FITCH-COMBINE-SCORES)) (88 49 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (88 49 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (88 49 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (76 38 (:TYPE-PRESCRIPTION INTEGER-ASSOC-HQUAL-INTEGER-HALISTP)) (76 19 (:REWRITE MEMBER-TAXA-ASSOC-HQUAL)) (72 72 (:REWRITE FOLD-CONSTS-IN-+)) (72 72 (:REWRITE |(< (+ c x y) d)|)) (72 72 (:REWRITE |(+ c (+ d x))|)) (65 13 (:DEFINITION HONS-EQUAL)) (58 58 (:REWRITE GOOD-TAXON-INDEX-HALIST-WHEN-NOT-CONSP)) (49 49 (:REWRITE |(equal (- x) (- y))|)) (41 41 (:TYPE-PRESCRIPTION GOOD-TAXON-BDD-ALIST)) (40 40 (:REWRITE SUBSET-SAME-MEMBERS)) (40 40 (:REWRITE MEMBER-PERM-GIVES-MEMBER)) (40 40 (:REWRITE MEMBER-DIFFERENCE-MEMBER)) (38 38 (:TYPE-PRESCRIPTION INTEGER-HALISTP)) (37 37 (:REWRITE PROPER-SUBTREE-MEMBER-GEN)) (37 37 (:REWRITE NOT-MEMBER-SUBSET)) (36 36 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-0-<-A+AB)) (36 36 (:REWRITE |(< d (+ c x))|)) (36 36 (:REWRITE |(< 0 (- x))|)) (36 36 (:DEFINITION FIX)) (32 8 (:REWRITE ASSOC-CAR-FROM-SUBSET)) (30 2 (:DEFINITION ZERO-SCORES)) (22 22 (:REWRITE GOOD-TAXON-BDD-ALIST-WHEN-NOT-CONSP)) (20 20 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-<-0)) (20 20 (:REWRITE REDUCE-INTEGERP-+)) (20 20 (:REWRITE INTEGERP-MINUS-X)) (20 20 (:REWRITE |(< (- x) 0)|)) (20 20 (:META META-INTEGERP-CORRECT)) (19 19 (:REWRITE MEMBER-GIVES-ASSOC-HQUAL)) (16 8 (:TYPE-PRESCRIPTION BOUND-TO-NAT-HET-NUMBER)) (16 4 (:REWRITE ATOM-CDR-ASSOC-GOOD-TAXON-LIST)) (14 2 (:DEFINITION HONS-MAKE-LIST-ACC)) (12 2 (:DEFINITION MAKE-LIST-AC)) (8 8 (:TYPE-PRESCRIPTION GOOD-INDEX-TAXON-HALIST)) (4 4 (:TYPE-PRESCRIPTION BOUND-TO-NAT-LIST)) (4 4 (:REWRITE GOOD-INDEX-TAXON-HALIST-WHEN-NOT-CONSP)) (3 3 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-=-0)) (3 3 (:REWRITE CONSP-NOT-LEN-0)) (3 3 (:REWRITE |(equal (- x) 0)|)) (2 2 (:REWRITE ZP-OPEN)) (2 2 (:REWRITE ASSOC-HQUAL-STATE-SCORELIST-MAP)) ) (FITCH-SCORE-TREE (211 4 (:DEFINITION HONS-GET)) (162 2 (:DEFINITION FITCH-SCORE-SUBTREE)) (138 3 (:DEFINITION HONS-ASSOC-EQUAL)) (113 9 (:REWRITE NOT-MEMBER-NOT-CONSP-ASSOC)) (92 1 (:DEFINITION TREE-MATCHES-SEQUENCES)) (88 2 (:DEFINITION MAKE-LEAF-SCORE-LIST)) (48 46 (:REWRITE DEFAULT-CAR)) (37 34 (:REWRITE DEFAULT-CDR)) (35 5 (:DEFINITION LEN)) (33 9 (:REWRITE MEMBER-GEN-WHEN-NOT-CONS)) (32 8 (:REWRITE NOT-CONSP-ASSOC-NOT-ASSOC-HQUAL)) (32 1 (:DEFINITION CHARSTATE-SCORELIST-MAP-P)) (24 24 (:TYPE-PRESCRIPTION STRIP-CARS-GEN)) (22 22 (:TYPE-PRESCRIPTION GOOD-TAXON-INDEX-HALIST)) (17 17 (:TYPE-PRESCRIPTION MEMBER-GEN)) (15 3 (:DEFINITION HONS-EQUAL)) (12 3 (:REWRITE MEMBER-TAXA-ASSOC-HQUAL)) (12 3 (:REWRITE MEMBER-STRIP-CARS-GOOD-TAXON-BDD-ASSOC)) (12 1 (:DEFINITION ZERO-SCORES)) (11 11 (:REWRITE GOOD-TAXON-INDEX-HALIST-WHEN-NOT-CONSP)) (11 6 (:REWRITE DEFAULT-+-2)) (10 10 (:TYPE-PRESCRIPTION LEN)) (9 9 (:REWRITE SUBSET-SAME-MEMBERS)) (9 9 (:REWRITE STRIP-CARS-GEN-WHEN-NOT-CONSP)) (9 9 (:REWRITE PROPER-SUBTREE-MEMBER-GEN)) (9 9 (:REWRITE NOT-MEMBER-SUBSET)) (9 9 (:REWRITE MEMBER-PERM-GIVES-MEMBER)) (9 9 (:REWRITE MEMBER-DIFFERENCE-MEMBER)) (8 8 (:TYPE-PRESCRIPTION HONS-ASSOC-EQUAL)) (8 4 (:TYPE-PRESCRIPTION INTEGER-ASSOC-HQUAL-INTEGER-HALISTP)) (8 2 (:REWRITE ATOM-CDR-ASSOC-GOOD-TAXON-LIST)) (7 1 (:DEFINITION HONS-MAKE-LIST-ACC)) (6 6 (:TYPE-PRESCRIPTION GOOD-TAXON-BDD-ALIST)) (6 6 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (6 6 (:REWRITE NORMALIZE-ADDENDS)) (6 6 (:REWRITE DEFAULT-+-1)) (6 1 (:DEFINITION MAKE-LIST-AC)) (5 4 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (5 4 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (5 4 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (5 1 (:DEFINITION RATIONAL-OR-NIL-LISTP)) (4 4 (:TYPE-PRESCRIPTION INTEGER-HALISTP)) (4 4 (:TYPE-PRESCRIPTION GOOD-INDEX-TAXON-HALIST)) (4 4 (:REWRITE |(equal (- x) (- y))|)) (3 3 (:REWRITE MEMBER-GIVES-ASSOC-HQUAL)) (3 3 (:REWRITE GOOD-TAXON-BDD-ALIST-WHEN-NOT-CONSP)) (2 2 (:REWRITE GOOD-INDEX-TAXON-HALIST-WHEN-NOT-CONSP)) (1 1 (:REWRITE ZP-OPEN)) (1 1 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-<-0)) (1 1 (:REWRITE SIMPLIFY-SUMS-<)) (1 1 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (1 1 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (1 1 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (1 1 (:REWRITE REDUCE-INTEGERP-+)) (1 1 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (1 1 (:REWRITE INTEGERP-MINUS-X)) (1 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE |(< (- x) 0)|)) (1 1 (:REWRITE |(< (- x) (- y))|)) (1 1 (:META META-INTEGERP-CORRECT)) ) (FITCH-SCORE-TREES (64 2 (:DEFINITION CHARSTATE-SCORELIST-MAP-P)) (16 16 (:REWRITE DEFAULT-CAR)) (14 2 (:DEFINITION LEN)) (13 13 (:REWRITE DEFAULT-CDR)) (12 12 (:TYPE-PRESCRIPTION LEN)) (10 2 (:DEFINITION RATIONAL-OR-NIL-LISTP)) (4 2 (:REWRITE SIMPLIFY-SUMS-EQUAL)) (4 2 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-EQUAL)) (4 2 (:REWRITE PREFER-POSITIVE-ADDENDS-EQUAL)) (4 2 (:REWRITE DEFAULT-+-2)) (2 2 (:TYPE-PRESCRIPTION RATIONAL-OR-NIL-LISTP)) (2 2 (:REWRITE SIMPLIFY-TERMS-SUCH-AS-A+AB-<-0)) (2 2 (:REWRITE SIMPLIFY-SUMS-<)) (2 2 (:REWRITE SIMPLIFY-PRODUCTS-GATHER-EXPONENTS-<)) (2 2 (:REWRITE REMOVE-WEAK-INEQUALITIES-TWO)) (2 2 (:REWRITE REMOVE-WEAK-INEQUALITIES-ONE)) (2 2 (:REWRITE REDUCE-INTEGERP-+)) (2 2 (:REWRITE PREFER-POSITIVE-ADDENDS-<)) (2 2 (:REWRITE NORMALIZE-TERMS-SUCH-AS-A/A+B-+-B/A+B)) (2 2 (:REWRITE NORMALIZE-ADDENDS)) (2 2 (:REWRITE INTEGERP-MINUS-X)) (2 2 (:REWRITE DEFAULT-<-2)) (2 2 (:REWRITE DEFAULT-<-1)) (2 2 (:REWRITE DEFAULT-+-1)) (2 2 (:REWRITE |(equal (- x) (- y))|)) (2 2 (:REWRITE |(< (- x) 0)|)) (2 2 (:REWRITE |(< (- x) (- y))|)) (2 2 (:META META-INTEGERP-CORRECT)) (2 2 (:DEFINITION VALID-CHAR)) )
import React from 'react'; import PropTypes from 'prop-types'; import CircularProgress from '@mui/material/CircularProgress'; import { makeStyles } from '@mui/material/styles'; import Typography from '@mui/material/Typography'; const useStyles = makeStyles({ root: { width: '100%', textAlign: 'center', }, }, { name: 'Loading' }); function Loading({ message }) { const classes = useStyles(); return ( <div className={classes.root}> <CircularProgress size={300} mode="indeterminate" /> <Typography>{message}</Typography> </div> ); } Loading.propTypes = { message: PropTypes.string.isRequired, }; export default Loading;
import { notification } from 'antd'; import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Route, Switch, useRouteMatch } from 'react-router'; import { useInjectReducer, useInjectSaga } from 'utils/redux-injectors'; import CreateForm from './CreateForm'; import Overview from './Overview'; import Product from './Product'; import { productsSaga } from './saga'; import { selectError, selectNotice } from './selectors'; import { actions, reducer, sliceKey } from './slice'; export default function Products() { useInjectSaga({ key: sliceKey, saga: productsSaga }); useInjectReducer({ key: sliceKey, reducer: reducer }); const match = useRouteMatch(); const dispatch = useDispatch(); const error = useSelector(selectError); const notice = useSelector(selectNotice); useEffect(() => { if (notice) { notification.success({ message: notice, placement: 'bottomRight', duration: 6, }); dispatch(actions.setNotice(null)); } }, [dispatch, notice]); useEffect(() => { if (error) { notification.error({ message: error, placement: 'bottomRight', duration: 6, }); dispatch(actions.setError(null)); } }, [dispatch, error]); return ( <Switch> <Route exact path={match.url} component={Overview}></Route> <Route exact path={`${match.url}/create`} component={CreateForm}></Route> <Route exact path={`${match.url}/:productId`} component={Product}></Route> </Switch> ); }
#!/usr/bin/env bash PREFIX=/opt ENABLE_SERVICE=1 if [ $# -gt 0 ];then if [ "$(echo $1|cut -d '=' -f1)" = "--prefix" ];then prefix_tmp="$(echo $1|cut -d '=' -f2)" if [ "$prefix_tmp" != "" ];then PREFIX="$prefix_tmp" fi fi fi cmd () { echo "$" "$@" "$@" ret=$? if [ $ret -ne 0 ];then exit $ret fi } top_dir=$(cd "$(dirname "$0")" && pwd) cmd cd "$top_dir" || exit 1 # For common usage cmd sudo apt install -y git # Tsd2Gspread cmd sudo pip3 install tsd2gspread # For BME280 # [Raspberry Piで温度湿度気圧を測ってスマホで見る](https://rcmdnk.com/blog/2019/08/26/computer-iot-raspberrypi/) cmd cd "$top_dir" || exit 1 cmd sudo apt install -y libi2c-dev i2c-tools wiringpi #cmd git clone https://github.com/andreiva/raspberry-pi-bme280.git cmd sudo pip3 install smbus2 # For MH-Z19B cmd sudo pip3 install pyserial cmd sudo pip3 install mh-z19 # For metrics cmd sudo pip3 install psutil # For COCORO cmd sudo pip3 install cocoro # For Blynk # [Blynkを使ってRaspberryi Piをスマホから操作する](https://rcmdnk.com/blog/2019/08/18/computer-iot-raspberrypi/) cmd cd "$top_dir" || exit 1 #cmd git clone https://github.com/blynkkk/blynk-library.git #cmd cd blynk-library/linux cd submodules/blynk-library/linux || exit 1 cmd make clean all target=raspberry # Install executables cmd cd "$top_dir" || exit 1 dest_bin="$PREFIX/bin" cmd mkdir -p "$dest_bin" for f in "$top_dir"/bin/*;do if [ -f "$f" ];then dest_file="$dest_bin/$(basename "$f")" cmd rm -f "$dest_file" cmd ln -s $f "$dest_file" cmd chmod 755 "$dest_file" fi done # Service cmd cd "$top_dir" || exit 1 services=() for f in ./etc/systemd/system/*;do if [ ! -f "$f" ];then continue fi dest_file=/etc/systemd/system/$(basename "$f") cmd sudo cp "$f" "$dest_file" cmd sed -i"" "s|PREFIX_BIN|$dest_bin|g" "$dest_file" name=$(basename "$f") if [ "$name" != "bme280.service" ] \ && [ "$name" != "mhz19.service" ] \ && [ "$name" != "metrics.service" ];then services=("${services[@]}" "$name") fi done cmd sudo systemctl daemon-reload if [ "$ENABLE_SERVICE" -eq 1 ];then for s in "${services[@]}";do cmd sudo systemctl enable "$s" cmd sudo systemctl restart "$s" done fi
package net.anotheria.moskito.extensions.codebeamer; import net.anotheria.anoplass.api.APIFactory; import net.anotheria.anoplass.api.APIFinder; import net.anotheria.anoprise.metafactory.ServiceFactory; import net.anotheria.moskito.webui.accumulators.api.AccumulatorAPI; public class CBAccumulatorApiFactory implements APIFactory<AccumulatorAPI> , ServiceFactory<AccumulatorAPI> { private Integer sizeOfHistory = 4140; public CBAccumulatorApiFactory(Integer sizeOfHistory) { super(); this.sizeOfHistory = sizeOfHistory; } @Override public AccumulatorAPI createAPI() { CBAccumulatorApiImpl cbAccumulatorApiImpl = new CBAccumulatorApiImpl(); cbAccumulatorApiImpl.setMaxValues(sizeOfHistory); return cbAccumulatorApiImpl; } @Override public AccumulatorAPI create() { APIFinder.addAPIFactory(AccumulatorAPI.class, this); return APIFinder.findAPI(AccumulatorAPI.class); } }
--- title: Calender 日历组件 --- # Calender 日历组件 ### 使用方法 <ClientOnly> <calendar-demo/> </ClientOnly> ### 示例代码: ```vue <x-calendar></x-calendar> ```
import React from "react"; import fetch from "isomorphic-fetch"; import { withRouter } from "next/router"; import MainLayout from "components/MainLayout"; import BreadcrumbsModule from "components/PrimarySourceSetsComponents/BreadcrumbsModule"; import ImageAndCaption from "components/ExhibitionsComponents/Exhibition/ImageAndCaption"; import Details from "components/ExhibitionsComponents/Exhibition/Details"; import { EXHIBITS_ENDPOINT, EXHIBIT_PAGES_ENDPOINT, FILES_ENDPOINT, ITEMS_ENDPOINT } from "constants/exhibitions"; import { SEO_TYPE } from "constants/exhibition"; import { API_ENDPOINT } from "constants/items"; import { getCurrentUrl, getCurrentFullUrl, getDplaItemIdFromExhibit, removeQueryParams } from "lib"; class Exhibition extends React.Component { componentDidMount() { window.scrollTo(0, 0); document.body.focus(); } render() { const { router, exhibition, currentFullUrl } = this.props; return ( <MainLayout route={router} pageImage={exhibition.thumbnailUrl} pageTitle={exhibition.title.replace(/\*/g, "")} seoType={SEO_TYPE} > <BreadcrumbsModule breadcrumbs={[ { title: "Exhibitions", url: "/exhibitions", as: "/exhibitions" }, { title: exhibition.title, search: "" } ]} route={router} /> <div id="main" role="main"> <ImageAndCaption exhibition={exhibition} route={router} /> <Details exhibition={exhibition} route={router} currentFullUrl={currentFullUrl} /> </div> </MainLayout> ); } } Exhibition.getInitialProps = async ({ query, req }) => { const currentFullUrl = getCurrentFullUrl(req); const currentUrl = getCurrentUrl(req); const { exhibition: exhibitionSlug } = query; const exhibitionsRes = await fetch(`${currentUrl}${EXHIBITS_ENDPOINT}`); const exhibitionsJson = await exhibitionsRes.json(); const exhibition = exhibitionsJson.find( exhibition => exhibition.slug === exhibitionSlug ); const exhibitPageRes = await fetch( `${currentUrl}${EXHIBIT_PAGES_ENDPOINT}?exhibit=${exhibition.id}` ); const exhibitPageJson = await exhibitPageRes.json(); const sortedExhibitPages = exhibitPageJson .filter(exhibition => !exhibition.parent) .sort((a, b) => a.order - b.order); // just in case order isn't consistent, try checking the slug first const homePage = sortedExhibitPages.find( exhibit => exhibit.slug === "home-page" || exhibit.slug === "homepage" ) || sortedExhibitPages[0]; const { text } = homePage.page_blocks[0]; const { item, caption } = homePage.page_blocks[0].attachments[0]; // Get homepage item file const filesRes = await fetch( `${currentUrl}${FILES_ENDPOINT}?item=${item.id}` ); const filesJson = await filesRes.json(); // Get homepage item (full metadata) const itemRes = await fetch(`${currentUrl}${ITEMS_ENDPOINT}/${item.id}`); const itemJson = await itemRes.json(); // Get DPLA item ID const dplaItemId = getDplaItemIdFromExhibit(itemJson); // Call DPLA API const dplaApiRes = await fetch(`${currentUrl}${API_ENDPOINT}/${dplaItemId}`); const dplaItemJson = await dplaApiRes.json(); const thumbnailUrl = filesJson[0].file_urls.fullsize; return { currentFullUrl, exhibition: Object.assign({}, exhibition, { thumbnailUrl, caption, text, dplaItemId, dplaItemJson, sections: sortedExhibitPages.slice(1) }) }; }; export default withRouter(Exhibition);
using System; namespace Enigma.Reflection.Emit { public interface IILCode { void Generate(ILExpressed il); } public interface IILCodeParameter { Type ParameterType { get; } void Load(ILExpressed il); void LoadAddress(ILExpressed il); } }
# # Copyright (c) 2013-2021 Christian Jaeger, copying@christianjaeger.ch # # This is free software, offered under either the same terms as perl 5 # or the terms of the Artistic License version 2 or the terms of the # MIT License (Expat version). See the file COPYING.md that came # bundled with this file. # =head1 NAME FP::Lazy::t -- tests for FP::Lazy =head1 SYNOPSIS =head1 DESCRIPTION Had to move them here to avoid dependency cycle. =cut package FP::Lazy::t; use strict; use warnings; use warnings FATAL => 'uninitialized'; use FP::Lazy ":all"; use Chj::TEST; use FP::Show; use FP::List; TEST { our $foo = ""; sub moo { my ($bar) = @_; local $foo = "Hello"; lazy {"$foo $bar"} } moo("you")->force } " you"; TEST { show(lazy { 1 / 0 }) } "lazy { 'DUMMY' }"; TEST { show(lazyT { 1 / 0 } "Fun") } "lazyT { 'DUMMY' } 'Fun'"; TEST { my $v = lazyT { cons(1, 2) } "FP::List::List"; force $v; [is_promise($v), show($v)] } [1, 'improper_list(1, 2)']; # method dispatch logic: TEST { (lazyT { list("a") } "FP::List::List")->rest } null; TEST { (lazyT { list("a") } "FP::List::Pair")->rest } null; TEST_EXCEPTION { (lazyT { 1 / 0 } "FP::List::Null")->rest } 'can\'t take the rest of the empty list'; 1
import 'package:cloud_firestore/cloud_firestore.dart'; extension AppFireStore on FirebaseFirestore { CollectionReference get branch => collection('branch'); CollectionReference get issueCaseCollection => collection('issueCase'); CollectionReference get doctorCollection => collection('doctor'); CollectionReference get userCollection => collection('user'); CollectionReference get appointmentCollection => collection('appointment'); Future<DocumentReference> branchDocument(String id) async { return FirebaseFirestore.instance.branch.doc(id); } } extension AppDocumentReference on DocumentReference { }
/* Write a program that reads a string from the console and replaces all series of consecutive identical letters with a single one.*/ using System; using System.Text; namespace _23.SeriesOfLetter { class SeriesOfLetter { static void Main(string[] args) { Console.WriteLine("Enter your string. "); Console.Write("String = "); String userString = Console.ReadLine(); StringBuilder result = new StringBuilder(); result.Append(userString[0]); for (int i = 1; i < userString.Length; i++) { if (userString[i] != userString[i - 1]) { result.Append(userString[i]); } } Console.WriteLine(result.ToString()); } } }
module Vmdb::Loggers class IoLogger < StringIO def initialize(logger, level = :info, prefix = nil) @logger = logger @level = level @prefix = prefix super() end def write(*args) args.each do |arg| @buffer ||= "" @buffer << arg dump_buffer if arg.include?("\n") end end def <<(string) write(string) end private def dump_buffer @buffer.each_line do |l| next if l.empty? line = [@prefix, l].join(" ").strip @logger.send(@level, line) end @buffer = nil end end end
require 'active_record' module XM module Models class Schedule < ActiveRecord::Base ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: File.expand_path('../../../schedules/schedules.db', __FILE__) self.inheritance_column = nil end end end
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def cas auth = request.env["omniauth.auth"] @user = User.where(email: auth["uid"].downcase).first if @user.present? sign_in_and_redirect @user, event: :authentication else redirect_to new_user_session_path error: t(:omniauth_invalid_user) end end end
class AllLanguages { static const zh_Hant_HK = 'zh_Hant_HK'; static const zh_MO = 'zh_MO'; static const zh_Hans_MO = 'zh_Hans_MO'; static const zh_Hans = 'zh_Hans'; static const zh_Hant = 'zh_Hant'; static const zh_Hant_TW = 'zh_Hant_TW'; static const zh_Hant_MO = 'zh_Hant_MO'; static const zh_SG = 'zh_SG'; static const zh_Hans_CN = 'zh_Hans_CN'; static const zh_HK = 'zh_HK'; static const zh = 'zh'; static const zh_TW = 'zh_TW'; static const ja = 'ja'; static const en = 'en'; static const zh_Hans_HK = 'zh_Hans_HK'; static const zh_CN = 'zh_CN'; static const zh_Hans_SG = 'zh_Hans_SG'; static const zh_Hant_CN = 'zh_Hant_CN'; static List<String> listEN = [en]; static List<String> listJA = [ja]; //繁体 static List<String> listTR = [zh_Hant_HK, zh_MO, zh_Hant, zh_Hant_TW, zh_Hant_MO, zh_SG, zh_HK, zh_TW, zh_Hant_CN]; //简体 static List<String> listCN = [zh_Hans_MO, zh_Hans, zh_Hans_CN, zh, zh_Hans_HK, zh_CN, zh_Hans_SG]; }
import { Payment, PaymentArgs } from 'connext/types' import { CustodialPaymentsDao } from './CustodialPaymentsDao' import { PaymentMetaDao } from '../dao/PaymentMetaDao' import { default as DBEngine, SQL } from '../DBEngine' import { assert, getTestConfig, getTestRegistry, TestServiceRegistry } from '../testing' import { channelUpdateFactory } from '../testing/factories' import { mkAddress } from '../testing/stateUtils' import { Logger } from '../util' const logLevel = 0 const log = new Logger('CustodialPaymentsDaoTest', logLevel) export async function createTestPayment( registry: TestServiceRegistry, args: Partial<PaymentArgs> = {}, paymentAmount: Partial<Payment> = {}, recipient = mkAddress('0x555'), ) { const dao: CustodialPaymentsDao = registry.get('CustodialPaymentsDao') const paymentDao: PaymentMetaDao = registry.get('PaymentMetaDao') const { update, user } = await channelUpdateFactory(registry, {}, 'Payment', { amountWei: '69', amountToken: '420', ...args, }) const paymentId = await paymentDao.save('foo', { recipient, amount: { amountWei: '69', amountToken: '420', ...paymentAmount, }, type: 'PT_CHANNEL', meta: {}, }) log.info(`UPD: ${update}`) await dao.createCustodialPayment(paymentId, update.id) return { update, user, paymentId, recipient } } describe('CustodialPaymentsDao', () => { const registry = getTestRegistry({ Config: getTestConfig({ logLevel }) }) const db: DBEngine = registry.get('DBEngine') const dao: CustodialPaymentsDao = registry.get('CustodialPaymentsDao') beforeEach(async () => await registry.clearDatabase()) describe('createCustodialPayment', () => { it('works', async () => { const { paymentId } = await createTestPayment(registry) assert.containSubset((await db.queryOne(SQL`select * from payments where id = ${paymentId}`)), { 'amount_token': '420', 'amount_wei': '69', 'contract': '0xCCC0000000000000000000000000000000000000', 'payment_type': 'PT_CUSTODIAL', 'purchase_id': 'foo', 'recipient': '0x5550000000000000000000000000000000000000', 'sender': '0xAAA0000000000000000000000000000000000000', }) }) it('fails if update does not match payment', async () => { await assert.isRejected( createTestPayment(registry, { amountWei: '5' }), /payment amount does not match update/ ) }) }) })
import { __decorate } from "tslib"; import { CommonModule } from "@angular/common"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; import { RouterModule } from "@angular/router"; import { AppButtonModule } from "src/app/components/button/button.module"; import { AppLabelModule } from "src/app/components/label/label.module"; import { AppSelectCommentModule } from "src/app/components/select/comment/comment.module"; import { AppSelectPostModule } from "src/app/components/select/post/post.module"; import { AppSelectUserModule } from "src/app/components/select/user/user.module"; import { AppFormComponent } from "./form.component"; const ROUTES = [ { path: "", component: AppFormComponent } ]; let AppFormModule = class AppFormModule { }; AppFormModule = __decorate([ NgModule({ declarations: [AppFormComponent], imports: [ CommonModule, FormsModule, ReactiveFormsModule, RouterModule.forChild(ROUTES), AppButtonModule, AppLabelModule, AppSelectCommentModule, AppSelectPostModule, AppSelectUserModule ] }) ], AppFormModule); export { AppFormModule }; //# sourceMappingURL=form.module.js.map
use lockbook_core::repo::local_storage; use test_utils::test_config; #[test] fn read() { let db = &test_config(); let result: Option<Vec<u8>> = local_storage::read(db, "namespace", "key").unwrap(); assert_eq!(result, None); } #[test] fn write_read() { let db = &test_config(); local_storage::write(db, "namespace", "key", "value".as_bytes()).unwrap(); let result: Vec<u8> = local_storage::read(db, "namespace", "key") .unwrap() .unwrap(); assert_eq!(String::from_utf8_lossy(&result), "value"); } #[test] fn overwrite_read() { let db = &test_config(); local_storage::write(db, "namespace", "key", "value-1".as_bytes()).unwrap(); local_storage::write(db, "namespace", "key", "value-2".as_bytes()).unwrap(); let result: Vec<u8> = local_storage::read(db, "namespace", "key") .unwrap() .unwrap(); assert_eq!(String::from_utf8_lossy(&result), "value-2"); } #[test] fn delete() { let db = &test_config(); local_storage::write(db, "namespace", "key-1", "value-1".as_bytes()).unwrap(); local_storage::write(db, "namespace", "key-2", "value-2".as_bytes()).unwrap(); local_storage::delete(db, "namespace", "key-2").unwrap(); let result1: Vec<u8> = local_storage::read(db, "namespace", "key-1") .unwrap() .unwrap(); let result2: Option<Vec<u8>> = local_storage::read(db, "namespace", "key-2").unwrap(); assert_eq!(String::from_utf8_lossy(&result1), "value-1"); assert_eq!(result2, None); } #[test] fn delete_all() { let db = &test_config(); local_storage::write(db, "namespace", "key-1", "value-1".as_bytes()).unwrap(); local_storage::write(db, "namespace", "key-2", "value-2".as_bytes()).unwrap(); local_storage::delete_all(db, "namespace").unwrap(); let result1: Option<Vec<u8>> = local_storage::read(db, "namespace", "key-1").unwrap(); let result2: Option<Vec<u8>> = local_storage::read(db, "namespace", "key-2").unwrap(); assert_eq!(result1, None); assert_eq!(result2, None); } #[test] fn delete_all_no_writes() { let db = &test_config(); local_storage::delete_all(db, "namespace").unwrap(); } #[test] fn dump() { let db = &test_config(); local_storage::write(db, "namespace", "key-1", "value-1".as_bytes()).unwrap(); local_storage::write(db, "namespace", "key-4", "value-4".as_bytes()).unwrap(); local_storage::write(db, "namespace", "key-3", "value-3".as_bytes()).unwrap(); local_storage::write(db, "namespace", "key-2", "value-2".as_bytes()).unwrap(); local_storage::write(db, "namespace", "key-5", "value-5".as_bytes()).unwrap(); let result: Vec<Vec<u8>> = local_storage::dump(db, "namespace").unwrap(); assert_eq!( result, vec![ "value-1".as_bytes(), "value-2".as_bytes(), "value-3".as_bytes(), "value-4".as_bytes(), "value-5".as_bytes(), ] ); }
--- name: bucket.diskCreateOperationsPerSecond type: attribute events: - CouchbaseBucketSample --- Number of new items created on disk per second for this bucket.
/* * Copyright (C) 2012-2018 Gregory Hedlund * * 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 ca.phon.plugins.praat.script; import java.io.*; import java.util.*; import org.apache.velocity.*; import org.apache.velocity.app.*; import org.apache.velocity.runtime.*; import org.apache.velocity.runtime.resource.loader.*; import org.apache.velocity.runtime.resource.util.*; /** * Helper class for loading script templates * and filling in values. * */ public class PraatScript { private String scriptTemplate; private String scriptText; /** * Constructor */ public PraatScript() { super(); scriptTemplate = new String(); } public PraatScript(String scriptText) { super(); this.scriptText = scriptText; } public PraatScript(String scriptText, String scriptTemplate) { super(); this.scriptTemplate = scriptTemplate; this.scriptText = scriptText; } public String getScriptTemplate() { return this.scriptTemplate; } public void setScriptTemplate(String script) { this.scriptTemplate = script; } public String getScriptText() { return scriptText; } public void setScriptText(String scriptText) { this.scriptText = scriptText; } /** * Generate a script from the specified template * using the given object map. * * @param template * @param objMap * * @return script * * @throws IOException */ public String generateScript(PraatScriptContext ctx) throws IOException { final Properties p = new Properties(); p.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); p.setProperty("string.resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader"); p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.JdkLogChute"); p.setProperty("runtime.log.logsystem.jdk.logger", "ca.phon.velocity"); p.setProperty("runtime.log.logsystem.jdk.logger.level", "FINE"); final VelocityEngine ve = new VelocityEngine(); ve.init(p); if(scriptTemplate == null || scriptTemplate.length() == 0) { // install string and set template name scriptTemplate = UUID.randomUUID().toString(); StringResourceRepository repository = StringResourceLoader.getRepository(); repository.putStringResource(scriptTemplate, scriptText); } // load template final Template t = ve.getTemplate(getScriptTemplate()); final StringWriter sw = new StringWriter(); t.merge(ctx.velocityContext(), sw); return sw.toString(); } }
import { useCallback, useMemo, useState } from "react"; import { useAxiosWithTokenRefresh } from "./auth-api"; import { OrganizationListenerData, OrganizationListenerDeleteData, OrganizationListenerPostData, OrganizationListenerViewProps, } from "../../types/organizations"; import { errorHandlerWrapper, resolveApiError } from "../../utils/error-utils"; export function useGetOrganizationListeners() { const [organizationListeners, setOrganizationListeners] = useState< OrganizationListenerViewProps[] >([]); const [{ loading }, apiCall] = useAxiosWithTokenRefresh< OrganizationListenerData[] >( { url: "/organizations/listeners", method: "get", }, { manual: true }, ); const getOrganizationListeners = useCallback(async () => { try { return await errorHandlerWrapper(async () => { const { data: listeners = [] } = await apiCall(); console.log("GET /organizations/listeners success:", listeners); setOrganizationListeners(listeners); return listeners; }, "GET /organizations/listeners error:")(); } catch (error) { resolveApiError(error); setOrganizationListeners([]); return []; } }, [apiCall]); return { organizationListeners, isLoading: loading, getOrganizationListeners, }; } export function useCreateOrganizationListeners() { const [{ loading }, apiCall] = useAxiosWithTokenRefresh< OrganizationListenerData[] >( { url: "/organizations/listeners", method: "post", }, { manual: true }, ); const createOrganizationListeners = useMemo( () => errorHandlerWrapper(async (listeners: OrganizationListenerPostData[]) => { const { data: newListeners = [] } = await apiCall({ data: { listeners }, }); console.log("POST /organizations/listeners success:", newListeners); if (newListeners.length === 0) { throw new Error("No new CC emails were added."); } return newListeners; }, "POST /organizations/listeners error:"), [apiCall], ); return { isLoading: loading, createOrganizationListeners, }; } export function useDeleteOrganizationListeners() { const [{ loading }, apiCall] = useAxiosWithTokenRefresh< OrganizationListenerData[] >( { url: "/organizations/listeners", method: "delete", }, { manual: true }, ); const deleteOrganizationListeners = useMemo( () => errorHandlerWrapper(async (ids: number[]) => { const organizationListenerDeleteData: OrganizationListenerDeleteData = { ids, }; const { data: deletedListeners = [] } = await apiCall({ data: organizationListenerDeleteData, }); console.log( "DELETE /organizations/listeners success:", deletedListeners, ); if (deletedListeners.length === 0) { throw new Error("No CC emails were removed."); } return deletedListeners; }, "DELETE /organizations/listeners error:"), [apiCall], ); return { isLoading: loading, deleteOrganizationListeners }; }
use itertools::Itertools; use serde_scan::scan; use std::{collections::HashMap, fs}; type Point = (usize, usize); fn read_input() -> Vec<(Point, Point)> { let raw_data = fs::read_to_string("inputs/5").unwrap(); raw_data .lines() .map(|line| -> (Point, Point) { scan!("{},{} -> {},{}" <- line).unwrap() }) .collect() } fn solve(manhattan: bool) -> usize { let mut segments = read_input(); if manhattan { segments = segments .into_iter() .filter(|(a, b)| a.0 == b.0 || a.1 == b.1) .collect_vec(); } let mut map = HashMap::new(); for (a, b) in &segments { let x_step = (b.0 as i32 - a.0 as i32).signum(); let y_step = (b.1 as i32 - a.1 as i32).signum(); let (mut x, mut y) = *a; loop { *map.entry((x, y)).or_insert(0) += 1; if (x, y) == *b { break; } x = (x as i32 + x_step) as usize; y = (y as i32 + y_step) as usize; } } map.values().filter(|&&v| v > 1).count() } #[allow(dead_code)] pub fn part1() { println!("day 5.1 {}", solve(true)); } #[allow(dead_code)] pub fn part2() { println!("day 5.2 {}", solve(false)); }
Recreation of the classic game Mastermind. A user navigates through text-based menus to read instructions, play, and set a difficulty. After setting a difficulty, the user attempts to guess the pattern that is set randomly by the computer. Feedback is given after each guess. Upon successfully guessing the pattern, the user is presented with their final time and number of guesses taken.
<?php declare(strict_types=1); namespace Onliner\ImgProxy\Options; final class Extend extends Option { /** * @var bool */ private $extend; /** * @var Gravity|null $gravity */ private $gravity; public function __construct(bool $extend = true, string $gravity = null) { $this->extend = $extend; if ($gravity !== null) { $this->gravity = Gravity::fromString($gravity); } } /** * @inheritDoc */ public function name(): string { return 'ex'; } /** * @inheritDoc */ public function data(): array { return array_merge( [(int) $this->extend], $this->gravity ? $this->gravity->data() : [] ); } }
//! This package provides various utility types and function that are too small //! to live in a separate package. #[macro_use] extern crate bitflags; #[macro_use] extern crate features; pub mod byte_slice_fmt; #[cfg(unix)] pub mod command; pub mod deterministic_operations; pub mod fs; pub mod ic_features; pub mod rle; pub mod serde_arc; pub mod thread;
// UnicodeFileToHtmlTextConverter exercise: // write the unit tests for the UnicodeFileToHtmlTextConverter class. // The UnicodeFileToHtmlTextConverter class is designed to reformat // a plain text file for display in a browser. describe('Unicode To Html Converter', function () { describe('UnicodeFileToHtmlTextConverter', function () { it('Do something', function () { var target = new UnicodeFileToHtmlTextConverter(); }); }); });
package parsers // Define types of expression tokens. const ( Unknown = iota LeftBrace RightBrace LeftSquareBrace RightSquareBrace Plus Minus Star Slash Procent Power Equal NotEqual More Less EqualMore EqualLess ShiftLeft ShiftRight And Or Xor Is In NotIn Element Null Not Like NotLike IsNull IsNotNull Comma Unary Function Variable Constant )
using System.Web; using System.Web.Optimization; namespace Hack121.Mvc { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqmeter").Include( "~/Scripts/jqmeter/jqmeter.js")); bundles.Add(new ScriptBundle("~/bundles/inputs").Include( "~/Scripts/inputs/*.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/controls").Include( "~/Scripts/gtm.js", "~/Scripts/select2.js", "~/Scripts/controls.js" )); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/twitter-bootstrap-hover-dropdown.js" )); bundles.Add(new StyleBundle("~/Content/plugins").Include( "~/Css/plugins/*.css")); bundles.Add(new StyleBundle("~/bundles/css").Include( "~/Css/style.css", "~/Css/materialize.css", "~/Css/jquery.dynatable.css" )); bundles.Add(new StyleBundle("~/Content/Theme/base/css").Include( "~/Css/Theme/base/jquery.ui.core.css", "~/Css/Theme/base/jquery.ui.resizable.css", "~/Css/Theme/base/jquery.ui.selectable.css", "~/Css/Theme/base/jquery.ui.accordion.css", "~/Css/Theme/base/jquery.ui.autocomplete.css", "~/Css/Theme/base/jquery.ui.button.css", "~/Css/Theme/base/jquery.ui.dialog.css", "~/Css/Theme/base/jquery.ui.slider.css", "~/Css/Theme/base/jquery.ui.tabs.css", "~/Css/Theme/base/jquery.ui.datepicker.css", "~/Css/Theme/base/jquery.ui.progressbar.css", "~/Css/Theme/base/jquery.ui.theme.css")); bundles.Add(new ScriptBundle("~/bundles/vendors").Include( "~/Css/Theme/vendors/uniform/jquery.uniform.js" , "~/Css/Theme/vendors/chosen.jquery.js" , "~/Css/Theme/vendors/bootstrap-datepicker/js/bootstrap-datepicker.js" , "~/Css/Theme/vendors/bootstrap-wysihtml5-rails-b3/vendor/assets/javascripts/bootstrap-wysihtml5/wysihtml5.js" , "~/Css/Theme/vendors/bootstrap-wysihtml5-rails-b3/vendor/assets/javascripts/bootstrap-wysihtml5/core-b3.js" , "~/Css/Theme/vendors/twitter-bootstrap-wizard/jquery.bootstrap.wizard-for.bootstrap3.js" , "~/Css/Theme/vendors/boostrap3-typeahead/bootstrap3-typeahead.js" , "~/Css/Theme/vendors/easypiechart/jquery.easy-pie-chart.js" , "~/Css/Theme/vendors/ckeditor/ckeditor.js" , "~/Css/Theme/vendors/tinymce/js/tinymce/tinymce.js" , "~/Css/Theme/vendors/bootstrap-wysihtml5-rails-b3/vendor/assets/javascripts/bootstrap-wysihtml5/wysihtml5.js" , "~/Css/Theme/vendors/bootstrap-wysihtml5-rails-b3/vendor/assets/javascripts/bootstrap-wysihtml5/core-b3.js" , "~/Css/Theme/vendors/jGrowl/jquery.jgrowl.js" , "~/Css/Theme/vendors/bootstrap-datepicker/js/bootstrap-datepicker.js" , "~/Css/Theme/vendors/sparkline/jquery.sparkline.js" , "~/Css/Theme/vendors/tablesorter/js/jquery.tablesorter.js" , "~/Css/Theme/vendors/flot/jquery.flot.js" , "~/Css/Theme/vendors/flot/jquery.flot.selection.js" , "~/Css/Theme/vendors/flot/jquery.flot.resize.js" , "~/Css/Theme/vendors/fullcalendar/fullcalendar.js" )); bundles.Add(new StyleBundle("~/Content/Theme").Include( "~/Css/bootstrap.css", "~/Css/bootstrap-theme.css", "~/Css/Theme/css/bootstrap-admin-theme.css", "~/Css/Theme/css/site.css")); bundles.Add(new StyleBundle("~/Content/Vendors").Include( "~/Css/Theme/vendors/bootstrap-datepicker/css/datepicker.css" , "~/Css/Theme/css/datepicker.fixes.css" , "~/Css/Theme/vendors/uniform/themes/default/css/uniform.default.min.css" , "~/Css/Theme/css/uniform.default.fixes.css" , "~/Css/Theme/vendors/chosen.min.css" , "~/Css/Theme/vendors/bootstrap-wysihtml5-rails-b3/vendor/assets/stylesheets/bootstrap-wysihtml5/core-b3.css" , "~/Css/Theme/vendors/easypiechart/jquery.easy-pie-chart.css" , "~/Css/Theme/vendors/easypiechart/jquery.easy-pie-chart_custom.css" , "~/Css/Theme/vendors/bootstrap-wysihtml5-rails-b3/vendor/assets/stylesheets/bootstrap-wysihtml5/core-b3.css" , "~/Css/Theme/vendors/jGrowl/jquery.jgrowl.css" , "~/Css/Theme/vendors/bootstrap-datepicker/css/datepicker.css" , "~/Css/Theme/vendors/fullcalendar/fullcalendar.css")); } } }
package typingsSlinky.lodash.fpMod import typingsSlinky.lodash.mod.ValueIterateeCustom import typingsSlinky.lodash.mod.__ import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait LodashFindIndexFrom1x4[T] extends StObject { def apply(predicate: ValueIterateeCustom[T, Boolean]): LodashFindIndexFrom1x5 = js.native def apply(predicate: ValueIterateeCustom[T, Boolean], fromIndex: Double): Double = js.native def apply(predicate: __, fromIndex: Double): LodashFindIndexFrom1x6[T] = js.native }
default_action :create attribute :name, [String, Symbol], required: true attribute :db_type, [:mysql, 'mysql', :postgresql, 'postgresql', :mongodb, 'mongodb'], required: true attribute :cron_minute, [String, Integer], default: lazy { get_default(:cron_minute) } attribute :cron_hour, [String, Integer], default: lazy { get_default(:cron_hour) } attribute :cron_weekday, [String, Integer], default: lazy { get_default(:cron_weekday) } attribute :cron_month, [String, Integer], default: lazy { get_default(:cron_month) } attribute :dbnames, String, default: lazy { get_default(:dbnames) } attribute :dbexclude, String, default: lazy { get_default(:dbexclude) } attribute :dbuser, [String, Symbol], default: lazy { get_default(:dbuser) } attribute :dir, String, default: lazy { get_default(:dir) } attribute :dir_permission, [String, Integer], default: lazy { get_default(:dir_permission) } attribute :file_permission, [String, Integer], default: lazy { get_default(:file_permission) } attribute :compression, [String, Symbol], default: lazy { get_default(:compression) } attribute :global, [String, TrueClass, FalseClass], default: lazy { get_default(:global) } attribute :host, String, default: lazy { get_default(:host) } attribute :port, [String, Integer], default: lazy { get_default(:port) } attribute :password, [String], default: lazy { get_default(:password) } attribute :group, [String, Symbol], default: lazy { get_default(:group) } attribute :owner, [String, Symbol], default: lazy { get_default(:owner) } attribute :runas, [String, Symbol], default: lazy { get_default(:runas) } attribute :keep_lasts, [String, Integer], default: lazy { get_default(:keep_lasts) } attribute :keep_days, [String, Integer], default: lazy { get_default(:keep_days) } attribute :keep_weeks, [String, Integer], default: lazy { get_default(:keep_weeks) } attribute :keep_months, [String, Integer], default: lazy { get_default(:keep_months) } attribute :keep_logs, [String, Integer], default: lazy { get_default(:keep_logs) } attribute :sock_paths, [String], default: lazy { get_default(:sock_paths) } def get_default(attribute) # User can override values per DB type, superior to global values if node['smart_db_backup'][self.db_type.to_s] superior_value = node['smart_db_backup'][self.db_type.to_s][attribute.to_s] return superior_value if superior_value end node['smart_db_backup'][attribute.to_s] end # MySQL specific action :create do config_file_path = "/etc/smart_db_backup/#{new_resource.name}.conf" pass_attributes_to_template = %w( db_type dbnames dbexclude dbuser dir dir_permission file_permission compression global host port password group owner runas keep_lasts keep_days keep_weeks keep_months keep_logs sock_paths ) template config_file_path do cookbook 'smart_db_backup' source 'config.erb' attributes = pass_attributes_to_template.each_with_object({}) do |attr, acc| acc[attr] = new_resource.public_send(attr) end variables(attributes) end cron "smart_backup_db_#{new_resource.name}" do command "/usr/local/bin/smart_db_backup #{config_file_path} > /dev/null" minute (new_resource.cron_minute || node['smart_db_backup']['cron_minute']) hour (new_resource.cron_hour || node['smart_db_backup']['cron_hour']) weekday (new_resource.cron_weekday || node['smart_db_backup']['cron_weekday']) month (new_resource.cron_month || node['smart_db_backup']['cron_month']) end end action :delete do config_file_path = "/etc/smart_db_backup/#{new_resource.name}.conf" file config_file_path do action :delete end cron "smart_backup_db_#{db_type}" do action :delete end end
set linesize 130 set pagesize 1000 SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id',&child));
import Data.List(takeWhile) primes :: [Integer] primes = sieve [2..] where sieve (p:ps) = p:sieve [q | q<-ps, q `mod` p /= 0] isInt f = floor f == ceiling f intSqrt :: Integral a => a -> (a, Bool) intSqrt n = (floor f, isInt f) where f = sqrt $ fromIntegral n weirdNs :: [Integer] weirdNs = helper primes where helper ps = if noSolution then helper (tail ps) else n:(helper (tail ps)) where (nsqr:others) = zipWith (-) ps [1,3,7,9,13,27] (n, perfect) = intSqrt nsqr noSolution = any (/=nsqr) others || (not perfect) main = do let limit = 10^6 print $ sum $ takeWhile (<limit) weirdNs
package packetdump import ( "github.com/pion/rtcp" "github.com/pion/rtp" ) // RTPFilterCallback can be used to filter RTP packets to dump. // The callback returns whether or not to print dump the packet's content. type RTPFilterCallback func(pkt *rtp.Packet) bool // RTCPFilterCallback can be used to filter RTCP packets to dump. // The callback returns whether or not to print dump the packet's content. type RTCPFilterCallback func(pkt []rtcp.Packet) bool
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.todou.nestrefresh.material.resources import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP import android.content.Context import android.content.res.ColorStateList import android.content.res.TypedArray import android.graphics.drawable.Drawable import android.os.Build.VERSION import android.os.Build.VERSION_CODES import androidx.annotation.RestrictTo import androidx.annotation.StyleableRes import androidx.appcompat.content.res.AppCompatResources /** * Utility methods to resolve resources for components. * * @hide */ @RestrictTo(LIBRARY_GROUP) object NRMaterialResources { /** * Returns the [ColorStateList] from the given [TypedArray] attributes. The resource * can include themeable attributes, regardless of API level. */ fun getColorStateList( context: Context, attributes: TypedArray, @StyleableRes index: Int ): ColorStateList? { if (attributes.hasValue(index)) { val resourceId = attributes.getResourceId(index, 0) if (resourceId != 0) { val value = AppCompatResources.getColorStateList(context, resourceId) if (value != null) { return value } } } // Reading a single color with getColorStateList() on API 15 and below doesn't always correctly // read the value. Instead we'll first try to read the color directly here. if (VERSION.SDK_INT <= VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { val color = attributes.getColor(index, -1) if (color != -1) { return ColorStateList.valueOf(color) } } return attributes.getColorStateList(index) } /** * Returns the [ColorStateList] from the given [NRTintTypedArray] attributes. The * resource can include themeable attributes, regardless of API level. */ fun getColorStateList( context: Context, attributes: NRTintTypedArray, @StyleableRes index: Int ): ColorStateList? { if (attributes.hasValue(index)) { val resourceId = attributes.getResourceId(index, 0) if (resourceId != 0) { val value = AppCompatResources.getColorStateList(context, resourceId) if (value != null) { return value } } } // Reading a single color with getColorStateList() on API 15 and below doesn't always correctly // read the value. Instead we'll first try to read the color directly here. if (VERSION.SDK_INT <= VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { val color = attributes.getColor(index, -1) if (color != -1) { return ColorStateList.valueOf(color) } } return attributes.getColorStateList(index) } /** * Returns the drawable object from the given attributes. * * * This method supports inflation of `<vector>` and `<animated-vector>` resources * on devices where platform support is not available. */ fun getDrawable( context: Context, attributes: TypedArray, @StyleableRes index: Int ): Drawable? { if (attributes.hasValue(index)) { val resourceId = attributes.getResourceId(index, 0) if (resourceId != 0) { val value = AppCompatResources.getDrawable(context, resourceId) if (value != null) { return value } } } return attributes.getDrawable(index) } /** * Returns a TextAppearanceSpan object from the given attributes. * * * You only need this if you are drawing text manually. Normally, TextView takes care of this. */ fun getTextAppearance( context: Context, attributes: TypedArray, @StyleableRes index: Int ): NRTextAppearance? { if (attributes.hasValue(index)) { val resourceId = attributes.getResourceId(index, 0) if (resourceId != 0) { return NRTextAppearance(context, resourceId) } } return null } /** * Returns the @StyleableRes index that contains value in the attributes array. If both indices * contain values, the first given index takes precedence and is returned. */ @StyleableRes internal fun getIndexWithValue(attributes: TypedArray, @StyleableRes a: Int, @StyleableRes b: Int): Int { return if (attributes.hasValue(a)) { a } else b } }
// // //import 'package:date/date.dart'; //import 'package:timezone/standalone.dart'; //import 'package:timeseries/timeseries.dart'; //import 'package:elec/src/time/calendar/calendars/nerc_calendar.dart'; //import 'package:load_viewer/src/lib_data.dart'; //import 'package:load_viewer/lib_shape_analysis.dart'; //import 'package:load_viewer/shape.dart'; // //getData() async { // NercCalendar _calendar = new NercCalendar(); // var location = getLocation('US/Eastern'); // var interval = Interval(TZDateTime(location, 2014, 1), // TZDateTime(location, 2017, 8)); // var data = await getHourlyRtSystemDemand(interval); // //data.take(5).forEach(print); // // var dataJul = new TimeSeries.fromIterable( // data.where((obs) => obs.interval.start.month == 7)); // dataJul.take(5).forEach(print); // //print(dataJul.length); // // var shapeByDay = hourlyShapeByDay(dataJul); // print(shapeByDay[new Date(2014,7,1)]); // // // keep only the non-holiday weekdays // List daysOut = []; // shapeByDay.keys.forEach((Date day) { // if (day.isWeekend() || _calendar.isHoliday(day)) // daysOut.add(day); // }); // daysOut.forEach((day) => shapeByDay.remove(day)); // // // // find the average shape of this year/month combination // var byYear = groupBy(shapeByDay.keys, (Date day) => day.year); // var avgShape = <int,HourlyShape>{}; // byYear.forEach((year,days) { // avgShape[year] = averageShape(days.map((day) => shapeByDay[day]).toList()); // print(avgShape[year].weights); // }); // // // print(avgShape); // //} // // //main() async { // initializeTimeZone(); // // await getData(); //}
package io.kommons.designpatterns.cqrs import io.kommons.designpatterns.cqrs.commands.CommandService import io.kommons.designpatterns.cqrs.domain.repository.AuthorRepository import io.kommons.designpatterns.cqrs.domain.repository.BookRepository import io.kommons.designpatterns.cqrs.queries.QueryService import io.kommons.junit.jupiter.random.RandomizedTest import io.kommons.logging.KLogging import org.amshove.kluent.shouldEqual import org.amshove.kluent.shouldEqualTo import org.amshove.kluent.shouldNotBeNull import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest /** * CqrsIntegrationTest * * @author debop */ @RandomizedTest @SpringBootTest(classes = [CqrsJpaConfiguration::class]) class CqrsIntegrationTest { companion object: KLogging() @Autowired private lateinit var command: CommandService @Autowired private lateinit var query: QueryService @Autowired private lateinit var authorRepo: AuthorRepository @Autowired private lateinit var bookRepo: BookRepository @BeforeAll fun beforeAll() { // create first author1 command.authorCreated("username1", "name1", "email1") // create author2 and update all it's data command.authorCreated("username2", "name2", "email2") command.authorEmailUpdated("username2", "new_email2") command.authorNameUpdated("username2", "new_name2") command.authorUsernameUpdated("username2", "new_username2") // add book1 to author1 command.bookAddedToAuthor("title1", 10.0, "username1") // add book2 to author1 and update all it's data command.bookAddedToAuthor("title2", 20.0, "username1") command.bookPriceUpdated("title2", 30.0) command.bookTitleUpdated("title2", "new_title2") } @Test fun `context loading`() { command.shouldNotBeNull() query.shouldNotBeNull() authorRepo.shouldNotBeNull() bookRepo.shouldNotBeNull() } @Test fun `get authors by username`() { val author = query.getAuthorByUsername("username1") author.shouldNotBeNull() author.username shouldEqual "username1" author.name shouldEqual "name1" author.email shouldEqual "email1" } @Test fun `get updated author by username`() { val author = query.getAuthorByUsername("new_username2") author.shouldNotBeNull() author.username shouldEqual "new_username2" author.name shouldEqual "new_name2" author.email shouldEqual "new_email2" } @Test fun `get book`() { val book = query.getBook("title1") book.shouldNotBeNull() book.title shouldEqual "title1" book.price shouldEqual 10.0 } @Test fun `get author books`() { val books = query.getAuthorBooks("username1") books.size shouldEqualTo 2 } @Test fun `get author books count`() { val bookCount = query.getAuthorBooksCount("username1") bookCount shouldEqualTo 2L } @Test fun `get authors count`() { val authorCount = query.getAuthorsCount() authorCount shouldEqualTo 2L } }
<?php // This file is auto-generated, don't edit it. Thanks. namespace AlibabaCloud\SDK\Linkedmall\V20180116\Models\ModifyBasicAndBizItemsRequest\itemList; use AlibabaCloud\Tea\Model; class skuList extends Model { /** * @var string */ public $benefitId; /** * @var int */ public $points; /** * @var int */ public $pointsAmount; /** * @var int */ public $priceCent; /** * @var int */ public $quantity; /** * @var int */ public $skuId; /** * @var int */ public $statusAction; /** * @var int */ public $supplierPrice; protected $_name = [ 'benefitId' => 'BenefitId', 'points' => 'Points', 'pointsAmount' => 'PointsAmount', 'priceCent' => 'PriceCent', 'quantity' => 'Quantity', 'skuId' => 'SkuId', 'statusAction' => 'StatusAction', 'supplierPrice' => 'SupplierPrice', ]; public function validate() { } public function toMap() { $res = []; if (null !== $this->benefitId) { $res['BenefitId'] = $this->benefitId; } if (null !== $this->points) { $res['Points'] = $this->points; } if (null !== $this->pointsAmount) { $res['PointsAmount'] = $this->pointsAmount; } if (null !== $this->priceCent) { $res['PriceCent'] = $this->priceCent; } if (null !== $this->quantity) { $res['Quantity'] = $this->quantity; } if (null !== $this->skuId) { $res['SkuId'] = $this->skuId; } if (null !== $this->statusAction) { $res['StatusAction'] = $this->statusAction; } if (null !== $this->supplierPrice) { $res['SupplierPrice'] = $this->supplierPrice; } return $res; } /** * @param array $map * * @return skuList */ public static function fromMap($map = []) { $model = new self(); if (isset($map['BenefitId'])) { $model->benefitId = $map['BenefitId']; } if (isset($map['Points'])) { $model->points = $map['Points']; } if (isset($map['PointsAmount'])) { $model->pointsAmount = $map['PointsAmount']; } if (isset($map['PriceCent'])) { $model->priceCent = $map['PriceCent']; } if (isset($map['Quantity'])) { $model->quantity = $map['Quantity']; } if (isset($map['SkuId'])) { $model->skuId = $map['SkuId']; } if (isset($map['StatusAction'])) { $model->statusAction = $map['StatusAction']; } if (isset($map['SupplierPrice'])) { $model->supplierPrice = $map['SupplierPrice']; } return $model; } }
# Contribors to oauth2client ## Maintainers * [Nathaniel Manista](https://github.com/nathanielmanistaatgoogle) * [Jon Wayne Parrott](https://github.com/jonparrott) * [Danny Hermes](https://github.com/dhermes) Previous maintainers: * [Craig Citro](https://github.com/craigcitro) * [Joe Gregorio](https://github.com/jcgregorio) ## Contributors This list is generated from git commit authors. * aalexand <aalexand@google.com> * Aaron <aaronwinter@users.noreply.github.com> * Adam Chainz <me@adamj.eu> * ade@google.com * Alexandre Vivien <alx.vivien@gmail.com> * Ali Afshar <afshar@google.com> * Andrzej Pragacz <apragacz@o2.pl> * api.nickm@gmail.com * Ben Demaree <bendemaree@gmail.com> * Bill Prin <waprin@gmail.com, waprin@google.com> * Brendan McCollam <brendan@mccoll.am, bmccollam@uchicago.edu> * Craig Citro <craigcitro@gmail.com, craigcitro@google.com> * Dan Ring <dfring@gmail.com> * Daniel Hermes <dhermes@google.com, daniel.j.hermes@gmail.com> * Danilo Akamine <danilowz@gmail.com> * daryl herzmann <akrherz@iastate.edu> * dlorenc <lorenc.d@gmail.com> * Dominik Miedziński <dominik@mdzn.pl> * dr. Kertész Csaba-Zoltán <cskertesz@gmail.com> * Dustin Farris <dustin@dustinfarris.com> * Eddie Warner <happyspace@gmail.com> * Edwin Amsler <EdwinGuy@GMail.com> * elibixby <elibixby@google.com> * Emanuele Pucciarelli <ep@acm.org> * Eric Koleda <eric.koleda@google.com> * Frederik Creemers <frederikcreemers@gmail.com> * Guido van Rossum <guido@google.com> * Harsh Vardhan <harshvd95@gmail.com> * Herr Kaste <thdz.x@gmx.net> * INADA Naoki <inada-n@klab.com> * JacobMoshenko <moshenko@google.com> * Jay Lee <jay0lee@gmail.com> * Jed Hartman <jhartman@google.com> * Jeff Terrace <jterrace@gmail.com, jterrace@google.com> * Jeffrey Sorensen <sorensenjs@users.noreply.github.com> * Jeremi Joslin <jeremi@collabspot.com> * Jin Liu <liujin@google.com> * Joe Beda <jbeda@google.com> * Joe Gregorio <jcgregorio@google.com, joe.gregorio@gmail.com> * Johan Euphrosine <proppy@google.com> * John Asmuth <jasmuth@gmail.com, jasmuth@google.com> * John Vandenberg <jayvdb@gmail.com> * Jon Wayne Parrott <jon.wayne.parrott@gmail.com, jonwayne@google.com> * Jose Alcerreca <jalc@google.com> * KCs <cskertesz@gmail.com> * Keith Maxwell <keith.maxwell@gmail.com> * Ken Payson <kpayson@google.com> * Kevin Regan <regank@google.com> * lraccomando <lraccomando@gmail.com> * Luar Roji <cyberplant@users.noreply.github.com> * Luke Blanshard <leadpipe@google.com> * Marc Cohen <marccohen@google.com> * Mark Pellegrini <markpell@google.com> * Martin Trigaux <mat@odoo.com> * Matt McDonald <mmcdonald@google.com> * Nathan Naze <nanaze@gmail.com> * Nathaniel Manista <nathaniel@google.com> * Orest Bolohan <orest@google.com> * Pat Ferate <pferate@gmail.com> * Patrick Costello <pcostello@google.com> * Rafe Kaplan <rafek@google.com> * rahulpaul@google.com <rahulpaul@google.com> * RM Saksida <rsaksida@gmail.com> * Robert Kaplow <rkaplow@google.com> * Robert Spies <wilford@google.com> * Sergei Trofimovich <siarheit@google.com> * sgomes@google.com <sgomes@google.com> * Simon Cadman <src@niftiestsoftware.com> * soltanmm <soltanmm@users.noreply.github.com> * Sébastien de Melo <sebastien.de-melo@ubicast.eu> * takuya sato <sato-taku@klab.com> * thobrla <thobrla@google.com> * Tom Miller <tom.h.miller@gmail.com> * Tony Aiuto <aiuto@google.com> * Travis Hobrla <thobrla@google.com> * Veres Lajos <vlajos@gmail.com> * Vivek Seth <vivekseth.m@gmail.com> * Éamonn McManus <eamonn@mcmanus.net>
'use strict'; module.exports = (sequelize, DataTypes) => { var Event = sequelize.define('Event', { date_start: DataTypes.DATE, date_end: DataTypes.DATE, date_create: DataTypes.DATE, title: DataTypes.TEXT, content:DataTypes.TEXT, description:DataTypes.TEXT, status:DataTypes.TEXT, url_image:DataTypes.TEXT, admin_id:DataTypes.INTEGER, admin_name: DataTypes.TEXT, amount: DataTypes.INTEGER }, {}); Event.associate = function(models) { // associations can be defined here Event.belongsTo(models.Admin,{foreignKey:"admin_id"}); }; return Event; };
# ✅ Quiz M5.03 ```{admonition} Question When fitting a decision tree regressor in scikit-learn, the predicted values at a leaf corresponds to: - a) the median of the training samples at this node - b) the mean of the training samples at this node - c) the most frequent value of the training samples at this node ``` +++ ```{admonition} Question Decision trees are capable of: - a) interpolating and extrapolating - b) only interpolating - c) only extrapolating ``` +++ ```{admonition} Question The predictions of a tree regressor corresponds to: - a) a piecewise-linear function - b) a piecewise-constant function - c) a piecewise-cubic function ```
using System; using System.Runtime.InteropServices; using jumpfs.Bookmarking; namespace jumpfs.EnvironmentAccess { public static class ShellGuesser { public static ShellType GuessShell(IEnvironment env) { //if the user has not specified the shell, try to guess it from environmental information var forcedEnv = env.GetEnvironmentVariable(EnvVariables.ShellOveride); return Enum.TryParse(typeof(ShellType), forcedEnv, true, out var shell) ? (ShellType) shell : RuntimeInformation.OSDescription.Contains("Linux") ? ShellType.Wsl : ShellType.PowerShell; } public static bool IsUnixy() => ( RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD) ); } }
import {Middleware} from './middleware' import {RequestInit} from 'node-fetch' import {get, set} from './url' import params from 'jquery-param' declare module 'node-fetch' {interface RequestInit {query?: string | {[key: string]: string | string[]}}} export const query: Middleware = (url, init, next) => { if (init && init.query) { if (typeof init.query === 'string') url = set(get(url) + '?' + init.query) else { const qs = params(init.query) url = set(get(url) + '?' + qs) } delete init.query } return next(url, init) }
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/Module/Module.h> namespace AzToolsFramework { class AzToolsFrameworkModule : public AZ::Module { public: AZ_RTTI(AzToolsFrameworkModule, "{FC9FEAC4-ADF5-426B-B26D-96A3413F3AF2}", AZ::Module); AZ_CLASS_ALLOCATOR(AzToolsFrameworkModule, AZ::OSAllocator, 0); AzToolsFrameworkModule(); ~AzToolsFrameworkModule() override = default; }; }
/** @module FilterNodeFactory */ import FilterCombinators from './filtercombinators'; import SimpleFilterNode from './simplefilternode'; import CombinedFilterNode from './combinedfilternode'; /** * FilterNodeFactory is a class containing static helper methods for * generating FilterNodes. */ export default class FilterNodeFactory { /** * Create an AND filter node, with specified children. * @param {...FilterNode} childrenNodes * @returns {FilterNode} */ static and (...childrenNodes) { return FilterNodeFactory._combine(FilterCombinators.AND, childrenNodes); } /** * Create an OR filter node, with specified children. * @param {...FilterNode} childrenNodes * @returns {FilterNode} */ static or (...childrenNodes) { return FilterNodeFactory._combine(FilterCombinators.OR, childrenNodes); } /** * Creates a combined filter node with the given combinator and children. * @param {string} combinator * @param {Array<FilterNode>} filterNodes * @returns {FilterNode} * @private */ static _combine (combinator, filterNodes) { const children = filterNodes.filter(fn => fn.getFilter().getFilterKey()); if (!children.length) { return new SimpleFilterNode(); } if (children.length === 1) { return children[0]; } return new CombinedFilterNode({ combinator: combinator, children: children }); } /** * Creates a filterNode from the given data. * @param {Object|FilterNode} filterNode * @returns {FilterNode} */ static from (filterNode = {}) { if (filterNode.children && filterNode.children.length) { return new CombinedFilterNode(filterNode); } return new SimpleFilterNode(filterNode); } }
using Pliant.Forest; using Pliant.Tokens; namespace Pliant.Tree { public sealed class TokenTreeNode : ITokenTreeNode { public TokenTreeNode(ITokenForestNode innerNode) { this.innerNode = innerNode; } public int Location => this.innerNode.Location; public IToken Token => this.innerNode.Token; public void Accept(ITreeNodeVisitor visitor) { visitor.Visit(this); } public override string ToString() { return $"{Token.TokenName}({Location}) = {Token.Value}"; } private readonly ITokenForestNode innerNode; } }
from pathlib import Path from django.test import TestCase from thumbnails import get_thumbnail import os.path # Create your tests here. class MyTests(TestCase): def test_thumbnail(self): # path = os.path.abspath('public/media/elmar.jpg') path = '/Volumes/Work/Projects/ElmarHinzDjango/public/media/Coursera' \ '-Bioinformatics-Finding-Hidden-Messages-in-DNA.pdf' tn = get_thumbnail( path, '300x300', crop='center') x = 1
module.exports = function check(str, bracketsConfig) { // if ((str.length % 2) !== 0) return false; // test 2/20 // newStrArr.forEach(el => (!bracketsConfig.flat().includes(el)) ? false : true); // test 13/20 const newConfig = bracketsConfig.map(el => el.join('')); // test 20/20 debugger; for (let i = 0; i < newConfig.length; i++) { if (str.includes(newConfig[i])) { str = str.replace(newConfig[i], ''); i = -1; console.log(str); } console.log(str); } return !str; } // console.log(check('|()|', [['(', ')'], ['|', '|']])) // -> true // console.log(check('|(|)', [['(', ')'], ['|', '|']])) // -> false // console.log(check('[(])', [['(', ')'], ['[', ']']])) // -> false
package com.pedrocosta.exchangelog.models; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; import java.util.Objects; @Entity @Table(uniqueConstraints = @UniqueConstraint( columnNames = { "base_currency_id", "quote_currency_id", "value_date" }) ) public class Exchange implements Cloneable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @OneToOne(fetch = FetchType.LAZY) private Currency baseCurrency; @OneToOne(fetch = FetchType.LAZY) private Currency quoteCurrency; @Column(name = "value_date") private Date valueDate; private BigDecimal rate; public Exchange() { this(null, null, BigDecimal.ZERO, null); } public Exchange(Currency base, Currency quote, BigDecimal rate, Date date) { setBaseCurrency(base); setQuoteCurrency(quote); setRate(rate); setValueDate(date); } public long getId() { return id; } public Exchange setId(long id) { this.id = id; return this; } public Currency getBaseCurrency() { return baseCurrency; } public Exchange setBaseCurrency(Currency baseCurrency) { this.baseCurrency = baseCurrency; return this; } public Currency getQuoteCurrency() { return quoteCurrency; } public Exchange setQuoteCurrency(Currency quoteCurrency) { this.quoteCurrency = quoteCurrency; return this; } public Date getValueDate() { return valueDate; } public Exchange setValueDate(Date valueDate) { this.valueDate = valueDate; return this; } public BigDecimal getRate() { return rate; } public Exchange setRate(BigDecimal rate) { this.rate = rate; return this; } public Exchange setRate(Double rate) { return setRate(BigDecimal.valueOf(rate)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Exchange exchange = (Exchange) o; return id == exchange.id && baseCurrency.getCode().equals(exchange.baseCurrency.getCode()) && quoteCurrency.getCode().equals(exchange.quoteCurrency.getCode()) && valueDate.equals(exchange.valueDate) && rate.equals(exchange.rate); } @Override public int hashCode() { return Objects.hash(id, baseCurrency, quoteCurrency, valueDate, rate); } @Override public Exchange clone() throws CloneNotSupportedException { return(Exchange) super.clone(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Exchange{") .append("id=").append(id) .append(", baseCurrency="); if (baseCurrency != null) builder.append(baseCurrency.getCode()); builder.append(", baseCurrency="); if (quoteCurrency != null) builder.append(quoteCurrency.getCode()); builder.append(", valueDate=").append(valueDate) .append(", rate=").append(rate) .append('}'); return builder.toString(); } }
package com.sitamadex11.CovidHelp.adapter import android.content.Context import android.content.Intent import android.graphics.Color import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.google.android.material.button.MaterialButton import com.sitamadex11.CovidHelp.R import com.sitamadex11.CovidHelp.model.CenterItem import java.util.* class VaccineCenterListAdapter(val context: Context) : RecyclerView.Adapter<VaccineCenterListAdapter.VaccineCenterViewHolder>() { private val centerList = ArrayList<CenterItem>() inner class VaccineCenterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val txtCenterName: TextView = itemView.findViewById<TextView>(R.id.txtCenterName) val txtCenterAddress: TextView = itemView.findViewById<TextView>(R.id.txtCenterAddress) val txtVaccineName: TextView = itemView.findViewById<TextView>(R.id.txtVaccineName) val txtVaccineFee: TextView = itemView.findViewById<TextView>(R.id.txtVaccineFee) val txtAgeLimit: TextView = itemView.findViewById<TextView>(R.id.txtAgeLimit) val txtDose1: TextView = itemView.findViewById<TextView>(R.id.txtDose1) val txtDose2: TextView = itemView.findViewById<TextView>(R.id.txtDose2) val txtSlot1: TextView = itemView.findViewById<TextView>(R.id.txtSlot1) val txtSlot2: TextView = itemView.findViewById<TextView>(R.id.txtSlot2) val txtSlot3: TextView = itemView.findViewById<TextView>(R.id.txtSlot3) val txtSlot4: TextView = itemView.findViewById<TextView>(R.id.txtSlot4) val txtPinCode: TextView = itemView.findViewById<TextView>(R.id.txtPinCode) val btnBookVac: MaterialButton = itemView.findViewById(R.id.btnBookVac) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VaccineCenterViewHolder { return VaccineCenterViewHolder( LayoutInflater.from(context).inflate(R.layout.vaccine_center_listitem, parent, false) ) } override fun onBindViewHolder(holder: VaccineCenterViewHolder, position: Int) { holder.txtCenterName.text = centerList[position].name holder.txtCenterAddress.text = centerList[position].address holder.txtVaccineName.text = centerList[position].sessions[0].vaccine holder.txtVaccineFee.text = centerList[position].feeType holder.txtAgeLimit.text = "${centerList[position].sessions[0].minAgeLimit}+" if (centerList[position].sessions[0].dose1.toString() == "0") { holder.txtDose1.text = "booked" holder.txtDose1.setTextColor(Color.parseColor("#FF0000")) } else { holder.txtDose1.text = centerList[position].sessions[0].dose1.toString() holder.txtDose1.setTextColor(Color.parseColor("#2e7d32")) } if (centerList[position].sessions[0].dose2.toString() == "0") { holder.txtDose2.text = "booked" holder.txtDose2.setTextColor(Color.parseColor("#FF0000")) } else { holder.txtDose2.text = centerList[position].sessions[0].dose2.toString() holder.txtDose2.setTextColor(Color.parseColor("#2e7d32")) } // holder.txtDose2.text = centerList[position].sessions[0].dose2.toString() val slotSize = centerList[position].sessions[0].slots.size when (slotSize) { 1 -> { holder.txtSlot1.text = centerList[position].sessions[0].slots[0] holder.txtSlot2.text = "No Slot Found" holder.txtSlot3.text = "No Slot Found" holder.txtSlot4.text = "No Slot Found" } 2 -> { holder.txtSlot1.text = centerList[position].sessions[0].slots[0] holder.txtSlot2.text = centerList[position].sessions[0].slots[1] holder.txtSlot3.text = "No Slot Found" holder.txtSlot4.text = "No Slot Found" } 3 -> { holder.txtSlot1.text = centerList[position].sessions[0].slots[0] holder.txtSlot2.text = centerList[position].sessions[0].slots[1] holder.txtSlot3.text = centerList[position].sessions[0].slots[2] holder.txtSlot4.text = "No Slot Found" } 4 -> { holder.txtSlot1.text = centerList[position].sessions[0].slots[0] holder.txtSlot2.text = centerList[position].sessions[0].slots[1] holder.txtSlot3.text = centerList[position].sessions[0].slots[2] holder.txtSlot4.text = centerList[position].sessions[0].slots[3] } } holder.txtPinCode.text = centerList[position].pinCode.toString() holder.btnBookVac.setOnClickListener { if (centerList[position].sessions[0].dose2.toString() == "0" && centerList[position].sessions[0].dose1.toString() == "0" ) { Toast.makeText(context, "Sorry! No slot Available here", Toast.LENGTH_SHORT).show() } else { val url = "https://selfregistration.cowin.gov.in/" val intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse(url) context.startActivity(intent) } } } override fun getItemCount(): Int { return centerList.size } fun updateList(newList: ArrayList<CenterItem>) { centerList.clear() centerList.addAll(newList) notifyDataSetChanged() } }
package com.naram.party_project.chattingModel data class Message( var uid: String, var name: String? = null, var picture: String? = null, var message: String, var timestamp: Any )
# frozen_string_literal: true require 'renderful/error/base' require 'renderful/error/entry_not_found_error' require 'renderful/error/no_component_error' require 'renderful/cache/base' require 'renderful/cache/redis' require 'renderful/cache/null' require 'renderful/content_entry' require 'renderful/provider/base' require 'renderful/provider/contentful' require 'renderful/provider/prismic' require 'renderful/client' require 'renderful/component/base' require 'renderful/version' module Renderful end
// // Author: // Aaron Bockover <abock@microsoft.com> // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Interactive.Client; using Xamarin.Interactive.CodeAnalysis.Events; using Xamarin.Interactive.CodeAnalysis.Models; using Xamarin.Interactive.I18N; using Xamarin.Interactive.Logging; using Xamarin.Interactive.Protocol; using Xamarin.Interactive.Representations; using Xamarin.Interactive.Representations.Reflection; namespace Xamarin.Interactive.CodeAnalysis.Evaluating { public sealed class EvaluationService : IEvaluationService { const string TAG = nameof (EvaluationService); sealed class Inhibitor : IDisposable { int inhibitions; public bool IsInhibited => inhibitions > 0; public IDisposable Inhibit () { inhibitions++; return this; } public void Dispose () => inhibitions--; } internal sealed class CodeCellState { public CodeCellId CodeCellId { get; } public IReadOnlyList<Diagnostic> Diagnostics { get; set; } = Array.Empty<Diagnostic> (); public bool IsDirty { get; set; } public bool AgentTerminatedWhileEvaluating { get; set; } public int EvaluationCount { get; set; } public CodeCellState (CodeCellId codeCellId) => CodeCellId = codeCellId; public bool IsEvaluationCandidate => IsDirty || EvaluationCount == 0; } internal sealed class EvaluationModel { public bool ShouldResetAgentState { get; set; } public bool ShouldMaybeStartNewCodeCell { get; set; } public List<CodeCellState> CellsToEvaluate { get; } = new List<CodeCellState> (); } readonly object stateChangeLock = new object (); readonly Inhibitor evaluationInhibitor = new Inhibitor (); readonly IWorkspaceService workspace; EvaluationEnvironment evaluationEnvironment; IEvaluationContextManager evaluationContextManager; IDisposable evaluationContextManagerEventsSubscription; readonly Dictionary<CodeCellId, CodeCellState> cellStates = new Dictionary<CodeCellId, CodeCellState> (); CodeCellId nugetReferenceCellId; public TargetCompilationConfiguration TargetCompilationConfiguration => workspace .Configuration .CompilationConfiguration; readonly Observable<ICodeCellEvent> events = new Observable<ICodeCellEvent> (); public IObservable<ICodeCellEvent> Events => events; public bool CanEvaluate => !evaluationInhibitor.IsInhibited; public EvaluationService ( IWorkspaceService workspace, EvaluationEnvironment evaluationEnvironment, IEvaluationContextManager evaluationContextManager = null) { this.workspace = workspace ?? throw new ArgumentNullException (nameof (workspace)); NotifyEvaluationEnvironmentChanged (evaluationEnvironment); NotifyEvaluationContextManagerChanged (evaluationContextManager); Events.Subscribe (new Observer<ICodeCellEvent> (OnCodeCellEvent)); } internal void NotifyEvaluationEnvironmentChanged (EvaluationEnvironment evaluationEnvironment) { lock (stateChangeLock) this.evaluationEnvironment = evaluationEnvironment; } public void NotifyEvaluationContextManagerChanged (IEvaluationContextManager evaluationContextManager) { lock (stateChangeLock) { evaluationContextManagerEventsSubscription?.Dispose (); evaluationContextManagerEventsSubscription = null; this.evaluationContextManager = evaluationContextManager; evaluationContextManagerEventsSubscription = evaluationContextManager ?.Events ?.Subscribe (events.Observers); } } #region IEvaluationService public void Dispose () { evaluationInhibitor.Dispose (); } public void OutdateAllCodeCells () { } public IDisposable InhibitEvaluate () => evaluationInhibitor.Inhibit (); Task IEvaluationService.EvaluateAsync (string input, CancellationToken cancellationToken) => throw new NotImplementedException (); Task IEvaluationService.LoadWorkbookDependencyAsync (string dependency, CancellationToken cancellationToken) => throw new NotImplementedException (); public Task EvaluateAllAsync (CancellationToken cancellationToken = default) => EvaluateAsync (evaluateAll: true, cancellationToken: cancellationToken); public async Task<bool> AddTopLevelReferencesAsync ( IReadOnlyList<string> references, CancellationToken cancellationToken = default) { if (references == null || references.Count == 0) return false; var buffer = new StringBuilder (); if (nugetReferenceCellId == default) { var firstCodeCellId = workspace .GetTopologicallySortedCellIds () .FirstOrDefault (); nugetReferenceCellId = await InsertCodeCellAsync ( string.Empty, firstCodeCellId, true, cancellationToken); } else { buffer.Append (await workspace.GetCellBufferAsync ( nugetReferenceCellId, cancellationToken)); } // TODO: Prevent dupes. Return false if no changes made foreach (var reference in references) { if (buffer.Length > 0) buffer.Append ("\n"); buffer .Append ("#r \"") .Append (reference) .Append ("\""); } workspace.SetCellBuffer (nugetReferenceCellId, buffer.ToString ()); return true; } #endregion internal Task<ImmutableList<CodeCellState>> GetAllCodeCellsAsync ( CancellationToken cancellationToken = default) => Task.FromResult (workspace .GetTopologicallySortedCellIds () .Select (id => cellStates [id]) .ToImmutableList ()); public Task<CodeCellId> InsertCodeCellAsync ( string initialBuffer = null, CodeCellId relativeToCodeCellId = default, bool insertBefore = false, CancellationToken cancellationToken = default) { var cells = workspace.GetTopologicallySortedCellIds (); var insertionIndex = cells.Count; if (relativeToCodeCellId != CodeCellId.Empty) { insertionIndex = cells.FindIndex (id => id == relativeToCodeCellId); if (insertionIndex < 0) throw new ArgumentException ( $"CodeCellId not found: {relativeToCodeCellId}", nameof (relativeToCodeCellId)); if (!insertBefore) insertionIndex++; } var previousCodeCellId = CodeCellId.Empty; var nextCodeCellId = CodeCellId.Empty; if (insertionIndex > 0) previousCodeCellId = cells [insertionIndex - 1]; if (insertionIndex < cells.Count) nextCodeCellId = cells [insertionIndex]; var codeCellId = workspace.InsertCell ( previousCodeCellId, nextCodeCellId); workspace.SetCellBuffer ( codeCellId, initialBuffer); var codeCellState = new CodeCellState ( codeCellId); cellStates.Add (codeCellId, codeCellState); return Task.FromResult (codeCellId); } public async Task<CodeCellUpdatedEvent> UpdateCodeCellAsync ( CodeCellId codeCellId, string buffer, CancellationToken cancellationToken = default) { workspace.SetCellBuffer (codeCellId, buffer); var cell = cellStates [codeCellId]; cell.IsDirty = true; return new CodeCellUpdatedEvent ( cell.CodeCellId, workspace.IsCellComplete (cell.CodeCellId), await workspace.GetCellDiagnosticsAsync ( cell.CodeCellId, cancellationToken)); } public Task RemoveCodeCellAsync ( CodeCellId codeCellId, CancellationToken cancellationToken = default) { var cells = workspace.GetTopologicallySortedCellIds (); var index = cells.IndexOf (codeCellId); var nextCodeCellId = index < cells.Count - 1 ? cells [index + 1] : default; workspace.RemoveCell ( codeCellId, nextCodeCellId); cellStates.Remove (codeCellId); return Task.CompletedTask; } internal async Task<EvaluationModel> GetEvaluationModelAsync ( CodeCellId targetCodeCellId = default, bool evaluateAll = false, CancellationToken cancellationToken = default) { var model = new EvaluationModel (); var cells = await GetAllCodeCellsAsync (); var targetCellIndex = evaluateAll ? -1 : cells.FindIndex (cell => cell.CodeCellId == targetCodeCellId); // we're either evaluating all cells head to tail or we failed to // find the target cell in the list; either way we're bailing early if (targetCellIndex < 0) { if (!evaluateAll && targetCodeCellId != default) throw new KeyNotFoundException ( $"{nameof (targetCodeCellId)} '{targetCodeCellId}' not found"); model.ShouldResetAgentState = true; model.CellsToEvaluate.AddRange (cells); return model; } // otherwise, starting with our target cell and working backwards to the, // head of the cell list figure out cells that need to be evaluated. for (var i = targetCellIndex; i >= 0; i--) { var cell = cells [i]; var isTargetCell = targetCellIndex == i; var shouldEvaluate = isTargetCell || cell.IsEvaluationCandidate; if (!shouldEvaluate && await workspace.IsCellOutdatedAsync (cell.CodeCellId, cancellationToken)) shouldEvaluate = true; if (shouldEvaluate) { model.ShouldResetAgentState |= i == 0; model.CellsToEvaluate.Insert (0, cell); } } // now look at all cells after our target cell; if any of them have been // evaluated before, we also want to re-evaluate those since they may // depend on state in previous cells which will become invalidated. for (var i = targetCellIndex + 1; i < cells.Count; i++) { var cell = cells [i]; // if a cell was previously run but resulted in an agent termination, // we do not want to automatically re-run that cell; the user must // explicitly re-run terminated cells (which would be handled in the // target->head walk above). if (cell.AgentTerminatedWhileEvaluating) break; // otherwise if we've evaluated this cell before, we should do so again if (cell.EvaluationCount > 0) model.CellsToEvaluate.Add (cell); // FIXME: this is where we did codeCellState.View.IsOutdated = true; // but I do not know why we did that yet. Let this be a clue to future // self. -abock, 2018-03-07 } model.ShouldMaybeStartNewCodeCell = targetCellIndex == cells.Count - 1; return model; } public async Task<CodeCellEvaluationFinishedEvent> EvaluateAsync ( CodeCellId targetCodeCellId = default, bool evaluateAll = false, CancellationToken cancellationToken = default) { var evaluationModel = await GetEvaluationModelAsync ( targetCodeCellId, evaluateAll, cancellationToken); if (evaluationModel.ShouldResetAgentState) await evaluationContextManager.ResetStateAsync ( TargetCompilationConfiguration.EvaluationContextId, cancellationToken); CodeCellEvaluationFinishedEvent lastCellFinishedEvent = default; foreach (var evaluatableCodeCell in evaluationModel.CellsToEvaluate) { events.Observers.OnNext ( new CodeCellEvaluationStartedEvent ( evaluatableCodeCell.CodeCellId)); var status = await CoreEvaluateCodeCellAsync (evaluatableCodeCell); lastCellFinishedEvent = new CodeCellEvaluationFinishedEvent ( evaluatableCodeCell.CodeCellId, status, evaluationModel.ShouldMaybeStartNewCodeCell && status == EvaluationStatus.Success && evaluatableCodeCell.CodeCellId == targetCodeCellId, evaluatableCodeCell.Diagnostics); events.Observers.OnNext (lastCellFinishedEvent); if (status != EvaluationStatus.Success) NotifyEvaluationComplete (evaluatableCodeCell.CodeCellId, status); switch (status) { case EvaluationStatus.ErrorDiagnostic: case EvaluationStatus.Disconnected: return lastCellFinishedEvent; } } return lastCellFinishedEvent; } readonly ConcurrentDictionary<CodeCellId, TaskCompletionSource<EvaluationStatus>> evaluationAwaiters = new ConcurrentDictionary<CodeCellId, TaskCompletionSource<EvaluationStatus>> (); void OnCodeCellEvent (ICodeCellEvent evnt) { if (evnt is Evaluation evaluation) NotifyEvaluationComplete (evaluation.CodeCellId, evaluation.Status); } public void NotifyEvaluationComplete (CodeCellId targetCodeCellId, EvaluationStatus status) { if (evaluationAwaiters.TryRemove (targetCodeCellId, out var awaiter)) awaiter.SetResult (status); } async Task<EvaluationStatus> CoreEvaluateCodeCellAsync ( CodeCellState codeCellState, CancellationToken cancellationToken = default) { if (evaluationContextManager == null) { codeCellState.Diagnostics = new [] { new Diagnostic ( DiagnosticSeverity.Error, "Cannot evaluate: not connected to agent.") }; return EvaluationStatus.Disconnected; } var evaluationCompletion = new TaskCompletionSource<EvaluationStatus> (); if (!evaluationAwaiters.TryAdd (codeCellState.CodeCellId, evaluationCompletion)) throw new Exception ($"This is already being evaluated: {codeCellState.CodeCellId}"); Compilation compilation = null; compilation = await workspace.EmitCellCompilationAsync ( codeCellState.CodeCellId, evaluationEnvironment, cancellationToken); codeCellState.Diagnostics = await workspace.GetCellDiagnosticsAsync ( codeCellState.CodeCellId, cancellationToken); if (codeCellState.Diagnostics.Any (d => d.Severity == DiagnosticSeverity.Error)) return EvaluationStatus.ErrorDiagnostic; var integrationAssemblies = compilation .References .Where (ra => ra.HasIntegration) .ToArray (); try { if (integrationAssemblies.Length > 0) await evaluationContextManager.LoadAssembliesAsync ( TargetCompilationConfiguration.EvaluationContextId, integrationAssemblies, cancellationToken); await evaluationContextManager.EvaluateAsync ( TargetCompilationConfiguration.EvaluationContextId, compilation, cancellationToken); } catch (Exception e) { Log.Error (TAG, "marking agent as terminated", e); codeCellState.AgentTerminatedWhileEvaluating = true; codeCellState.Diagnostics = new [] { new Diagnostic ( DiagnosticSeverity.Error, Catalog.GetString ( "The application terminated during evaluation of this cell. " + "Run this cell manually to try again.")) }; } var evaluationStatus = await evaluationCompletion.Task; if (codeCellState.AgentTerminatedWhileEvaluating) evaluationStatus = EvaluationStatus.Disconnected; codeCellState.IsDirty = false; codeCellState.EvaluationCount++; return evaluationStatus; } } }
{- Sumar el triple del primero al segundo > sumarNumeroAlTriple 3 2 sumarNumeroAlTriple a b = ((+) . (*3)) a b 1) Primero hace (*3) a, la función (*) sólo toma dos argumentos uno de los argumentos es "3" porque esta dentro del () y el otro argumento es a, y devuelve el producto de 3*a 2) Segundo hace (+) c b la función suma sólo toma dos argumentos la "c" es el producto de (3*a) y el producto de 3*a, lo suma con b *************************************************************************** Sumar el triple del primero al segundo y dividir el resultado a la mitad > laMitadDeSumarTriple 2 15 laMitaDeSumarTriple a = (2/) . (((+) . (*3))) a (2/) . (((+) . (*3))) a --> 3 funciones (*3) (+) y (/2), 2 argumentos (a,b) (*3) a = c --> multiplica el primer argumento (a) por 3 (+)c b = d --> al resultado anterior (c) le suma el segundo argumento (b) (/2) d = resultado --> al resultado anterior (d) lo divide por 2 # Nota: Si le hubiera pasado el segundo argumento (b) fallaría, porque seguido del (/2) está el punto de "composición", por lo que espera una función (*3), no un valor "10". 1) Primero hace (3*a) la función (*) sólo toma dos argumentos, pero (*3) toma sólo un argumento ya que el 3 ya está dentro de la función, el segundo argumento será "a", y devuelve el producto de 3*a 2) segundo hace (+) c b la "c" es el producto de la operación anterior (3*a) la b es el argumento que no aparece porque se aplica parcialmente (reduciendo argumentos) y devuelve el resultaod de sumar c+b 3) tercero hace (/2) d "d" es el resultado de la sumatoria de la función anterior la función (/) acepta dos argumentos, el primero ya está agregado en los () que es el 2 el segundo es "d" que era el resultado de la suma anterior -} doble = (*2) triple = (*3) sumar = (+) --sumarNumeroAlTriple a b = ((+) . (*3)) a b --sumarNumeroAlTriple a b = (sumar . triple) a b --sumarNumeroAlTriple = ((+) . (*3)) sumarNumeroAlTriple = (sumar . triple) dobleDelTriple numero = (doble . triple) numero laMitaDeSumarTriple a = (2/) . (((+) . (*3))) a lista = [1,2,3] main = do print(sumarNumeroAlTriple 3 2) print(dobleDelTriple 2) print(laMitaDeSumarTriple 5 15)
package de.rdnp.preflight.flightplanner; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class TripRepositoryTestDataController { private static final String PUT_NEW_URL = "http://localhost:8080/trips/9223372036854775807"; private RestTemplate restTemplate = new RestTemplate(); @Autowired private TripRepository repository; @Autowired private FlightRepository flightRepository; @CrossOrigin() @RequestMapping(path = "/setDefaultTestDataForTrips", method = RequestMethod.POST) public List<Trip> createDefaultTestDataForTrips() { List<Trip> testData = new ArrayList<>(); Trip tripOne = new Trip(); Flight flight = flightRepository.findByName("Flight.to.Schwaebisch.Hall").get(0); tripOne.setFlightId(flight.getId()); tripOne.setDateOfFlight("2019-12-18"); tripOne.setEstimatedOffBlockTime("10:10"); tripOne.setAircraftRegistration("DESAE"); tripOne.setAircraftType("C172"); tripOne.setSegments(createFirstSampleTripToSchwaebischHall()); testData.add(tripOne); restTemplate.put(PUT_NEW_URL, tripOne); Trip tripTwo = new Trip(); tripTwo.setFlightId(flight.getId()); tripTwo.setDateOfFlight("2019-12-19"); tripTwo.setEstimatedOffBlockTime("06:50"); tripTwo.setAircraftRegistration("DESAC"); tripTwo.setAircraftType("C172"); tripTwo.setSegments(createSecondSampleTripToSchwaebischHall()); testData.add(tripTwo); restTemplate.put(PUT_NEW_URL, tripTwo); return testData; } private List<TripSegment> createFirstSampleTripToSchwaebischHall() { List<TripSegment> testTrip = new ArrayList<>(); testTrip.add(createSegmentToLBU(testTrip)); testTrip.add(createSegmentToDKB(testTrip)); testTrip.add(createSegmentToEDTY(testTrip)); return testTrip; } private List<TripSegment> createSecondSampleTripToSchwaebischHall() { List<TripSegment> testTrip = new ArrayList<>(); TripSegment createSegmentToLBU = createSegmentToLBU(testTrip); createSegmentToLBU.setAltitude(5000); testTrip.add(createSegmentToLBU); TripSegment createSegmentToDKB = createSegmentToDKB(testTrip); createSegmentToDKB.setChildren(Collections.emptyList()); createSegmentToDKB.setAltitude(5000); testTrip.add(createSegmentToDKB); TripSegment createSegmentToEDTY = createSegmentToEDTY(testTrip); createSegmentToEDTY.setAltitude(5000); testTrip.add(createSegmentToEDTY); return testTrip; } private TripSegment createSegmentToLBU(List<TripSegment> testTrip) { TripSegment newSegment = new TripSegment(); newSegment.setVariation(2); newSegment.setHourlyFuelConsumptionRate(12); newSegment.setWindDirection(350); newSegment.setWindSpeed(10); newSegment.setTrueAirspeed(79); newSegment.setAltitude(3300); newSegment.setMagneticCourse(58); newSegment.setMagneticHeading(51); newSegment.setGroundSpeed(74); newSegment.setTimeInMinutes(4); newSegment.setFuel(0.8); newSegment.setChildren(Collections.emptyList()); return newSegment; } private TripSegment createSegmentToDKB(List<TripSegment> testTrip) { TripSegment newSegment = new TripSegment(); newSegment.setVariation(2); newSegment.setHourlyFuelConsumptionRate(9.8); newSegment.setWindDirection(350); newSegment.setWindSpeed(10); newSegment.setTrueAirspeed(117); newSegment.setAltitude(3300); newSegment.setMagneticCourse(68); newSegment.setMagneticHeading(63); newSegment.setGroundSpeed(114); newSegment.setTimeInMinutes(19); newSegment.setFuel(3.0); List<TripSegment> children = new ArrayList<TripSegment>(); TripSegment childSegment = new TripSegment(); childSegment.setVariation(2); childSegment.setHourlyFuelConsumptionRate(12); childSegment.setWindDirection(350); childSegment.setWindSpeed(10); childSegment.setTrueAirspeed(79); childSegment.setAltitude(3300); childSegment.setMagneticCourse(68); childSegment.setMagneticHeading(61); childSegment.setGroundSpeed(76); childSegment.setTimeInMinutes(2); childSegment.setFuel(0.4); children.add(childSegment); newSegment.setChildren(children); return newSegment; } private TripSegment createSegmentToEDTY(List<TripSegment> testTrip) { TripSegment newSegment = new TripSegment(); newSegment.setVariation(2); newSegment.setHourlyFuelConsumptionRate(9.8); newSegment.setWindDirection(350); newSegment.setWindSpeed(10); newSegment.setTrueAirspeed(117); newSegment.setAltitude(3300); newSegment.setMagneticCourse(264); newSegment.setMagneticHeading(269); newSegment.setGroundSpeed(116); newSegment.setTimeInMinutes(9); newSegment.setFuel(1.5); newSegment.setChildren(Collections.emptyList()); return newSegment; } @CrossOrigin() @RequestMapping(path = "/deleteAllTestDataForTrips", method = RequestMethod.POST) public void deleteAllTripTestData() { repository.deleteAll(); System.out.println("All route-segment test data purged."); } }
SELECT date_format(sec_to_time(trfh_duree*60),'%Hh%i') AS 'Durée Max', concat(trfh_tarif,' €') AS 'tarif' FROM TARIF_HORAIRE
-- ALTER TABLE `services_package` ADD `all_services` tinyint default 0; ALTER TABLE `users` MODIFY `comment` text; --//@UNDO ALTER TABLE `services_package` DROP `all_services`; --
<?php namespace App\Http\Controllers; use App\Category; use App\ToDoList; use Illuminate\Http\Request; use App\Http\Requests; class ToDoListController extends Controller { // Basic Index Page For Showing ToDoList Items public function index() { // $list = ToDoList::find(2); // $category = Category::find(1); // // if (!$list->categories->contains($category)) // { // $list->categories()->save($category); // } // $category1 = new Category; // $category1->name='Vacation'; // $category2 = new Category; // $category2->name='Tropical'; // $category3 = new Category; // $category3->name='Leisure'; // // $categories = [$category1,$category2,$category3]; // $list->categories()->saveMany($categories); // $list->categories()->save($category); $todolist = ToDoList::all(); return view('ToDoList.index',['todolists'=>$todolist]); } }
from random import randint num_updates = 0 maximum = randint(1, 100) print("{}".format(maximum)) for i in range(99): new_num = randint(1, 100) if new_num > maximum: maximum = new_num num_updates += 1 print("{} (atualizado)".format(new_num)) else: print("{}".format(new_num)) print("O valor máximo encontrado foi {}".format(maximum)) print("O número máximo de vezes que o maior valor foi " "atualizado foi {} vezes." .format(num_updates))
// Copyright 2020 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fxcodec/gif/gif_progressive_decoder.h" #include "core/fxcodec/cfx_codec_memory.h" #include "core/fxcodec/gif/gif_decoder.h" namespace fxcodec { // static GifProgressiveDecoder* GifProgressiveDecoder::GetInstance() { static pdfium::base::NoDestructor<GifProgressiveDecoder> s; return s.get(); } GifProgressiveDecoder::GifProgressiveDecoder() = default; GifProgressiveDecoder::~GifProgressiveDecoder() = default; FX_FILESIZE GifProgressiveDecoder::GetAvailInput(Context* context) const { return GifDecoder::GetAvailInput(context); } bool GifProgressiveDecoder::Input(Context* context, RetainPtr<CFX_CodecMemory> codec_memory, CFX_DIBAttribute* pAttribute) { return GifDecoder::Input(context, codec_memory, pAttribute); } } // namespace fxcodec
package org.sxchinacourt.util; import android.util.Log; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by 殇冰无恨 on 2018/3/13. */ public class TimeUtils { /** * 获取当前时间 * @return */ public static String getNowTime(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date = new Date(System.currentTimeMillis()); return simpleDateFormat.format(date); } /** * 获取时间戳 * * @return 获取时间戳 */ public static String getTimeString() { SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日"); Calendar calendar = Calendar.getInstance(); return df.format(calendar.getTime()); } /** * 时间转换为时间戳 * @param time:需要转换的时间 * @return */ public static String dateToStamp(String time) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = simpleDateFormat.parse(time); } catch (ParseException e) { e.printStackTrace(); } long ts = date.getTime(); return String.valueOf(ts); } /** * 时间戳转换为字符串 * @param time:时间戳 * @return */ public static String times(String time) { SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日"); @SuppressWarnings("unused") long lcc = Long.valueOf(time); int i = Integer.parseInt(time); String times = sdr.format(new Date(i * 1000L)); return times; } /** *获取距现在某一小时的时刻 * @param hour hour=-1为上一个小时,hour=1为下一个小时 * @return */ public static String getLongTime(int hour){ Calendar c = Calendar.getInstance(); // 当时的日期和时间 int h; // 需要更改的小时 h = c.get(Calendar.HOUR_OF_DAY) - hour; c.set(Calendar.HOUR_OF_DAY, h); SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Log.v("time",df.format(c.getTime())); return df.format(c.getTime()); } /** * 比较时间大小 * @param str1:要比较的时间 * @param str2:要比较的时间 * @return */ public static boolean isDateOneBigger(String str1, String str2) { boolean isBigger = false; SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Date dt1 = null; Date dt2 = null; try { dt1 = sdf.parse(str1); dt2 = sdf.parse(str2); } catch (ParseException e) { e.printStackTrace(); } if (dt1.getTime() > dt2.getTime()) { isBigger = true; } else if (dt1.getTime() < dt2.getTime()) { isBigger = false; } return isBigger; } }
/* * Copyright 2018 Zhang Di * * 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 org.dizhang.pubg import java.time.ZoneId import java.util.Date import org.dizhang.pubg.Stat.Counter import PlayerStates._ import org.slf4j.{Logger, LoggerFactory} /** * elements will be aggregated to windows * windowSize unit is second * */ class PlayerStates(windows: Int, windowSize: Int, len1: Int, len2: Int) extends Serializable { val logger: Logger = LoggerFactory.getLogger(getClass) var fakeWaterMark: Long = 0L var earliest: Long = 0L var latest: Long = 0L var lastIndex: Int = 0 var current: Array[Int] = zero(len) var history: Array[Array[Int]] = zero(windows, len) val counter: Counter = new Counter(len) def len = len1 + len2 def earliestIndex: Int = (lastIndex + windows + 1 - occupiedSize)%windows def occupiedSize: Int = ((latest - earliest)/(windowSize * 1000) + 1).toInt def emitElement(): Array[Int] = current /** * add element to history * update the state * */ def addElement(cnt: Array[Int], time: Long, first: Boolean): Unit = { if (time >= earliest) { fakeWaterMark = math.max(fakeWaterMark, time) logger.debug(s"time: ${time.utc}, earliest: ${earliest.utc}") /** data to be inserted */ val enriched: Array[Int] = if (first) cnt ++ zero(len2) else zero(len1) ++ cnt val rawIdx = ((time - earliest)/(windowSize * 1000)).toInt logger.debug(s"rawIdx: $rawIdx, occupiedSize: $occupiedSize, windows: $windows") val currentTime = time/(windowSize * 1000) * (windowSize * 1000) logger.debug(s"currentTime (slot): $currentTime ${currentTime.utc}") if (rawIdx < occupiedSize + windows - 1) { /** if fall in range or override part of old data */ for (i <- 0 to (rawIdx - occupiedSize)) { val idx = (lastIndex + 1 + i)%windows current = counter.sub(current, history(idx)) history(idx) = zero(len) } current = counter.add(current, enriched) val idx = (earliestIndex + rawIdx)%windows logger.debug(s"idx: $idx") history(idx) = counter.add(history(idx), enriched) logger.debug(s"overlap idx?: ${currentTime - (windowSize.toLong * (windows - 1) * 1000)}") earliest = math.max(earliest, currentTime - (windowSize.toLong * (windows - 1) * 1000)) if (currentTime > latest) { latest = currentTime lastIndex = idx } } else { /** throw away old data */ history = zero(windows, len) history(0) = enriched.clone() current = enriched.clone() earliest = currentTime latest = earliest lastIndex = 0 } } else { logger.debug(s"time ${time.utc} < ${earliest.utc}") } } def pprint(): String = { s""" |windows: $windows |windowSize: $windowSize |earliest: ${new Date(earliest)} |latest: ${new Date(latest)} |earliestIndex: ${earliestIndex} |lastIndex: $lastIndex |occupiedSize: $occupiedSize |current: ${current.mkString(",")} |history: |${history.zipWithIndex.map{case (r, i) => s"\t$i: ${r.mkString(",")}"}.mkString("\n")} |""".stripMargin } } object PlayerStates { private def zero(size: Int): Array[Int] = Array.fill(size)(0) private def zero(rows: Int, cols: Int): Array[Array[Int]] = Array.fill(rows)(Array.fill(cols)(0)) implicit class utctime(val time: Long) extends AnyVal { def utc = new Date(time).toInstant.atZone(ZoneId.of("UTC")).toString } }
<?php namespace Kartenmacherei\RestFramework\UnitTests\Request; use Kartenmacherei\RestFramework\Request\Pattern; use PHPUnit\Framework\TestCase; /** * @covers \Kartenmacherei\RestFramework\Request\Pattern */ class PatternTest extends TestCase { /** * @dataProvider patternValueProvider * * @param string $patternValue * @param string $expectedString */ public function testAsString($patternValue, $expectedString) { $pattern = new Pattern($patternValue); $this->assertSame($expectedString, $pattern->asString()); } /** * @return array */ public static function patternValueProvider() { return [ ['foo/bar', '/foo\/bar/'], ['/baskets/\w+$', '/\/baskets\/\w+$/'] ]; } }